Jest: Mocking Conditional Function Calls
Solution 1:
As @balzee mentioned, you have to actually spy on the method you want to make assertions about. That causes Jest to replace the method with a special spy function that keeps track of the parameters it is called with, how many times it was called, and so on.
You should also provide a mock implementation for that function, so that you don't actually call out to Sentry when running your unit tests.
Finally, when spying on a method, you first pass the object the method is on, and then the name of the method as a string. Jest then replaces that property on the object with a spy function, that will call the original function if no mock implementation is given.
Without referencing the object the function exists on, you would just be changing what a local function variable points to, from the original/real function to a jest spy function. That won't change the function that the code you are testing invokes, so the test will fail.
So the final test should be:
handleError.test.js:
import * as sentry from'@sentry/browser'; // CHANGEDimport handleError from'../handleError';
classApiErrorextendsError {
constructor() {
super();
this.name = 'ApiError';
}
}
// added this to remove any spies/mocks after the testafterEach(() => {
jest.restoreAllMocks();
});
test('When an ApiError is returned with no action type, sentry is notified', () => {
const sampleError = newApiError();
// added next line
jest.spyOn(sentry, 'captureMessage').mockImplementation(() => {});
handleError(sampleError);
// note the use of `sentry.captureMessage`, which is now a jest spy fnexpect(sentry.captureMessage).toHaveBeenCalledWith('this is an error message.');
});
Post a Comment for "Jest: Mocking Conditional Function Calls"