Alternative to spyOn().and.callfake in Jestjs

javascript, jestjs

Solution

jest.spyOn official documentation gives a great answer:

Note: By default, jest.spyOn also calls the spied method. This is different behavior from most other test libraries. If you want to overwrite the original function, you can use jest.spyOn(object, methodName).mockImplementation(() => customImplementation) or object[methodName] = jest.fn(() => customImplementation);

So in your case just pass a fake method to `customImplementation`.

Problem

I used to have `spyOn().and.callFake` in jasmine and it helps a lot in my tests, now I'm using Jest, I've found in the doc that `jest.spyOn()` exist but without the `callFake`. My Question: How to spy on a method and call Fake with Jest and `expect`?

Original source