Jest — mockReset for afterEach affect toHaveBeenCalledTimes
Published in
1 min readNov 7, 2019
Problem
I used Jest to mock the function for unit test on the nodeJS application. I ran into a situation that the toHaveBeenCalledTimes actual value not correct for the second ‘it’ test case. The called times count was one more than the expected value.
Therefore, I though that it may accumulate the previous toHaveBeenCalledTimes count for the first test case. Then I found out that I didn’t call mockReset for this newly used method.
Solution
I added the function.mockReset() in the afterEach hook and the count was matched after. This way will reset toHaveBeenCalledTimes for the mock function after each test case.
afterEach(() => {
function.mockReset();
});expect(function).toHaveBeenCalledTimes(1);