Waiting for a sinon stubbed promise to resolve within a function before asserting values on a Sinon spy

921 views
Skip to first unread message

George Hattrell

unread,
Oct 24, 2017, 8:33:08 AM10/24/17
to Sinon.JS
I have a middleware function which checks a session token to see if the user is an admin user. The function does not return anything if all checks pass but simply calls next(). 

How can I wait for the internal asynchronous Promise (adminPromise) to resolve before making assertions on the next() callback which is a Sinon spy? The test will currently fail because the assertion in the test is made before the resolution of the promise in AdminMiddleware.prototype.run.

The function and test are below.


AdminMiddleware.prototype.run = function (req, res, next) {
  let token        = req.header(sessionTokenHeader);
  let adminPromise = new admin().send()

  adminPromise.then(function (authResponse) {
    let adminBoolean = JSON.parse(authResponse).payload.admin;

    if (adminBoolean !== true) {
      return new responseTypes().clientError(res, {
          'user': 'validation.admin'
      }, 403);
    };

    next();
  });
};
it('should call next once if admin', function (done) {
  stub = sinon.stub(admin.prototype, 'send');
  stub.resolves(JSON.stringify({success : true, payload : {admin : true}}));
  let nextSpy = sinon.spy();

  AdminMiddleware.prototype.run({header: function (token) {}}, {}, nextSpy);
    expect(nextSpy.calledOnce).to.be.true;
    done();
});

Raghunandan Ghagharvale

unread,
Jan 6, 2018, 10:38:52 AM1/6/18
to Sinon.JS
+1
Reply all
Reply to author
Forward
0 new messages