How to use createRawSnippet to test components? #13518
-
In #2588, we're told that we can use Svelte 5's Additionally, despite the switch at lower left being set to TypeScript, the example code is pure JavaScript and I don't know what types to use. The result is that this code produces the error "Argument of type '[string]' is not assignable to parameter of type 'never'" and the test doesn't work as expected. import { describe, it } from 'vitest'
import { render, screen } from '@testing-library/svelte'
import { createRawSnippet } from 'svelte'
import Badge from './Badge.svelte'
const badge = createRawSnippet((body) => {
return {
render: () => `<Badge>${body}</Badge>`,
setup: (node) => {
$effect(() => {
node.innerHTML = `${body}`
})
},
}
})
describe('Badge', () => {
it('shows a badge with the slot', () => {
render(badge('SAUSAGE'))
screen.debug()
})
}) I also get "'Badge' is defined but never used", because TypeScript isn't able to parse the template string. I'd rather have a way of rendering the component that doesn't use template strings, TBH — if I'd wanted to pepper my code with those, I'd use React 😁 What should I be putting here? (It would be really helpful if the docs actually covered the use of this for writing tests, as that's likely to be one of the main uses…) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 6 replies
-
<script>
import { createRawSnippet, mount, unmount } from 'svelte';
import Component from "./Component.svelte";
import Container from "./Container.svelte"
const props = $state({ name: "Test" })
const snip = createRawSnippet((name) => {
return {
render: () => `<div></div>`,
setup: (target) => {
const comp = mount(Component, { target, props });
return () => unmount(comp);
}
};
});
</script>
<input bind:value={props.name}><br>
<Container children={snip} /> |
Beta Was this translation helpful? Give feedback.
render()
should return an ordinary HTML, while insetup()
you make it interactive (add event listeners or mount a component).Usage is like this: