Use case is I need to stub a method that returns an object with a save method which in real code is a promise. In my test I want to verify that the arg data was constructed properly AND allow the promise method to be called without error:
const reservation = store.createRecord('reservation', {
payment_options: [{
count: 1,
payment_option_id: get(this, 'selectedOption.payment_option_id'),
type: get(this, 'selectedOption.payment_option_type')
}],
});
try {
yield reservation.save();
} catch (err) {
this.showErrors(err);
}
Currently if I do stub(this.store, 'createRecord').withArgs('reservation').returnsArg(1), I have no way to attach a save() method onto the returned object. Without being able to do that, my test will always fail as the try/catch block throws with object has no save method.
Again I want to be able to test e.g. payment_option_id: get(this, 'selectedOption.payment_option_id'), was constructed properly.
I tried playing with sinon.addBehavior but the fake object has no access to the args from what I could tell and since it magically ignores the return value, there was no way to build what I'm proposing here.
The api could look like sinon.stub(thing, 'method').returnsArg(1).assign(<fooObject>) or returnsArgWithContext(n, <fooObject>) etc
PSS I was thinking it could be nice if the sinon.js stub.returnX methods accepted an optional callback form where you could do e.g.:
stub(store, 'createRecord').returnsArg(1, (obj) => { return <modified first-arg-obj> })
Currently if I do stub(this.store, 'createRecord').withArgs('reservation').returnsArg(1), I have no way to attach a save() method onto the returned object.
I think you can do it with .callsFake http://sinonjs.org/releases/v4.2.2/stubs/#stubcallsfakefakefunction. It gives you access to passed parameters.
var sinon = require("sinon")
var stub = sinon.stub().callsFake(function(type, record) {
record.save = function() { console.log('saved ' + this.id); }
return record;
});
var record = stub('reservation', {id: 10});
record.save();
ok thanks ill try that! :D
Most helpful comment
I think you can do it with
.callsFakehttp://sinonjs.org/releases/v4.2.2/stubs/#stubcallsfakefakefunction. It gives you access to passed parameters.