Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different arguments/return values for sinon expectation

I'm writing unit tests for my module and use SinonJS to verify a couple of expectations regarding function calls to other modules. First, I register a mock for the other module:

var otherModule = {
    getConfig : function () {}
};

mockery.registerMock("otherModule", otherModule);

Later on, I run some tests and (successfully) verify some expectations such as:

var otherModuleMock = sinon.mock(otherModule);
otherModuleMock
    .expects("getConfig")
    .once()
    .withArgs("A")
    .returns(configValuesForA);

// run test

otherModuleMock.verify(); // <- succeeds

I run into a problem however, when the module calls the getConfig function twice, with different arguments:

otherModuleMock
    .expects("getConfig")
    .once()
    .withArgs("A")
    .returns(configValuesForA);

otherModuleMock
    .expects("getConfig")
    .once()
    .withArgs("B")
    .returns(configValuesForB);

From my understanding of the documentation, this should probably work. However, this results in the following error:

ExpectationError: Unexpected call: getConfig(A)
    Expectation met: getConfig(A[, ...]) once
    Expectation met: getConfig(B[, ...]) once

I tried replacing once() with atLeast(1) or removing it completely. I also tried capturing the expectation returned by otherModuleMock.expect("getConfig") and applying withArgs and returns on that instead. Both to no avail.

Pretty sure I'm using mock() in a way I'm not supposed to, but how should I go from here?

like image 633
tkers Avatar asked May 20 '26 02:05

tkers


1 Answers

Turns out the module I was testing actually calls getConfig 3 times: Once with A, once with B and then with A again.

And apparently Sinon keeps track of the order of all expectations/calls, which is the reason the test even failed when using atLeast(1) instead of once(). Makes sense when I look at it now, but these cases are not really documented extensively in the Sinon docs (in my own defence).

like image 75
tkers Avatar answered May 22 '26 22:05

tkers