javascript / expert
Snippet
Isolierte AsyncLocalStorage-Kontext-Injektion für Next.js Server Action Unit-Tests
AsyncLocalStorage ermöglicht saubere Dependency Injection von anfragebezogenem Kontext beim Unit-Testing von Next.js Server Actions ohne Anpassung der Funktionssignaturen.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { AsyncLocalStorage } from 'node:async_hooks';import test from 'node:test';import assert from 'node:assert';export const requestStore = new AsyncLocalStorage<{ requestId: string }>();export async function logServerAction(actionName: string) {const store = requestStore.getStore();if (!store) throw new Error('Action invoked outside request context');return `[${store.requestId}] Executed ${actionName}`;}test('runs server action with injected trace context', async () => {const result = await requestStore.run({ requestId: 'req_123' }, () =>logServerAction('updateUser'));assert.strictEqual(result, '[req_123] Executed updateUser');});
nextjs
Erklärung
1
export const requestStore = new AsyncLocalStorage<{ requestId: string }>();
Instanziiert einen asynchronen Kontext-Store zur impliziten Weitergabe von Anfragedaten über asynchrone Aufrufketten.
2
const result = await requestStore.run({ requestId: 'req_123' }, () => ...);
Führt die Server Action innerhalb eines Mock-Kontextbereichs aus, der für Testvalidierungen bereitgestellt wird.