An onUnhandledRequest error does not make the test fail #943
Replies: 4 comments 9 replies
-
|
Hey, @bennettdams. Could you please ensure you're using the latest version of the library?
You've chosen the right API: setting |
Beta Was this translation helpful? Give feedback.
-
|
see this behaviour in UPD tried "msw": "2.7.0", same behaviour, test passes, error is logged |
Beta Was this translation helpful? Give feedback.
-
|
I am also experiencing this issue with: Anyone figured out how to make tests fail successfully? 😆 |
Beta Was this translation helpful? Give feedback.
-
|
As I stumbled on this discussion not the first time, I'll publish the solution that worked for me in jest. It is the same as @Nilegfx published here for vite // ./hm-tests/unit-test-utils/mswServer.ts
import { setupServer } from 'msw/node';
export const mswServer = setupServer();
// ---------------------------------------
/*
jest.msw.setup.ts file – used in jestconfig in setupFilesAfterEnv like
setupFilesAfterEnv: [
'@testing-library/jest-dom',
'<rootDir>/jest.env.ts',
'<rootDir>/jest.msw.setup.ts',
],
*/
import { mswServer } from './hm-tests/unit-test-utils/mswServer';
const onUnhandledRequest = jest.fn().mockImplementation((req: any) => {
console.error(`
[jest.msw.setup.ts]
Error: intercepted a request without a matching request handler:
• ${req.method} ${req.url}
If you still wish to intercept this unhandled request, please create a request handler for it.
You can find all MSW handlers in blah/blah/index.ts file`);
});
beforeAll(() => {
mswServer.listen({ onUnhandledRequest: onUnhandledRequest });
});
afterEach(() => {
// this what makes individual tests fail when mock is missing
expect(onUnhandledRequest).not.toHaveBeenCalled();
// Reset the request handlers between each test.
// This way the handlers we add on a per-test basis
// do not leak to other, irrelevant tests.
mswServer.resetHandlers();
});
afterAll(() => {
// disable API mocking after the tests are done.
mswServer.close();
}); |
Beta Was this translation helpful? Give feedback.


Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I just started using MSW and found out that an
onUnhandledRequesterror does not make the test fail:Here's my config:
jest.config.jsmsw-setup.tsIs there something specific that has to be configured for my test to fail in such situations?
BTW: As a beginner of MSW, I looked for a solution to block all requests that are not handled via MSW. I still wanted to get notified of missing handlers, so using wildcards (e.g.
rest.get("*")) was not an option. The docs and also the console message whenonUnhandledRequestis "triggered" do not make this clear in my opinion. Without this discussion, I would've never known that the requests are also blocked (which is exactly what I wanted).Beta Was this translation helpful? Give feedback.
All reactions