How to test Svelte component props with Vitest?

1.3k views Asked by At

I want to test the props of a Svelte component with Vitest.

Component:

<script>
  export let foo
</script>

<div>{foo}</div>

Test:

const { component } = render(MyComponent, { foo: 'bar' })
expect(component.foo).toBe('bar')

When I run this test, I get the following error:

Props cannot be read directly from the component instance unless compiling with 'accessors: true' or '<svelte:options accessors/>'

According to this post, I should pass accessors: true to the render() function:

const { component } = render(MyComponent, { accessors: true })

However, this doesn't work either and I keep getting the same error.

How can I test Svelte component props?

2

There are 2 answers

0
Janosh On

Rather than always enabling the accessors compiler option which might negatively impact performance, here's how to do it only a test time. vitest automatically sets the boolean environment variable process.env.TEST=true when it runs.

/** @type {import('@sveltejs/kit').Config} */
export default {
  extensions: [`.svelte`, `.svx`, `.md`],

  preprocess: preprocess(),

  compilerOptions: {
    // enable direct prop access for vitest unit tests. now you can do
    // const comp = new Component({ target: document.body, props: {...} })
    // comp.access_some_prop
    accessors: process.env.TEST,
  },

  kit: {
    adapter: adapter(),
  },
}
0
user20090462 On

Add it to svelte.config.js

compilerOptions: {
  accessors: true
},