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

Issue

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/

Answered By – Pooya

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published