javascript / expert
Snippet
WeakMap-Cached Higher-Order Function Binding for React Component Test Harnesses
When isolating components during automated unit tests, holding references to spy handlers in static maps risks memory leaks across test suites. Using a WeakMap keyed by the Component reference allows garbage collection of test harnesses while offering fast memoized lookup of spy registries per unit test.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
const mockFnRegistry = new WeakMap();export function createIsolatedTestHarness(Component) {return function BoundHarness(props) {let boundSpies = mockFnRegistry.get(Component);if (!boundSpies) {boundSpies = new Map();mockFnRegistry.set(Component, boundSpies);}const safeProps = { ...props, _harnessId: Symbol('harness') };return Component(safeProps);};}
react
Breakdown
1
const mockFnRegistry = new WeakMap();
Creates a weak reference map where target component keys can be garbage collected when out of test scope.
2
let boundSpies = mockFnRegistry.get(Component);
Retrieves cached test spy associations dynamically for the rendered target component.
3
const safeProps = { ...props, _harnessId: Symbol('harness') };
Injects unique non-enumerable identity symbols into props to prevent cross-test state collision.