Skip to main content

FAQ


Does this library also work with SvelteKit?

Yes, it does. It requires the same setup as a "normal" Svelte project.

Why isn't onMount called when rendering components?

Since the test is running in a Node environment instead of a browser environment, it uses the SSR exports from Svelte, which declare all lifecycle events as no-ops.

One solution is to configure Vite to use browser resolutions in tests.

vite.config.js
import {svelte} from '@sveltejs/vite-plugin-svelte'
import {defineConfig} from 'vite'

export default defineConfig(({mode}) => ({
plugins: [svelte()],
resolve: {
// The default would be [ 'svelte', 'node' ]
// as set by vite-plugin-svelte and vitest.
// This sets [ 'browser', 'svelte', 'node' ]
conditions: mode === 'test' ? ['browser'] : [],
},
test: {
environment: 'jsdom',
},
}))

See svelte-testing-library's issue 222 for more details.

How do I test file upload?

Use the upload utility from @testing-library/user-event rather than fireEvent. It works well in both jsdom and happy-dom.

test('upload file', async () => {
const user = userEvent.setup()

render(Uploader)
const file = new File(['hello'], 'hello.png', {type: 'image/png'})
const input = screen.getByLabelText(/upload file/i)

await user.upload(input, file)

expect(input.files[0]).toBe(file)
expect(input.files.item(0)).toBe(file)
expect(input.files).toHaveLength(1)
})

Why aren't transition events running?

The jsdom implementation of requestAnimationFrame can be unreliable in Vitest. To work around it, you can:

  • Switch to happy-dom, if you are able, which does not exhibit the same issues
  • Replace the implementation of requestAnimationFrame
beforeEach(() => {
const raf = fn => setTimeout(() => fn(new Date()), 16)
vi.stubGlobal('requestAnimationFrame', raf)
})

// Alternatively, set `unstubGlobals: true` in vitest.config.js
afterEach(() => {
vi.unstubAllGlobals()
})

See svelte-testing-library's issue 206 for more details.