javascript / expert
Snippet
Synthetic Event Dispatch and Mock MutationObserver Testing for Svelte Node Directives
Demonstrates isolated unit testing of custom Svelte DOM action directives using MutationObserver capturing and synthetic CustomEvent dispatches. This avoids full browser rendering while validating node modifications and teardown functions.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
export function testSvelteAction(actionFn, targetNode, options) {const mutations = [];const mockObserver = new MutationObserver((records) => mutations.push(...records));mockObserver.observe(targetNode, { attributes: true, childList: true });const instance = actionFn(targetNode, options);targetNode.dispatchEvent(new CustomEvent('test-trigger', { bubbles: true }));return {getMutations: () => [...mutations],cleanup: () => {mockObserver.disconnect();instance?.destroy?.();}};}
svelte
Breakdown
1
const mutations = [];
Initializes an in-memory buffer to record element mutation records during test execution.
2
const mockObserver = new MutationObserver((records) => mutations.push(...records));
Creates a DOM MutationObserver instance to record attribute and DOM hierarchy changes.
3
const instance = actionFn(targetNode, options);
Invokes the Svelte action directly on the mock DOM node with target test parameters.
4
targetNode.dispatchEvent(new CustomEvent('test-trigger', { bubbles: true }));
Dispatches a bubbling custom event to evaluate action event listener behavior.
5
instance?.destroy?.();
Executes the action teardown function to ensure zero resource leaks post-test.