javascript / expert
Snippet
Mocking von AsyncLocalStorage-Kontexten für isolierte Server-Komponenten-Unittests
Fokussiert das Unittesting der Anfrageisolierung in asynchronen Node.js-Umgebungen (wie Next.js Server Components/Actions). Verwendet `AsyncLocalStorage` zur Simulation isolierter Request-Stores und prüft Kontextgrenzen über automatisierte Assertions.
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
Erklärung
1
const requestContextStorage = new AsyncLocalStorage();
Instanziiert eine asynchrone lokale Speicherengine zur impliziten Kontextweitergabe.
2
return requestContextStorage.run(store, callback);
Führt einen Callback aus, der an den angegebenen Kontextspeicher gebunden ist.
3
export function testRequestContextIsolation() {
Exportiert eine isolierte Unittest-Funktion zur Überprüfung der Ausführungssicherheit.
4
resultA = requestContextStorage.getStore()?.tenantId;
Ruft Speicherdaten ab, die speziell an den aktuellen asynchronen Ausführungsfluss gebunden sind.
5
console.assert(resultA === 'tenant-alpha', 'Tenant A isolation check failed');
Führt programmgesteuerte Test-Assertions aus, um sicherzustellen, dass die Kontextgrenzen isoliert bleiben.