javascript / expert
Snippet
Mocking Custom Component Event Payloads in Svelte Unit Tests
Testing custom event handlers in Svelte components requires mocking callback functions with spied abstractions like Vitest's `vi.fn()`. By supplying spy functions through component props or event listeners, developers can trigger user interaction via `@testing-library/svelte` and strictly validate the emitted payload structure.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { render, fireEvent } from '@testing-library/svelte';import { vi, expect, test } from 'vitest';import CustomForm from './CustomForm.svelte';test('dispatches submitted payload correctly upon user submit', async () => {const handleSubmit = vi.fn();const { getByRole } = render(CustomForm, { props: { onsubmit: handleSubmit } });const submitBtn = getByRole('button', { name: /submit/i });await fireEvent.click(submitBtn);expect(handleSubmit).toHaveBeenCalledOnce();expect(handleSubmit).toHaveBeenCalledWith(expect.objectContaining({ detail: { valid: true } }));});
svelte
Breakdown
1
const handleSubmit = vi.fn();
Creates a Vitest spy function to capture and record calls made by the component event emitter.
2
const { getByRole } = render(CustomForm, { props: { onsubmit: handleSubmit } });
Renders the Svelte component into a synthetic DOM passing the spy callback as a prop.
3
await fireEvent.click(submitBtn);
Simulates a user click event asynchronously, triggering DOM event handlers in Svelte.
4
expect(handleSubmit).toHaveBeenCalledWith(expect.objectContaining({ detail: { valid: true } }));
Asserts that the mocked event callback received the expected structured payload object.