|
1 | | -import MultiSelect, { type MultiSelectEvents } from '$lib' |
| 1 | +import MultiSelect, { type MultiSelectEvents, type Option } from '$lib' |
2 | 2 | import { beforeEach, describe, expect, test, vi } from 'vitest' |
| 3 | +import Test2WayBind from './Test2WayBind.svelte' |
3 | 4 |
|
4 | 5 | beforeEach(() => { |
5 | 6 | document.body.innerHTML = `` |
@@ -536,4 +537,56 @@ describe(`MultiSelect`, () => { |
536 | 537 | expect(input.value).toBe(expected) |
537 | 538 | } |
538 | 539 | ) |
| 540 | + |
| 541 | + test(`2-way bind selected`, async () => { |
| 542 | + let selected: Option[] |
| 543 | + const binder = new Test2WayBind({ |
| 544 | + target: document.body, |
| 545 | + }) |
| 546 | + binder.$on(`selected-changed`, (e: CustomEvent) => { |
| 547 | + selected = e.detail |
| 548 | + }) |
| 549 | + |
| 550 | + // test internal changes bind outwards |
| 551 | + for (const _ of [1, 2]) { |
| 552 | + const li = doc_query(`ul.options li`) |
| 553 | + li.dispatchEvent(new MouseEvent(`mouseup`)) |
| 554 | + await sleep() |
| 555 | + } |
| 556 | + |
| 557 | + expect(selected).toEqual([1, 2]) |
| 558 | + |
| 559 | + // test external changes bind inwards |
| 560 | + selected = [3] |
| 561 | + binder.$set({ selected }) |
| 562 | + await sleep() |
| 563 | + expect(doc_query(`ul.selected`).textContent?.trim()).toBe(`3`) |
| 564 | + }) |
| 565 | + |
| 566 | + test.each([ |
| 567 | + [null, [1, 2]], |
| 568 | + [1, 2], |
| 569 | + [2, [1, 2]], |
| 570 | + ])( |
| 571 | + `1-way bind value when maxSelect=%s, expected value=%s`, |
| 572 | + async (maxSelect, expected) => { |
| 573 | + const binder = new Test2WayBind({ |
| 574 | + target: document.body, |
| 575 | + props: { maxSelect }, |
| 576 | + }) |
| 577 | + let value: Option[] |
| 578 | + binder.$on(`value-changed`, (e: CustomEvent) => { |
| 579 | + value = e.detail |
| 580 | + }) |
| 581 | + |
| 582 | + // test internal changes bind outwards |
| 583 | + for (const _ of [1, 2]) { |
| 584 | + const li = doc_query(`ul.options li`) |
| 585 | + li.dispatchEvent(new MouseEvent(`mouseup`)) |
| 586 | + await sleep() |
| 587 | + } |
| 588 | + |
| 589 | + expect(value).toEqual(expected) |
| 590 | + } |
| 591 | + ) |
539 | 592 | }) |
0 commit comments