@react-mock/fetch

Mock Fetch requests declaratively

Usage no npm install needed!

<script type="module">
  import reactMockFetch from 'https://cdn.skypack.dev/@react-mock/fetch';
</script>

README

Fetch requests

A declarative wrapper for the wonderful fetch-mock.

Note: FetchMock mocks the global Fetch API, so only one FetchMock instance should be rendered at once.

import { FetchMock } from '@react-mock/fetch';

// Passing fetch-mock options
render(
  <FetchMock options={{ matcher: '/login', response: 401, method: 'POST' }}>
    <MyComponent />
  </FetchMock>
);

// Passing fetch-mock config
render(
  <FetchMock
    matcher="/posts"
    response={200}
    config={{ fallbackToNetwork: true }}
  >
    <MyComponent />
  </FetchMock>
);

Multiple mocks

render(
  <FetchMock
    mocks={[
      { matcher: '/users', response: [{ id: 123 }] },
      { matcher: '/user/123', response: { name: 'Jessica' } }
    ]}
  >
    <MyComponent />
  </FetchMock>
);

Inspection

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.

import { fetchMock } from '@react-mock/fetch';

const [, { body }] = fetchMock.lastCall('/login', 'POST');
expect(JSON.parse(body)).toEqual({ user: 'harry' });