javascript / expert
Snippet
Testing Svelte Action Lifecycle Cleanups using DOM MutationObserver Mocks
Unit testing Svelte custom element actions requires verifying that teardown methods release DOM event listeners without throwing exceptions when nodes are detached. Wrapping the action execution with a DOM MutationObserver listener validates automatic cleanup logic during component unmounting.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
export function createActionCleanupTester(actionFn, node) {let isCleanedUp = false;const destroyHandle = actionFn(node) || {};const observer = new MutationObserver(() => {if (!document.body.contains(node)) {try {destroyHandle.destroy?.();isCleanedUp = true;} catch (err) {throw new Error(`Action cleanup thrown: ${err.message}`);}}});observer.observe(node.parentNode, { childList: true });return () => ({ isCleanedUp, disconnect: () => observer.disconnect() });}
svelte
Breakdown
1
const destroyHandle = actionFn(node) || {};
Executes the Svelte action against a target DOM element node to obtain its destruction callback object.
2
const observer = new MutationObserver(() => {
Instantiates a MutationObserver instance to monitor node removal events in test environments.
3
if (!document.body.contains(node)) {
Determines if the target node was detached from the main DOM body during test execution.
4
destroyHandle.destroy?.();
Invokes the teardown method safely while capturing any runtime errors produced during unmount.