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?


You should use onCall(n) function

Sample 1:

const FetchStub = sinon
const sample = getSample(FetchStub);

Sample 2:

describe("stub", function () {
    it("should behave differently on consecutive calls", function () {
        const callback = sinon.stub();

        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