I want MSW to break the test case when an request is not mocked.
I've tried to modify onUnhandledRequest
but with no success.
Component:
import React, { useState } from 'react';
import Child from './Child';
const ExampleComponent: React.FC = () => {
const [data, setData] = useState(null);
fetch('http://example.com/movies.json')
.then((response) => response.json())
.then((d) => setData(d));
return (
<>
<h1>This is a header</h1>
<Child data={data} />
</>
);
};
export default ExampleComponent;
and test case:
import * as React from 'react';
import { render } from '@testing-library/react';
import ExampleComponent from './ExampleComponent';
describe('ExampleComponent', () => {
test('should render error message', () => {
const { getByText } = render(<ExampleComponent />);
expect(getByText('This is a header')).toBeInTheDocument();
});
});
This will result in a unhandled request in the MSW mock server:
beforeAll(() => {
server.listen({
onUnhandledRequest(req) {
// eslint-disable-next-line no-console
console.error(
'Found an unhandled %s request, with query %s query %s and variables %s',
req.method,
req.url.href,
req.body?.query,
req.body?.variables,
);
},
});
});
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
Message:
console.error
Found an unhandled GET request, with query http://example.com/movies.json query undefined and variables undefined
44 | onUnhandledRequest(req) {
45 | // eslint-disable-next-line no-console
> 46 | console.error(
| ^
47 | 'Found an unhandled %s request, with query %s query %s and variables %s',
48 | req.method,
49 | req.url.href,
at onUnhandledRequest (src/setupTests.tsx:46:21)
at onUnhandledRequest (../node_modules/msw/src/utils/request/onUnhandledRequest.ts:226:5)
at handleRequest (../node_modules/msw/src/utils/handleRequest.ts:80:5)
at ../node_modules/msw/src/node/SetupServerApi.ts:69:24
Wanted behavior is a fail of the test case if one misses to add a mock for the request. I want this since the project is large and I've seen some developers missing to add mock for all requests.