-
Notifications
You must be signed in to change notification settings - Fork 0
test: add convenient API for applying custom schema based mocks #148
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
+952
−757
Merged
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
b2e76ba
test: add mock wrapper
kantord 69b7265
better import experience
kantord 91db28b
update mocks documentation
kantord 65cef62
add some usage examples for mock overrides
kantord 2e7dbf2
add overrideResponse helper
kantord bc387f0
encourage type safety in mock overrides
kantord 4c1d01b
allow creating reusable scenarios?
kantord 5f64128
add shared type for mock scenarios
kantord 3924281
simple way to activate same scenario across multipl mocks
kantord 6f30446
jsdoc for mock scenarios
kantord f9dd352
reduce pr size
kantord 3183f97
address claude code review points
kantord 6228d1a
improve wording in jsdoc
kantord 10a9ecf
make docs less verbose
kantord a0b56a3
test: mock token retrieval globally
kantord 23f3f45
apply some of copilot's suggestions
kantord 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
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,62 @@ | ||
| import { mockedGetRegistryV01Servers } from "@mocks/fixtures/registry_v0_1_servers/get"; | ||
| import { HttpResponse } from "msw"; | ||
| import { describe, expect, it } from "vitest"; | ||
| import { getServers } from "./actions"; | ||
|
|
||
| // Authentication is mocked globally in vitest.setup.ts: | ||
| // - auth.api.getSession returns a mock session | ||
| // - getValidOidcToken returns "mock-test-token" | ||
|
|
||
| describe("getServers", () => { | ||
| it("returns servers from default fixture", async () => { | ||
| const servers = await getServers(); | ||
|
|
||
| expect(servers.length).toBeGreaterThan(0); | ||
| expect(servers[0].name).toBe("awslabs/aws-nova-canvas"); | ||
| }); | ||
|
|
||
| // Demo: using .activateScenario() for reusable test scenarios | ||
| it("returns empty array when using empty-servers scenario", async () => { | ||
| mockedGetRegistryV01Servers.activateScenario("empty-servers"); | ||
|
|
||
| const servers = await getServers(); | ||
|
|
||
| expect(servers).toEqual([]); | ||
| }); | ||
|
|
||
| // Demo: using .activateScenario() for error scenarios | ||
| it("throws on server error scenario", async () => { | ||
| mockedGetRegistryV01Servers.activateScenario("server-error"); | ||
|
|
||
| await expect(getServers()).rejects.toBeDefined(); | ||
| }); | ||
|
|
||
| // Demo: using .override() for type-safe response modifications | ||
| it("can override response data with type safety", async () => { | ||
| mockedGetRegistryV01Servers.override(() => ({ | ||
| servers: [ | ||
| { | ||
| server: { | ||
| name: "test/server", | ||
| title: "Test Server", | ||
| }, | ||
| }, | ||
| ], | ||
| metadata: { count: 1 }, | ||
| })); | ||
|
|
||
| const servers = await getServers(); | ||
|
|
||
| expect(servers).toHaveLength(1); | ||
| expect(servers[0].name).toBe("test/server"); | ||
| }); | ||
|
|
||
| // Demo: using .overrideHandler() for error status codes | ||
| it("can use overrideHandler for custom error responses", async () => { | ||
| mockedGetRegistryV01Servers.overrideHandler(() => | ||
| HttpResponse.json({ error: "Unauthorized" }, { status: 401 }), | ||
| ); | ||
|
|
||
| await expect(getServers()).rejects.toBeDefined(); | ||
| }); | ||
| }); |
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 |
|---|---|---|
| @@ -0,0 +1,140 @@ | ||
| import type { HttpResponseResolver, JsonBodyType } from "msw"; | ||
| import { HttpResponse } from "msw"; | ||
| import type { MockScenarioName } from "./scenarioNames"; | ||
|
|
||
| const SCENARIO_HEADER = "x-mock-scenario"; | ||
|
|
||
| type ResponseResolverInfo = Parameters<HttpResponseResolver>[0]; | ||
|
|
||
| type OverrideHandlerFn<T> = (data: T, info: ResponseResolverInfo) => Response; | ||
| type OverrideFn<T> = (data: T, info: ResponseResolverInfo) => T; | ||
| type ScenarioFn<T> = ( | ||
| instance: AutoAPIMockInstance<T>, | ||
| ) => AutoAPIMockInstance<T>; | ||
|
|
||
| export interface ActivateScenarioOptions { | ||
| /** If true, silently falls back to default when scenario doesn't exist. Default: false (throws) */ | ||
| fallbackToDefault?: boolean; | ||
| } | ||
|
|
||
| export interface AutoAPIMockInstance<T> { | ||
| /** MSW handler to use in handler registration. Respects overrides and scenarios. */ | ||
| generatedHandler: HttpResponseResolver; | ||
|
|
||
| /** Override response data with type safety. Preferred for simple data changes. */ | ||
| override: (fn: OverrideFn<T>) => AutoAPIMockInstance<T>; | ||
|
|
||
| /** Override the full handler. Use for errors, network failures, or invalid data. */ | ||
| overrideHandler: (fn: OverrideHandlerFn<T>) => AutoAPIMockInstance<T>; | ||
|
|
||
| /** Define a reusable named scenario for this mock. */ | ||
| scenario: ( | ||
| name: MockScenarioName, | ||
| fn: ScenarioFn<T>, | ||
| ) => AutoAPIMockInstance<T>; | ||
|
|
||
| /** Activate a named scenario for the current test. */ | ||
| activateScenario: ( | ||
| name: MockScenarioName, | ||
| options?: ActivateScenarioOptions, | ||
| ) => AutoAPIMockInstance<T>; | ||
|
|
||
| /** Reset to default behavior. Called automatically before each test. */ | ||
| reset: () => AutoAPIMockInstance<T>; | ||
|
|
||
| /** The default fixture data. */ | ||
| defaultValue: T; | ||
| } | ||
|
|
||
| // Registry to track all instances for bulk reset | ||
| const registry: Set<AutoAPIMockInstance<unknown>> = new Set(); | ||
|
|
||
| export function AutoAPIMock<T>(defaultValue: T): AutoAPIMockInstance<T> { | ||
| let overrideHandlerFn: OverrideHandlerFn<T> | null = null; | ||
| const scenarios = new Map<MockScenarioName, ScenarioFn<T>>(); | ||
|
|
||
| const instance: AutoAPIMockInstance<T> = { | ||
| defaultValue, | ||
|
|
||
| generatedHandler(info: ResponseResolverInfo) { | ||
| // Check for header-based scenario activation (for browser/dev testing) | ||
| const headerScenario = info.request.headers.get(SCENARIO_HEADER); | ||
| if (headerScenario) { | ||
| const scenarioFn = scenarios.get(headerScenario as MockScenarioName); | ||
| if (scenarioFn) { | ||
| // Temporarily apply scenario and get the handler | ||
| const previousHandler = overrideHandlerFn; | ||
| scenarioFn(instance); | ||
| const result = overrideHandlerFn | ||
| ? overrideHandlerFn(defaultValue, info) | ||
| : HttpResponse.json(defaultValue as JsonBodyType); | ||
| // Restore previous state | ||
| overrideHandlerFn = previousHandler; | ||
| return result; | ||
| } | ||
| } | ||
kantord marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| if (overrideHandlerFn) { | ||
| return overrideHandlerFn(defaultValue, info); | ||
| } | ||
| return HttpResponse.json(defaultValue as JsonBodyType); | ||
| }, | ||
|
|
||
| override(fn: OverrideFn<T>) { | ||
| return instance.overrideHandler((data, info) => | ||
| HttpResponse.json(fn(data, info) as JsonBodyType), | ||
| ); | ||
| }, | ||
|
|
||
| overrideHandler(fn: OverrideHandlerFn<T>) { | ||
| overrideHandlerFn = fn; | ||
| return instance; | ||
| }, | ||
|
|
||
| scenario(name: MockScenarioName, fn: ScenarioFn<T>) { | ||
| scenarios.set(name, fn); | ||
| return instance; | ||
| }, | ||
|
|
||
| activateScenario( | ||
| name: MockScenarioName, | ||
| options?: ActivateScenarioOptions, | ||
| ) { | ||
| const scenarioFn = scenarios.get(name); | ||
| if (!scenarioFn) { | ||
| if (options?.fallbackToDefault) { | ||
| return instance; | ||
| } | ||
| throw new Error( | ||
| `Scenario "${name}" not found. Available scenarios: ${[...scenarios.keys()].join(", ") || "(none)"}`, | ||
| ); | ||
| } | ||
| return scenarioFn(instance); | ||
| }, | ||
|
|
||
| reset() { | ||
| overrideHandlerFn = null; | ||
| return instance; | ||
| }, | ||
| }; | ||
|
|
||
| registry.add(instance as AutoAPIMockInstance<unknown>); | ||
|
|
||
| return instance; | ||
| } | ||
|
|
||
| export function resetAllAutoAPIMocks(): void { | ||
| for (const instance of registry) { | ||
| instance.reset(); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Activate a scenario globally across all registered mocks. | ||
| * Mocks that don't have the scenario defined will silently use their default. | ||
| */ | ||
| export function activateMockScenario(name: MockScenarioName): void { | ||
| for (const instance of registry) { | ||
| instance.activateScenario(name, { fallbackToDefault: true }); | ||
| } | ||
| } | ||
kantord marked this conversation as resolved.
Show resolved
Hide resolved
|
||
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.