Search code examples
node.jsmocha.jssinonkue

Sinon stub chained methods


I have the following code in my SailsJs controller:

Jobs.create('beginImport', {
    version: version
}).save(function(err){
    if(err) {
        return res.serverError(err);
    }
    res.ok({ info: "import started" });
});

And in my test I am trying to stub Jobs like this:

var save = { save: sinon.stub() };
sinon.stub(Jobs, "create").returns(save);

However my test times out after 2000 ms and fails.

How can I stub these methods so that the test passes?


Solution

  • Your stub should call the function that is passed to it using stub.callsArg(index); or related functions.

    var save = { save: sinon.stub() };
    

    should become

    var save = { save: sinon.stub().callsArg(0) };
    

    if you don't need to pass in any parameters, or

    var save = { save: sinon.stub().callsArgWith(0, new Error('error')) };
    

    if you need to test the error.