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