javascript / expert
Snippet
Isolated AsyncLocalStorage Context Injection for Next.js Server Action Unit Testing
AsyncLocalStorage facilitates clean dependency injection of request-scoped context during unit testing of Next.js Server Actions without polluting core function signatures.
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
Breakdown
1
export const requestStore = new AsyncLocalStorage<{ requestId: string }>();
Instantiates an asynchronous context store to implicitly flow request context across async calls.
2
const result = await requestStore.run({ requestId: 'req_123' }, () => ...);
Executes the Server Action within a mock context scope tailored specifically for assertion validation.