-
-
Notifications
You must be signed in to change notification settings - Fork 0
feat(test-utils): add custom response matchers for API error handling #436
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
bff3f2a
feat(test-utils): add custom response matchers for API error handling
luxass 76adf0e
chore: lint
luxass c926df3
feat(test-utils): enhance error message matching in response matcher
luxass fe7ec72
refactor(test-utils): remove unused HeadersOptions interface
luxass 0a2b79b
refactor(test-utils): improve error message matching logic
luxass 2340ed9
refactor(test-utils): use Object.keys for data iteration
luxass File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,279 @@ | ||
| import type { ApiError } from "@ucdjs/schemas"; | ||
| import type { MatcherState, RawMatcherFn } from "@vitest/expect"; | ||
| import { tryOr } from "@ucdjs-internal/shared"; | ||
|
|
||
| export interface ApiErrorOptions { | ||
| status: number; | ||
| message?: string | RegExp; | ||
| } | ||
|
|
||
| export const toBeApiError: RawMatcherFn<MatcherState, [ApiErrorOptions]> = async function ( | ||
| this: MatcherState, | ||
| received: Response, | ||
| options: ApiErrorOptions, | ||
| ) { | ||
| const { isNot, equals } = this; | ||
|
|
||
| if (!equals(received.status, options.status)) { | ||
| return { | ||
| pass: false, | ||
| message: () => `Expected response to${isNot ? " not" : ""} be an API error with status ${options.status}, but got ${received.status}`, | ||
| }; | ||
| } | ||
|
|
||
| const contentType = received.headers.get("content-type"); | ||
| if (!contentType?.includes("application/json")) { | ||
| return { | ||
| pass: false, | ||
| message: () => `Expected response to${isNot ? " not" : ""} have application/json content-type`, | ||
| }; | ||
| } | ||
|
|
||
| const error = await received.json() as ApiError; | ||
|
|
||
| if (!error.status || !error.message || !error.timestamp) { | ||
| return { | ||
| pass: false, | ||
| message: () => `Expected response to${isNot ? " not" : ""} have status, message, and timestamp properties`, | ||
| }; | ||
| } | ||
|
|
||
| if (options.message) { | ||
| const messageMatches = typeof options.message === "string" | ||
| ? error.message === options.message | ||
| : options.message.test(error.message); | ||
|
|
||
| if (!messageMatches) { | ||
| const expectedMsg = typeof options.message === "string" | ||
| ? options.message | ||
| : options.message.source; | ||
| return { | ||
| pass: false, | ||
| message: () => `Expected error message to${isNot ? " not" : ""} match ${expectedMsg}, but got "${error.message}"`, | ||
| }; | ||
| } | ||
| } | ||
|
|
||
| return { | ||
| pass: true, | ||
| message: () => `Expected response to${isNot ? " not" : ""} be an API error`, | ||
| }; | ||
| }; | ||
|
|
||
| export const toBeHeadError: RawMatcherFn<MatcherState, [number]> = function ( | ||
| this: MatcherState, | ||
| received: Response, | ||
| expectedStatus: number, | ||
| ) { | ||
| const { isNot, equals } = this; | ||
|
|
||
| if (!equals(received.status, expectedStatus)) { | ||
| return { | ||
| pass: false, | ||
| message: () => `Expected HEAD response status to${isNot ? " not" : ""} be ${expectedStatus}, but got ${received.status}`, | ||
| }; | ||
| } | ||
|
|
||
| const contentLength = received.headers.get("content-length"); | ||
| if (contentLength !== null && Number.parseInt(contentLength, 10) !== 0) { | ||
| return { | ||
| pass: false, | ||
| message: () => `Expected HEAD response to${isNot ? " not" : ""} have content-length of 0`, | ||
| }; | ||
| } | ||
|
|
||
| return { | ||
| pass: true, | ||
| message: () => `Expected HEAD response to${isNot ? " not" : ""} have status ${expectedStatus}`, | ||
| }; | ||
| }; | ||
|
|
||
| export interface ResponseMatcherOptions { | ||
| /** | ||
| * Expected HTTP status code | ||
| */ | ||
| status?: number; | ||
|
|
||
| /** | ||
| * Expected response headers (supports exact match or regex pattern) | ||
| */ | ||
| headers?: Record<string, string | RegExp>; | ||
|
|
||
| /** | ||
| * Whether to verify application/json content-type | ||
| */ | ||
| json?: boolean; | ||
|
|
||
| /** | ||
| * Whether to verify cache-control header exists | ||
| */ | ||
| cache?: boolean; | ||
|
|
||
| /** | ||
| * Regex pattern to match against cache-control max-age value | ||
| */ | ||
| cacheMaxAgePattern?: RegExp; | ||
|
|
||
| /** | ||
| * For API error responses, validate error structure and message. | ||
| * When provided, ensures the response is JSON and contains status, message, and timestamp properties. | ||
| */ | ||
| error?: { | ||
| /** | ||
| * Expected error message (string for exact match, RegExp for pattern) | ||
| */ | ||
| message?: string | RegExp; | ||
| }; | ||
| } | ||
|
|
||
| export const toMatchResponse: RawMatcherFn<MatcherState, [ResponseMatcherOptions]> = async function ( | ||
| this: MatcherState, | ||
| received: Response, | ||
| options: ResponseMatcherOptions, | ||
| ) { | ||
| const { isNot, equals } = this; | ||
|
|
||
| // Check status code | ||
| if (options.status !== undefined && !equals(received.status, options.status)) { | ||
| return { | ||
| pass: false, | ||
| message: () => `Expected status to${isNot ? " not" : ""} be ${options.status}, but got ${received.status}`, | ||
| }; | ||
| } | ||
|
|
||
| const contentType = received.headers.get("content-type"); | ||
| const isJson = contentType?.includes("application/json"); | ||
|
|
||
| // Check if content-type is JSON. | ||
| if (options.json && !isJson) { | ||
| return { | ||
| pass: false, | ||
| message: () => `Expected response to${isNot ? " not" : ""} have application/json content-type`, | ||
| }; | ||
| } | ||
|
|
||
| // Check cache headers if requested | ||
| if (options.cache) { | ||
| const cacheControl = received.headers.get("cache-control"); | ||
| if (!cacheControl) { | ||
| return { | ||
| pass: false, | ||
| message: () => `Expected response to${isNot ? " not" : ""} have cache-control header`, | ||
| }; | ||
| } | ||
|
|
||
| if (options.cacheMaxAgePattern && !options.cacheMaxAgePattern.test(cacheControl)) { | ||
| return { | ||
| pass: false, | ||
| message: () => `Expected cache-control to${isNot ? " not" : ""} match ${options.cacheMaxAgePattern!.source}`, | ||
| }; | ||
| } | ||
|
|
||
| if (!options.cacheMaxAgePattern && !/max-age=\d+/.test(cacheControl)) { | ||
| return { | ||
| pass: false, | ||
| message: () => `Expected cache-control to${isNot ? " not" : ""} have max-age`, | ||
| }; | ||
| } | ||
| } | ||
|
|
||
| // Check custom headers | ||
| if (options.headers) { | ||
| for (const [key, value] of Object.entries(options.headers)) { | ||
| const headerValue = received.headers.get(key); | ||
| if (!headerValue) { | ||
| return { | ||
| pass: false, | ||
| message: () => `Expected response to${isNot ? " not" : ""} have ${key} header`, | ||
| }; | ||
| } | ||
|
|
||
| const matches = typeof value === "string" | ||
| ? equals(headerValue, value) | ||
| : value.test(headerValue); | ||
|
|
||
| if (!matches) { | ||
| const expected = typeof value === "string" ? value : value.source; | ||
| return { | ||
| pass: false, | ||
| message: () => `Expected ${key} header to${isNot ? " not" : ""} match ${expected}, but got "${headerValue}"`, | ||
| }; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // Check error structure and message if requested | ||
| if (options.error) { | ||
| if (!isJson) { | ||
| return { | ||
| pass: false, | ||
| message: () => `Expected error response to${isNot ? " not" : ""} have application/json content-type`, | ||
| }; | ||
| } | ||
|
|
||
| const error = await tryOr({ | ||
| try: async () => received.json() as Promise<ApiError>, | ||
luxass marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| err(err) { | ||
| console.error("Failed to parse response JSON:", err); | ||
luxass marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| return null; | ||
| }, | ||
| }); | ||
|
|
||
| if (error == null) { | ||
| return { | ||
| pass: false, | ||
| message: () => `Expected response body to${isNot ? " not" : ""} be valid JSON`, | ||
| }; | ||
| } | ||
|
|
||
| // Check required error properties | ||
| if (!error.status) { | ||
| return { | ||
| pass: false, | ||
| message: () => `Expected error to${isNot ? " not" : ""} have "status" property`, | ||
| }; | ||
| } | ||
| if (!error.message) { | ||
| return { | ||
| pass: false, | ||
| message: () => `Expected error to${isNot ? " not" : ""} have "message" property`, | ||
| }; | ||
| } | ||
| if (!error.timestamp) { | ||
| return { | ||
| pass: false, | ||
| message: () => `Expected error to${isNot ? " not" : ""} have "timestamp" property`, | ||
| }; | ||
| } | ||
|
|
||
| // Check that error status matches response status if both are provided | ||
| if (options.status !== undefined && !equals(error.status, options.status)) { | ||
| return { | ||
| pass: false, | ||
| message: () => `Expected error.status to${isNot ? " not" : ""} be ${options.status}, but got ${error.status}`, | ||
| }; | ||
| } | ||
|
|
||
| // Check error message if provided | ||
| if (options.error.message) { | ||
| const messageMatches = options.error.message instanceof RegExp | ||
| ? options.error.message.test(error.message) | ||
| : equals(error.message, options.error.message); | ||
|
|
||
| if (!messageMatches) { | ||
| const expectedMsg = typeof options.error.message === "string" | ||
| ? options.error.message | ||
| : options.error.message.source; | ||
| return { | ||
| pass: false, | ||
| message: () => `Expected error.message to${isNot ? " not" : ""} match "${expectedMsg}", but got "${error.message}"`, | ||
| }; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return { | ||
| pass: true, | ||
| message: () => `Expected response to${isNot ? " not" : ""} match the given criteria`, | ||
| }; | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| import type { MatcherState, RawMatcherFn } from "@vitest/expect"; | ||
| import type z from "zod"; | ||
|
|
||
| export interface SchemaMatcherOptions<TSchema extends z.ZodType> { | ||
| schema: TSchema; | ||
| success: boolean; | ||
| data?: Partial<z.infer<TSchema>>; | ||
| } | ||
|
|
||
| export const toMatchSchema: RawMatcherFn<MatcherState, [SchemaMatcherOptions<z.ZodType>]> = function <TSchema extends z.ZodType>( | ||
| this: MatcherState, | ||
| received: unknown, | ||
| options: SchemaMatcherOptions<TSchema>, | ||
| ) { | ||
| const result = options.schema.safeParse(received); | ||
| const successMatches = result.success === options.success; | ||
|
|
||
| if (!successMatches) { | ||
| const expectedStatus = options.success ? "succeed" : "fail"; | ||
| const actualStatus = result.success ? "succeeded" : "failed"; | ||
| const issues = result.error?.issues ? `\n${this.utils.printExpected(result.error.issues)}` : ""; | ||
| return { | ||
| pass: false, | ||
| message: () => `Expected schema validation to ${expectedStatus}, but it ${actualStatus}${issues}`, | ||
| }; | ||
| } | ||
|
|
||
| // Check partial data properties if provided | ||
| if (options.data && result.success) { | ||
| for (const key of Object.keys(options.data)) { | ||
| const expected = (options.data as any)[key]; | ||
| const received = (result.data as any)[key]; | ||
|
|
||
| if (!this.equals(received, expected)) { | ||
| return { | ||
| pass: false, | ||
| message: () => | ||
| `Expected property "${key}" to equal ${this.utils.printExpected(expected)}, but received ${this.utils.printReceived(received)}`, | ||
| }; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return { | ||
| pass: true, | ||
| message: () => `Expected schema validation to not match`, | ||
| }; | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,16 @@ | ||
| import { expect } from "vitest"; | ||
| import { toMatchError } from "./error-matchers"; | ||
| import { | ||
| toBeApiError, | ||
| toBeHeadError, | ||
| toMatchResponse, | ||
| } from "./response-matchers"; | ||
| import { toMatchSchema } from "./schema-matchers"; | ||
|
|
||
| expect.extend({ | ||
| toMatchError, | ||
| toMatchSchema, | ||
| toBeApiError, | ||
| toBeHeadError, | ||
| toMatchResponse, | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.