Create svelte components on-the-fly using a vite-plugin and async imports under the hood. Useful for writing unit tests using Vitest. Relies on your existing Vite configuration to apply any Svelte transforms. Inspired by svelte-inline-compile.
Install using your package manager:
npm install svelte-inline-compile-vite
Add it to your vitest.config.js:
// file: vitest.config.js
import { defineConfig } from 'vitest/config';
import { SvelteInlineCompile } from 'svelte-inline-compile-vite';
import { svelte } from '@sveltejs/vite-plugin-svelte';
export default defineConfig(() => {
return {
plugins: [
svelte(),
SvelteInlineCompile(),
],
test: {
environment: 'jsdom',
}
}
});
If you're using SvelteKit, use it with vitest-svelte-kit
// file: vitest.config.js
import { defineConfig } from 'vitest/config';
import { extractFromSvelteConfig } from 'vitest-svelte-kit';
import { SvelteInlineCompile } from 'svelte-inline-compile-vite';
export default defineConfig(async () => {
const config = await extractFromSvelteConfig();
return {
...config,
plugins: [
...config.plugins,
SvelteInlineCompile()
],
test: {
environment: 'jsdom'
}
};
})
Import the svelte
function and pass it your svelte component template as a
string or tagged template literal. It returns the pending dynamic import as a
promise you need to await.
Check it out in a test:
import { it } from 'vitest';
import { render, screen } from '@testing-library/svelte';
import { svelte } from 'svelte-inline-compile-vite';
it('renders a svelte component', async () => {
render(await svelte`
<div>hello world</div>
`);
screen.getByText('hello world');
})
This doesn't seem to work with SvelteKit for a couple reasons: