javascript / expert
Snippet
Mocking AsyncLocalStorage Contexts for Isolated Server Component Unit Tests
Focuses on unit testing request isolation in asynchronous Node.js environments (like Next.js Server Components/Actions). Uses `AsyncLocalStorage` to simulate isolated request stores and validates context boundaries using automated assertion checks.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { AsyncLocalStorage } from 'node:async_hooks';const requestContextStorage = new AsyncLocalStorage();export function runInRequestContext(store, callback) {return requestContextStorage.run(store, callback);}export function testRequestContextIsolation() {const storeA = { tenantId: 'tenant-alpha' };const storeB = { tenantId: 'tenant-beta' };let resultA, resultB;runInRequestContext(storeA, () => {resultA = requestContextStorage.getStore()?.tenantId;});runInRequestContext(storeB, () => {resultB = requestContextStorage.getStore()?.tenantId;});console.assert(resultA === 'tenant-alpha', 'Tenant A isolation check failed');console.assert(resultB === 'tenant-beta', 'Tenant B isolation check failed');}
nextjs
Breakdown
1
const requestContextStorage = new AsyncLocalStorage();
Instantiates an asynchronous local storage engine for implicit context propagation.
2
return requestContextStorage.run(store, callback);
Runs a synchronous or asynchronous callback bounded within the specified contextual store.
3
export function testRequestContextIsolation() {
Exports an isolated unit test function for verifying execution context safety.
4
resultA = requestContextStorage.getStore()?.tenantId;
Retrieves store metadata tied specifically to the current asynchronous execution flow.
5
console.assert(resultA === 'tenant-alpha', 'Tenant A isolation check failed');
Performs programmatic test assertions verifying store boundaries remain uncontaminated.