Skip to content

Commit 9c3f22c

Browse files
committed
add tests for '2-way bind selected' and '1-way bind value'
1 parent 40650ef commit 9c3f22c

File tree

2 files changed

+71
-1
lines changed

2 files changed

+71
-1
lines changed

tests/unit/Test2WayBind.svelte

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<script lang="ts">
2+
import MultiSelect, { type Option } from '$lib'
3+
import { createEventDispatcher } from 'svelte'
4+
5+
export let selected: Option[] = []
6+
export let options: Option[] = [1, 2, 3]
7+
export let value: Option | Option[] | null = null
8+
export let maxSelect: number | null = null
9+
10+
const dispatch = createEventDispatcher()
11+
12+
$: dispatch(`options-changed`, options)
13+
$: dispatch(`selected-changed`, selected)
14+
$: dispatch(`value-changed`, value)
15+
</script>
16+
17+
<MultiSelect bind:options bind:selected bind:value {maxSelect} />

tests/unit/multiselect.test.ts

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1-
import MultiSelect, { type MultiSelectEvents } from '$lib'
1+
import MultiSelect, { type MultiSelectEvents, type Option } from '$lib'
22
import { beforeEach, describe, expect, test, vi } from 'vitest'
3+
import Test2WayBind from './Test2WayBind.svelte'
34

45
beforeEach(() => {
56
document.body.innerHTML = ``
@@ -536,4 +537,56 @@ describe(`MultiSelect`, () => {
536537
expect(input.value).toBe(expected)
537538
}
538539
)
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+
)
539592
})

0 commit comments

Comments
 (0)