javascript / expert
Snippet
Validating Svelte Action Mount and Destroy Side-Effects using Isolated Event Simulation
Unit testing Svelte actions requires programmatic instantiation of the action handler and manually triggering synthetic events to ensure cleanup methods detach global listeners properly.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
export function autoFocusAction(node, options = {}) {const handleKeyDown = (e) => {if (e.key === 'Escape') node.blur();};window.addEventListener('keydown', handleKeyDown);if (options.focusImmediately) node.focus();return {destroy() {window.removeEventListener('keydown', handleKeyDown);}};}export function testAutoFocusLifecycle(testNode) {const actionInstance = autoFocusAction(testNode, { focusImmediately: false });const escapeEvent = new KeyboardEvent('keydown', { key: 'Escape', bubbles: true });window.dispatchEvent(escapeEvent);actionInstance.destroy();const secondaryEvent = new KeyboardEvent('keydown', { key: 'Escape', bubbles: true });return window.dispatchEvent(secondaryEvent);}
svelte
Breakdown
1
window.addEventListener('keydown', handleKeyDown);
Attaches a global keydown event listener inside the Svelte action closure.
2
destroy() { window.removeEventListener('keydown', handleKeyDown); }
Returns an explicit lifecycle teardown method invoked when Svelte unmounts the host node.
3
const escapeEvent = new KeyboardEvent('keydown', { key: 'Escape', bubbles: true });
Instantiates a realistic synthetic KeyboardEvent to test the active event handler logic during test execution.