Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I stub a chain of methods in Sinon?

I know how to use stub to replace one function.

sandbox.stub(Cars, "findOne",
            () => {return car1 });

But now I have a line in my function I want to test that I need to stub that looks like this

Cars.find().fetch()

So there is a chain of function here and I'm unsure what I need to do. How do I stub "find" to return something that I can use to stub "fetch"?

like image 355
Diskdrive Avatar asked Jun 21 '16 15:06

Diskdrive


People also ask

How do you stub a dependency of a module?

To stub a dependency (imported module) of a module under test you have to import it explicitly in your test and stub the desired method. For the stubbing to work, the stubbed method cannot be destructured, neither in the module under test nor in the test.

How do you stub a promise in Sinon?

To stub a promise with sinon and JavaScript, we can return a promise with a stub. import sinon from "sinon"; const sandbox = sinon. sandbox. create(); const promiseResolved = () => sandbox.

What does sandbox stub do?

sandbox.Causes all stubs and mocks created from the sandbox to return promises using a specific Promise library instead of the global one when using stub. rejects or stub. resolves . Returns the stub to allow chaining.


2 Answers

IMHO, we can just use returns to do this. We don't need to use callsFake or mock it as function.

// Cars.find().fetch()

sinon.stub(Cars, 'find').returns({
  fetch: sinon.stub().returns(anything);
});

in case, if there is another method after fetch(), we can use returnsThis()

// Cars.find().fetch().where()

sinon.stub(Cars, 'find').returns({
  fetch: sinon.stub().returnsThis(),
  where: sinon.stub().returns(anything);
});

Ref: https://sinonjs.org/releases/v6.3.3/

Hope it helps

like image 183
deerawan Avatar answered Sep 28 '22 04:09

deerawan


Try this:

sandbox.stub(Cars, "find", () => {
    return {
        fetch: sinon.stub().returns(anything);
    };
});
like image 40
aprok Avatar answered Sep 28 '22 06:09

aprok