Search code examples
node.jstypescriptdependency-injectionsinon

Fake return value of function call, each call with different data


I have function which I would like to fake using sinon. I inject faked function using DI.

Usually I do fake.resolves(result) but I cannot change resolved value during test.

I execute function three times and I expect different result each time. I would like to do something like here fake.resolvesEach([result1, result2, result3]).

What could I use to solve my problem?


Solution

  • You should use onCall(n) function

    Sample 1:

    const FetchStub = sinon
     .stub()
     .onCall(0)
     .resolves(serviceAccountAccessTokenRes)
     .onCall(1)
     .resolves(signJsonClaimRes)
     .onCall(2)
     .resolves(getTokenRes)
     .onCall(3)
     .resolves(makeIapPostRequestRes);
    const sample = getSample(FetchStub);
    

    Sample 2:

    
    describe("stub", function () {
        it("should behave differently on consecutive calls", function () {
            const callback = sinon.stub();
            callback.onCall(0).returns(1);
            callback.onCall(1).returns(2);
            callback.returns(3);
    
            assert.equals(callback(), 1); // Returns 1
            assert.equals(callback(), 2); // Returns 2
            assert.equals(callback(), 3); // All following calls return 3
        });
    });
    

    You can read documents in https://sinonjs.org/releases/latest/stubs/