javascript / expert
Snippet
Unit Testing Explicit Resource Management (Symbol.dispose) in Hook Cleanups
Utilizes the ES Explicit Resource Management standard (Symbol.dispose) inside React useEffect cleanup callbacks, and verifies deterministic resource teardown using component unmount testing.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { renderHook } from '@testing-library/react';import { useEffect } from 'react';function useExplicitResource(resource) {useEffect(() => {return () => {if (typeof resource[Symbol.dispose] === 'function') {resource[Symbol.dispose]();}};}, [resource]);}test('disposes resource on unmount', () => {const disposeSpy = jest.fn();const mockResource = { [Symbol.dispose]: disposeSpy };const { unmount } = renderHook(() => useExplicitResource(mockResource));unmount();expect(disposeSpy).toHaveBeenCalledTimes(1);});
react
Breakdown
1
if (typeof resource[Symbol.dispose] === 'function') {
Checks if the passed object adheres to the Disposable interface via Symbol.dispose.
2
resource[Symbol.dispose]();
Executes the cleanup logic defined on the explicit disposable resource.
3
const { unmount } = renderHook(() => useExplicitResource(mockResource));
Renders the hook in isolation to test lifecycle teardown execution.