I have the below Middleware class which I want to unit test:
const jwt = require('jsonwebtoken');
const config = require('../config/auth.config.js');
const db = require('../models');
const User = db.user;
const Role = db.role;
isAdmin = (req, res, next) => {
User.findById(req.userId).exec((err, user) => {
if (err) {
res.status(500).send({ message: err });
return;
}
Role.find(
{
_id: { $in: user.roles }
},
(err, roles) => {
console.log('Made it here Role');
console.log(JSON.stringify(roles));
console.log(roles);
if (err) {
console.log(err);
res.status(500).send({ message: err });
return;
}
for (let i = 0; i < roles.length; i++) {
if (roles[i].name === 'admin') {
next();
return;
}
}
res.status(403).send({ message: 'Require Admin Role!' });
return;
}
);
});
};
I'm able to mock the User.findById, the config the jsonwebtoken, but I'm not able to correctly stub the Role.find(... This is my current test spec using Mocha and Chai, Sinon and Proxyquire
const chai = require('chai');
const proxyquire = require('proxyquire');
const sinon = require('sinon');
const mongoose = require('mongoose');
chai.should();
var expect = chai.expect;
describe('Verify AuthJWT class', () => {
let mockAuthJwt;
let userStub;
let roleStub;
let configStub;
let jwtStub;
let json;
let err;
let json1;
let err1;
before(() => {
userStub = {
exec: function (callback) {
callback(err, json);
}
};
roleStub = {
find: function (query, callback) {
console.log('Heree');
return callback(err1, json1);
}
};
configStub = {
secret: 'my-secret'
};
jwtStub = {
verify: function (token,
secretOrPublicKey, callback) {
return callback(err, json);
}
};
mockAuthJwt = proxyquire('../../../middlewares/authJwt.js',
{
'User': sinon.stub(mongoose.Model, 'findById').returns(userStub),
'db.role': sinon.stub().returns(roleStub),
'../config/auth.config.js': configStub,
'jsonwebtoken': jwtStub
}
);
});
describe('isAdmin function', () => {
it('should Pass when user is Admin', (done) => {
err = null;
json = { roles: ['5ef3bd3f4144ae5898347e4e'] };
err1 = {};
json1 = [{ _id: '5ef3bd3f4144ae5898347e4e', name: 'admin', __v: 0 }];
let fakeRes = {
status: sinon.stub().returnsThis(),
send: sinon.stub()
};
let fakeReq = {
body: { userId: '123', email: 'test@test.com', roles: ['admin'] }
};
let fakeNext = sinon.spy();
mockAuthJwt.isAdmin(fakeReq, fakeRes, fakeNext);
expect(fakeNext.calledOnce).to.be.true;
console.log('Status ' + fakeRes.status.firstCall.args[0]);
done();
});
Any inside on how to correctly use the proxyquire mock and stub the Role.find method so I can unit test the function correctly.