mardi 24 février 2015

A stub that returns a stub

Let's say you have code that returns an object containing pre-programmed functions, which you use like this:



someFunction(/* pass in data */)
.post(/* some data */) //Returned post function is pre-programmed to send a POST request to the right URL
.then(function() {
//do something
});


How can I unit test this using sinon.js?


To direct what a function returns, you need to use a stub:



var mockService = sinon.stub();
mockService.returns(/* some return value */);


But let's say I want to verify that someFunction was called with the right arguments, in addition to verifying that the returned post function was called with the right arguments. I would need a stub to return a stub:



mockService.returns({
post: sinon.stub()
});


How can I access mockService.post to verify that the right arguments were passed, in this case?


Bonus Question: What's the name of this design pattern (returning a function with pre-programmed behavior)? I've seen it used before, but don't know the name of it.


Aucun commentaire:

Enregistrer un commentaire