Introduction
There are lots of mockXXXOnce functions in Jest API, for example:
These functions are only mocked on the first call, all the subsequent calls will use the original implementations or return the original values.
Be careful when using such functions, it may not be what you want, take the following code as example:
1 | export class AppComponent { |
Here are the test codes, the first one pass test, but the second one will failed. Do you know why?
1 | it(`should return 5+ hours`, () => { |
Because the first test case only reach the first if
branch in getDuration
function, it only call getIdleTime
once. So there is no problem.
But the second test case need to reach the second if
branch in getDuration
function, but the mock only take effect in the first if branch, the second branch will still use the original implementation of getIdleTime
function, so the test failed.
To fix this issue, you can use mockImplementation
instead of mockImplementationOnce
in the second test case.