Kousalya
Kousalya

Reputation: 760

Jest Unit test case for React functional component Api call

I am new to Jest Unit testing. I need to write a test case for a React functional Component. Below is the code snippet for API call

  useEffect(() => {
    getInitialData(props.id, props.baseUrl).then((response: any) => {
      setInitialResponse(response.initialResponse);
      if (props.initialData) props.initialData(response.initialResponse);
      setLoader(false);
    });
  }, []);

I don't know how to cover these lines in the jest test case. Passing id and baseUrl to this component, not covering lines after 'then'. I don't know How can I mock this also as it is present inside useEffect.

Upvotes: 2

Views: 2804

Answers (2)

Khushbu Patel
Khushbu Patel

Reputation: 329

This is the way I use the jest to test something after the API has finished fetching.

Create Mock Function, (May be in other file to be used by all test cases, change it the way you want to setup)

const mockAPI = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('foo');
  }, 300);
});

Define APIs

 import * as APIS from '~/api/[API_PATH]';

  const mockGetInitialData = (params = {}) =>
    jest
      .spyOn(APIS, 'getInitialData')
      .mockImplementation(() => mockAPI(params));

Test case

it('Initial Data loading Failed', async () => {
    mockGetInitialData({
      error: { errors: {name: 'Invalid Name' } }
    });
});

Upvotes: 2

diedu
diedu

Reputation: 20775

Assuming you import the getInitialData function from somewhere, a mock for that would look like this

  jest.mock("./getInitialData", () =>
    jest.fn().mockResolvedValue(initialResponseMock)
  );
  // rest of your test in here

The concept you are missing is that you need to use mockResolvedValue when mocking async code.

https://blog.jimmydc.com/mock-asynchronous-functions-with-jest/

Upvotes: 0

Related Questions