Skip to content

Commit

Permalink
fix: throw on invalid request handlers value in ".use()" (#1876)
Browse files Browse the repository at this point in the history
  • Loading branch information
kettanaito authored Nov 24, 2023
1 parent f188d77 commit ce73dfe
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 11 deletions.
26 changes: 15 additions & 11 deletions src/core/SetupApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,12 @@ export abstract class SetupApi<EventsMap extends EventMap> extends Disposable {
constructor(...initialHandlers: Array<RequestHandler>) {
super()

this.validateHandlers(...initialHandlers)
invariant(
this.validateHandlers(initialHandlers),
devUtils.formatMessage(
`Failed to apply given request handlers: invalid input. Did you forget to spread the request handlers Array?`,
),
)

this.initialHandlers = toReadonlyArray(initialHandlers)
this.currentHandlers = [...initialHandlers]
Expand All @@ -41,20 +46,19 @@ export abstract class SetupApi<EventsMap extends EventMap> extends Disposable {
})
}

private validateHandlers(...handlers: ReadonlyArray<RequestHandler>): void {
private validateHandlers(handlers: ReadonlyArray<RequestHandler>): boolean {
// Guard against incorrect call signature of the setup API.
for (const handler of handlers) {
invariant(
!Array.isArray(handler),
devUtils.formatMessage(
'Failed to apply given request handlers: invalid input. Did you forget to spread the request handlers Array?',
),
this.constructor.name,
)
}
return handlers.every((handler) => !Array.isArray(handler))
}

public use(...runtimeHandlers: Array<RequestHandler>): void {
invariant(
this.validateHandlers(runtimeHandlers),
devUtils.formatMessage(
`Failed to call "use()" with the given request handlers: invalid input. Did you forget to spread the array of request handlers?`,
),
)

this.currentHandlers.unshift(...runtimeHandlers)
}

Expand Down
11 changes: 11 additions & 0 deletions test/node/msw-api/setup-server/use.node.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,3 +126,14 @@ test('returns a mocked response from a one-time request handler override only up
expect(anotherBookResponse.status).toBe(200)
expect(await anotherBookResponse.json()).toEqual({ title: 'Original title' })
})

test('throws if provided the invalid handlers array', async () => {
expect(() =>
server.use(
// @ts-expect-error Intentionally invalid input.
[http.get('*', () => new Response())],
),
).toThrow(
'[MSW] Failed to call "use()" with the given request handlers: invalid input. Did you forget to spread the array of request handlers?',
)
})

0 comments on commit ce73dfe

Please sign in to comment.