javascript / expert
Snippet
Verifying Asynchronous Custom Event Emitters via Microtask Queue Assertions
In Svelte component unit tests, event dispatches and reactive state updates do not execute synchronously on the immediate stack frames. Using Svelte's tick promise ensures pending microtask queue cycles complete prior to asserting event payload delivery.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
import { tick } from 'svelte';export async function assertEventEmitted(dispatchFn, listenerSpy) {dispatchFn('customEvent', { value: 99 });await tick();if (!listenerSpy.calledWith(99)) {throw new Error('Asynchronous event payload mismatch');}}
svelte
Breakdown
1
import { tick } from 'svelte';
Imports the core tick utility from Svelte to await pending state and DOM microtasks.
2
export async function assertEventEmitted(dispatchFn, listenerSpy) {
Exports an asynchronous test assertion helper accepting dispatch functions and spies.
3
dispatchFn('customEvent', { value: 99 });
Dispatches a custom event payload asynchronously through the provided emitter.
4
await tick();
Pauses test execution until Svelte resolves queued DOM changes and pending updates.
5
if (!listenerSpy.calledWith(99)) {
Asserts that the event listener spy recorded the expected payload arguments.