We are moving a repo from sinon stubs to jest, and I'm having trouble with this mock. What I want to do is call the actual implementation on the first call, then mock the rest of the calls. This function is recursive, so we want the first call to call the actual implementation, then mock the recursive calls.
In sinon, it was done like this
const stub = sandbox.stub(instance, 'function');
stub
.onFirstCall()
.callsFake(stub.wrappedMethod)
.callsFake((args) => args);
I would like to do something like this, but cannot find the actual implementation on the jest spy or mock instance. Is this simply not possible?
const spy = jest.spyOn(instance, 'function');
spy
.mockImplementationOnce(spy.mock.actual) // ???
.mockImplementation((args) => args);
Why can't you do something similar to as follows?
const spy = jest.spyOn(instance, 'function');
spy
.mockImplementationOnce(() => originalInstanceFunction())
.mockImplementation((args) => args);
Here is an example implementation - Note had to store a reference to the original instance function
const original = {
func: (args) => { console.log(`original ${args}`)}
};
describe('test', () => {
it('should call original then mock', () => {
const originalFunction = original.func;
const spy = jest.spyOn(original, 'func');
spy.mockImplementationOnce((args) => originalFunction(args))
.mockImplementation((args) => console.log(`mock ${args}`));
original.func('test-args');
original.func('test-args');
expect(spy).toBeCalledTimes(2);
});
});
Outputs:
console.log
original test-args
at originalFunction (test.test.js:2:28)
console.log
mock test-args
at Object.spy.mockImplementationOnce.mockImplementation.args (test.test.js:12:42)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With