svelte-component-test-recipes icon indicating copy to clipboard operation
svelte-component-test-recipes copied to clipboard

Test 2-way binding with only `vitest`

Open janosh opened this issue 1 year ago • 4 comments

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.

janosh avatar Sep 15 '22 18:09 janosh

Sadly, no. 😅 I discussed with @benmccann the pain of testing two-way binding, use directive, context API at discord.

wd-David avatar Sep 15 '22 23:09 wd-David

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).

janosh avatar Oct 25 '22 18:10 janosh

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.

wd-David avatar Oct 26 '22 13:10 wd-David

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.

janosh avatar Oct 26 '22 15:10 janosh