2

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.

2
  • please read this stackoverflow.com/help/how-to-ask. Share the snippet you have tried so far. Commented Jan 29, 2022 at 18:20
  • 1
    are you using enzyme or react testing library? Commented Feb 1, 2022 at 5:26

2 Answers 2

2

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' } }
    });
});
Sign up to request clarification or add additional context in comments.

Comments

0

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.