Sinon: Feature Request: Return stub using args AND allow modifying returned arg object

Created on 24 Jan 2018  路  2Comments  路  Source: sinonjs/sinon

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> })
Feature Request

Most helpful comment

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();

All 2 comments

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

Was this page helpful?
0 / 5 - 0 ratings