Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest testing, call actual implementation on first call, mock the rest

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);
like image 902
Brobin Avatar asked Dec 06 '25 03:12

Brobin


1 Answers

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)
like image 180
jeeves Avatar answered Dec 08 '25 17:12

jeeves



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!