R.A. Lucas
R.A. Lucas

Reputation: 1161

Sinon stub pass through arguments

I want to be able to just return the arguments that a stub receives passed to a promise, is this possible:

Impl:

function(arg) {
   return db.find(arg)
     .then(result => {
        return fnIWantToStub(result);
      })
      .then(nextResult => {
         return done()
      });

Test:

var stub = sinon.stub(fnIWantToStub);
stub.returns(PassedThruArgsThatReturnsAPromise);

Can this be done?

Upvotes: 2

Views: 5101

Answers (1)

Justin Grayston
Justin Grayston

Reputation: 472

The docs state that you can return an arg at a given index.

stub.returnsArg(index);

I don't think there is a blanket return all args.

(UPDATE after question edit)

You could stub the db.find function and resolve it. I use mocha and chai.

const dbStub = sinon.stub(db, 'find');
const expected = {..};
dbStub.returns(Promise.resolve(someDataFixture));
const result = functionUnderTest(args);
// using chaiAsPromised
return expect(result).to.eventually.equal(expected);

Note you have to return to get Mocha to run through the promise. You can also use mocha's done callback. Although quite often I'll just use a Promise.

Checkout http://staxmanade.com/2015/11/testing-asyncronous-code-with-mochajs-and-es7-async-await/

Upvotes: 2

Related Questions