Search code examples
javascriptunit-testingsinonjasmine2.0sinon-chai

What's the equivalent of jasmine.createSpy().and.callFake(fn) in sinonjs


I'm looking for the equivalent of jasmine.createSpy().and.callFake(fn) in sinonjs.

For example:

const mySpy = jasmine.createSpy('my spy')
.and
.callFake((options) => Object.assign({}, {name: 'foo'}, options));

Solution

  • A spy that can modify the return value (of the optional wrapped function) is called a stub in Sinon parlance, so what you are looking for is the documentation on stubs. Your example would look like this:

    const myStub = sinon.stub().callsFake((options) => Object.assign({}, {name: 'foo'}, options));
    
    console.log(myStub().name === 'foo') // => 'true'
    

    Disclosure: I am part of the Sinon maintainer team.