saunders
saunders

Reputation: 989

Jest mock callback function from a promise

I am trying to test a function inside my component which is only called when the API request is successful. For context when you click a button I call this function:

return onUpdate(params, setError, success, cancel);

and when it is successful it calls the success function:

const success = (data) => {
  // do some stuff when successful
};

The onUpdate function is imported and is the API request which looks like this:

const onUpdate = (params, onError, onSuccess, onCancel) => {
  save(params)
    .then((data) => {
      if (onSuccess) {
        onSuccess(data.data);
      }
    })
    .catch((error) => {
      if (axios.isCancel(error)) {
        if (onCancel) {
          onCancel();
        }
      } else {
        onError(error);
      }
    });
};

I have been mocking the implementation of this function in my tests like so:

jest.mock('../../dataAccess', () => ({
  onUpdate: jest
    .fn()
    .mockImplementation(
      (params, onError, onSuccess) =>
        new Promise((resolve) => resolve(onSuccess(response))),
    ),
}));

From reading the docs / stack overflow it looks like a callback is passed in an example question and if I add the other params and add cb as the last param it still doesn't seem to fire my success function.

What do I need to mock to get my test to call my success function in my component? I am sure it is something very small but not quite sure what.

Upvotes: 1

Views: 5670

Answers (1)

Dori Aviram
Dori Aviram

Reputation: 322

When you return a new Promise its basically covert you function from callback based to async function, try to do something similar to:

jest.mock('../../dataAccess', () => ({
  onUpdate: jest
    .fn()
    .mockImplementation(
      (params, onError, onSuccess) => {
        onSuccess(response)
      }
    ),
}));

Or even easier:

jest.mock('../../dataAccess', () => ({
  onUpdate: (params, onError, onSuccess) => {
     onSuccess(response)
  }
}));

Upvotes: 1

Related Questions