javascript / expert
Snippet
Prototype-Linked Dependency Injection Container for React Unit Tests
Uses prototype delegation (Object.create) and WeakMap memory management to build a scoped dependency injection container for React hook isolation during automated unit testing. Child test scopes inherit base mocks without polluting root test registries.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function createTestContainer(parent = null) {const registry = Object.create(parent ? parent.registry : null);const cleanups = new WeakMap();return {registry,register(key, service, cleanupFn) {registry[key] = service;if (cleanupFn) cleanups.set(service, cleanupFn);},resolve(key) {const service = registry[key];if (!service) throw new Error(`Unresolved dependency: ${String(key)}`);return service;},teardown(service) {const cleanup = cleanups.get(service);if (cleanup) cleanup();}};}
react
Breakdown
1
const registry = Object.create(parent ? parent.registry : null);
Creates a prototype-linked lookup object for hierarchical mock inheritance across test suites.
2
const cleanups = new WeakMap();
Uses a WeakMap to associate non-retained cleanup handlers with service instances to avoid memory leaks.
3
if (!service) throw new Error(`Unresolved dependency: ${String(key)}`);
Validates lookup resolution and throws descriptive runtime errors when dependencies are missing.
4
teardown(service) { const cleanup = cleanups.get(service); ... }
Retrieves and triggers scoped teardown handlers when unmounting tested React hooks.