javascript / expert
Snippet
Mocking Next.js Cookies and Request Headers in Integration Tests
Constructing isolated Map-backed cookie container fixtures allows running Next.js Server Action unit tests without relying on full Next.js runtime ambient execution contexts.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
export function createMockCookieStore(initialCookies = {}) {const store = new Map(Object.entries(initialCookies));return {get: (name) => store.has(name) ? { name, value: store.get(name) } : undefined,set: (name, value) => store.set(name, value),has: (name) => store.has(name)};}export function executeWithMockCookies(actionFn, mockData) {const mockStore = createMockCookieStore(mockData);try {return actionFn(mockStore);} catch (error) {throw new Error(`Test fixture failure: ${error.message}`);}}
nextjs
Breakdown
1
const store = new Map(Object.entries(initialCookies));
Converts key-value parameter records into an encapsulated Map lookup table.
2
get: (name) => store.has(name) ? { name, value: store.get(name) } : undefined,
Implements the standardized Next.js ReadonlyRequestCookies getter contract.
3
throw new Error(`Test fixture failure: ${error.message}`);
Wraps lower-level action exceptions with explicit testing context diagnostics.