9

I am calling api in the the react functional component. I am writing unit test cases of the component. I have mocked fetch using jest-fetch-mock.

global.fetch = require('jest-fetch-mock');

Component.ts

const Component = () => {

    useEffect(() => {
      return fetch(
          'url',
        )
          .then(response => response.json())
          .then(json => {
            setApiResult(json);
            setFilterResult(json?.videos);
          })
          .catch(error => {
            console.error(error);
          });
    }, []);

}

Does anyone know how to mock the fetch response for this component in jest.

Ajay S
  • 48,003
  • 27
  • 91
  • 111
  • I know it's not what you're looking for, but I've recently discovered [msw](https://mswjs.io/) and I'll never mock fetch again! – Adam Jenkins Jun 30 '22 at 23:14

2 Answers2

5

This one is from jest-fetch-mock docs directly

  • Create a file setupJest.js file in root directory of project with following content.
require('jest-fetch-mock').enableMocks()
  • Add the setupJest.js file to jest.config.js or package.json wherever your jest config is.
"jest": {
  "automock": false,
  "setupFiles": [
    "./setupJest.js"
  ]
}

now you can use fetch and fetchMock on global scope

describe('testing Component', () => {
  beforeEach(() => {
    fetch.resetMocks()
  })
 
  it('testing something...', () => {
    fetch.mockResponseOnce(JSON.stringify({ data: '12345' }))
    const container = render (<Component/>)
    // expect statement can be wrong.
    expect(container.getByText(/12345/).toBeDefined())
  })
});
Ashu Sahu
  • 417
  • 6
  • 7
  • This will send same response in each fetch. I am making two fetch calls in the useeffect. How to handle that ? – Ajay S Jun 26 '22 at 06:03
  • 1
    @AjayS you can mock multiple fetch with different responses too. `fetch.once(JSON.stringify({ data: 'abcde' }).once(JSON.stringify({ data: '12345' }))` this will resolve first fetch with `abcde` and second one with `12345` – Ashu Sahu Jun 26 '22 at 09:59
0

Here is small example for same using axios

jest.mock("axios");
 it('mock data', async () => {
        render(<Abc />);
        axios.get.mockResolvedValueOnce(data); // data is your static object
        // rest code goes here
        
    });
Aman Sadhwani
  • 2,902
  • 3
  • 16
  • 24