javascript / expert
Snippet
Custom Assertion Matchers for Next.js Headers and Redirect Validation
When testing Next.js middleware or API route responses, built-in test assertions can become verbose. Creating custom matchers via `expect.extend` allows clean validation of standard Response objects, verifying header keys against literal strings or regular expressions while providing custom error diagnostics.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
expect.extend({toHaveHeader(response, headerName, expectedValue) {const actualValue = response.headers.get(headerName);const pass = expectedValue instanceof RegExp? expectedValue.test(actualValue ?? ''): actualValue === expectedValue;return {pass,message: () =>`Expected header "${headerName}" to ${pass ? 'not ' : ''}match ${expectedValue}, but received "${actualValue}"`,};},});
nextjs
Breakdown
1
expect.extend({ toHaveHeader(response, headerName, expectedValue) {
Registers a custom matcher function with Vitest or Jest to extend assertion capabilities.
2
const pass = expectedValue instanceof RegExp ? expectedValue.test(actualValue ?? '') : actualValue === expectedValue;
Evaluates if the header value matches either a literal string or a regular expression pattern.