I have a problem understanding the behaviour of sinonjs spies.
This is my test:
asyncTest('sinon async spies test',
function() {
var pApi =
{
product: function(id, options) {
var d = { o: 'a result' };
options.success(d);
return d;
},
};
this.spy(pApi, 'product');
pApi.product(1, { success: function(data) {} });
//Assertion 1
ok(pApi.product.calledOnce, 'product API called: ' +
pApi.product.calledOnce);
setTimeout(
function() {
//Assertion 2
ok(pApi.product.calledOnce,
'product function called once (calledOnce: ' +
pApi.product.calledOnce + ')');
start();
}, 1000);
});
Running the above test with qunit and sinonjs (via sinon-qunit), I pass Assertion 1 but fail the Assertion 2 (within the setTimeout callback). In fact, when we log the value of pApi.product.calledOnce in the console (as is done via the assertion’s message), it is undefined.
Note: I have this at the top of my test file:
sinon.config.useFakeTimers = false;
Could anyone explain this curious behaviour? Shouldn’t pApi.product within the setTimeout callback and without both have calledOnce as a valid property of the spy?
Updated
Based on http://api.qunitjs.com/asyncTest/, I figured out why the above behaviour is displayed.
asyncTest does not run the testrunner until the start() function is called. The above test worked when I changed this.spy(pApi, 'product') to sinon.spy(pApi, 'product'). Apparently there is a dependency on whether test is used instead of asyncTest, which affects when the this.spy method is run.
Will need to actually look at the sinon, qunit and sinon-qunit code in order to figure this one out.
You should assign the spy to a variable, and use that to assert calledOnce:
This will pass both assertions. I think the problem has to do with Sinon restoring the method at the end of the test function, even though QUnit is still waiting for
start()to indicate the test is complete. When your timeout function is invoked,pApi.productis no longer a spy object, so it does not have a calledOnce property. Setting the spy to its own variable allows you to keep a handle on it until the timeout is called.