@magic/test
Svelte Testing
@magic/test has built-in support for testing Svelte 5 components: it compiles your components, mounts them in a DOM, and hands you helpers to poke at and assert on.
internally uses happy-dom to create the DOM and html elements.
mount
import { mount, html } from '@magic/test/svelte'const component = './path/to/MyComponent.svelte'export default [{component,props: { message: 'Hello' },fn: ({ target }) => html(target).includes('Hello'),expect: true,info: 'renders the message prop',},]
Exported Functions
- mount(filePath, options) - mounts a component, returns { target, component, unmount, css }
- html(target) - innerHTML of a mounted component's target element
- text(target) - textContent of a target element
- component(instance) - the component instance, for accessing exported values
- props(target) - attribute name/value pairs from the target element
- createSnippet(renderFn) - a raw snippet to pass as a children prop
- tick() - svelte's tick, retry-wrapped — await it after interactions
Interaction Functions
fire everything a user can do:
- mouse: click (target, selector?), dblClick, contextMenu, mouseDown/Up/Move/Enter/Leave/Over/Out
- keys: keyDown, keyPress, keyUp (target, key), type, input, change
- focus: focus, focusIn, focusOut, blur, submit
- pointer: pointerDown, pointerUp, pointerMove, pointerOver, pointerOut
- touch: touchStart, touchMove, touchEnd
- drag: dragStart, drag, dragEnd, dragEnter, dragLeave, dragOver, drop
- clipboard: copy, cut, paste
- media: play, pause, ended, volumeChange
- animation: animationStart, animationEnd, animationIteration, transitionEnd
- other: resize(target, w, h), scroll(target, x, y), checked, fireEvent, trigger(target, eventType, options?)
Test Properties
- component - path to the .svelte file
- props - props to pass to the component
- context - svelte context: a static object, or a factory (info: { target, props }) => object
- fn - test function receiving { target, component, unmount }
Accessing Component State
import { mount } from '@magic/test/svelte'const component = './src/lib/svelte/components/Counter.svelte'export default [{component,fn: async ({ target, component: instance }) => {return instance.count},expect: 0,info: 'initial count is 0',},]
Automatic Test Exports
$state and $derived variables are exported automatically, so they are accessible in tests without manual exports. Svelte 5 only — svelte 4 components can't do this.
<!-- Component.svelte --><script>let count = $state(0)let doubled = $derived(count * 2)<!-- No export needed! --></script><button class="inc">+</button><span>{doubled}</span>
and in the test:
import { mount } from '@magic/test'export default [{component: './Component.svelte',fn: async ({ component }) => component.count, // 0expect: 0,info: 'access $state without manual export',},{component: './Component.svelte',fn: async ({ component }) => component.doubled, // 0 (derived)expect: 0,info: 'access $derived without manual export',},]
works for every $state and $derived rune, no config.
Testing Error Handling
import { tryCatch } from '@magic/test'import { mount } from '@magic/test/svelte'const component = './src/lib/svelte/components/MyComponent.svelte'export default [{fn: tryCatch(mount, component, { props: null }),expect: t => t.message === 'Props must be an object, got object',info: 'throws when props is null',},]
SvelteKit Mocks
mocks SvelteKit $app modules:
import { browser, dev, prod, createStaticPage } from '@magic/test/svelte'export default [{fn: () => browser, // mocks a browser environmentexpect: true,info: 'always true',},{fn: () => dev, // production mode is set by -pexpect: process.env.MAGIC_TEST_ENV !== 'production',info: 'true unless the run is in production mode (-p)',},{fn: () => prod, // production mode is set by -pexpect: process.env.MAGIC_TEST_ENV === 'production',info: 'true only in production mode (-p)',},]
createStaticPage
creates a static $app/state page proxy (url/params/state):
import { createStaticPage } from '@magic/test/svelte'export default [{fn: () => {const page = createStaticPage({ url: 'http://example.com', params: { id: '1' } })return page.url.hostname === 'example.com' && page.params.id === '1'},expect: true,info: 'createStaticPage returns a page proxy with url/params/state',},]
compileSvelte
compile a .svelte file to js/css (async, file path in):
import { compileSvelte } from '@magic/test/svelte'export default [{fn: async () => {const { js } = await compileSvelte('./path/to/button.svelte')return typeof js === 'string'},expect: true,info: 'compiles a svelte file to js/css',},]
Available functions:
- compileSvelte(source, filename) - Compiles Svelte source to JS/CSS modules
- ensureSvelte() - Lazy-loads the Svelte package, throws if not installed
ensureSvelte
lazy-loads the svelte package, throws if it is not installed:
import { ensureSvelte } from '@magic/test/svelte'export default [{fn: async () => {const svelte = await ensureSvelte()return svelte.version.startsWith('5')},expect: true,info: 'loads svelte package',},]