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?
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 variableprocess.env.TEST=true
when it runs.