svelte-component-test-recipes
svelte-component-test-recipes copied to clipboard
Test 2-way binding with only `vitest`
Very cool resource! Thanks for putting this together. 👍
Do you know of a way to test 2-way binding without '@testing-library/svelte'
and 'svelte-htm'
, i.e. using only vitest
?
Either way, feel free to close this right away.
Sadly, no. 😅 I discussed with @benmccann the pain of testing two-way binding, use directive, context API at discord.
The way I started testing 2-way binding over at https://github.com/janosh/svelte-multiselect is with a wrapper component that dispatches when ever bound variables change.
<script lang="ts">
// Test2WayBind.svelte
import MultiSelect, { type Option } from '$lib'
import { createEventDispatcher } from 'svelte'
export let options: Option[]
export let selected: Option[] = []
const dispatch = createEventDispatcher()
$: dispatch(`options-changed`, options)
$: dispatch(`selected-changed`, selected)
</script>
<MultiSelect bind:options bind:selected />
Here's a usage example that tests both inward and outward binding.
Seems to work well and needs to extra dependencies (vitest
only).
We can create wrapper components for cases like two-way binding, named slots, and actions like this write-up from Swyx two years ago: Testing and Debugging Svelte. (It's worth checking even it's archived.)
I'm not an experienced front-end tester. Sometimes it feels like I'm testing Svelte's internal or implementation as a component/ library author. I also doubted my approach when I wrote a lot of test harnesses for the sake of test coverage at work.
Anyway, many kudos to @janosh, your great work, especially the testing, on svelte-multiselect
always inspire me and I learned so much from you.
like this write-up from Swyx two years ago: Testing and Debugging Svelte. (It's worth checking even it's archived.)
Cool, didn't know about this. Thanks for sharing.