javascript / expert
Snippet
Asserting MutationObserver Lifecycle Cleanup in Custom Element Directives
Demonstrates unit testing techniques for Svelte actions, verifying that asynchronous MutationObserver callbacks do not execute post-directive teardown by draining the microtask queue.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
export function observeAttributeChanges(node, callback) {const observer = new MutationObserver((mutations) => callback(mutations));observer.observe(node, { attributes: true });return {destroy() {observer.disconnect();}};}export async function testActionCleanup(nodeMock) {let called = false;const action = observeAttributeChanges(nodeMock, () => { called = true; });action.destroy();await Promise.resolve();return called === false;}
svelte
Breakdown
1
const observer = new MutationObserver((mutations) => callback(mutations));
Instantiates DOM MutationObserver attached to the given action target node.
2
observer.disconnect();
Stops observing attribute mutations to prevent resource leaking when the component unmounts.
3
action.destroy();
Executes Svelte action lifecycle teardown function explicitly within test runner environment.
4
await Promise.resolve();
Flushes pending asynchronous microtasks before asserting that callback execution was blocked.