Jest - How to get code coverage for callback inside promise?

Viewed 244

When running a coverage test, I am unable to get a specific block of code to be covered. It's a promise with a callback function (which sets the react state), but I am having a hard time getting the callback function to be covered correctly in the coverage test. Here is the unit test:

TestPage.test.js

it('Handle form submit for entity with processToWaitFor', () => {
    const wrapper = shallow( <TestPage data={{ processToWaitFor: 'submission' }} /> );
    wrapper.instance().setState({ redirect: false });
    wrapper.instance().submitForm();
    
    const checkEntityFormStatus = jest.fn().mockImplementation(() => Promise.resolve('ended'));
    const mockCallbackFunc = () => { wrapper.instance().setState({ redirect: true }) };
    expect(checkEntityFormStatus('', '', '', mockCallbackFunc())).resolves.toBe('ended');
    expect(wrapper.state().redirect).toEqual(true);
});

TestPage.js

submitForm = () => {
    const {processToWaitFor} = this.props.data;
    if (processToWaitFor) {
        return checkEntityFormStatus( // Defined in APIcalls.js below
            entity,
            token,
            processToWaitFor,
            (response) => {
                // Unit test not covering this callback which sets the state
                this.setState({redirect: true});
                return response;
            }
        );
    }
}

APIcalls.js

export const checkEntityFormStatus = (
  entity,
  token,
  processToWaitFor,
  callback
) => {
  const fetchStatus = async (n) => {
      try {
        const response = await API.checkEntityFormStatus(entity, token, processToWaitFor).then(API.handleResponse);
        if (response == 'ended') {
          return callback(response);
        } else {
          return new Error('No Status');
        }
      } catch (error) {
        throw error;
      }
  };
};

Any idea how to get the unit test should look like so our coverage test covers the callback which sets the state when response is 'ended' from checkEntityFormStatus?

0 Answers
Related