Home > Blockchain >  How to mock fetch response using jest-fetch-mock
How to mock fetch response using jest-fetch-mock

Time:06-25

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.

CodePudding user response:

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
        
    });

CodePudding user response:

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())
  })
});
  • Related