Mock Fetch requests declaratively
npm install @react-mock/fetchA declarative wrapper for the wonderful fetch-mock.
> Note: FetchMock mocks the global Fetch API, so only one FetchMock instance should be rendered at once.
``js
import { FetchMock } from '@react-mock/fetch';
// Passing fetch-mock options
render(
);
// Passing fetch-mock config
render(
response={200}
config={{ fallbackToNetwork: true }}
>
);
`
`js`
render(
{ matcher: '/users', response: [{ id: 123 }] },
{ matcher: '/user/123', response: { name: 'Jessica' } }
]}
>
);
See fetch-mock's inspection methods to check how fetch was called.
> Note: Import fetchMock from @react-mock/fetch to ensure you're inspecting on the right fetch-mock instance.
`js
import { fetchMock } from '@react-mock/fetch';
const [, { body }] = fetchMock.lastCall('/login', 'POST');
expect(JSON.parse(body)).toEqual({ user: 'harry' });
``