我有以下要进行单元测试的中间件类:
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;
}
);
});
};
我能够模拟 User.findById,配置 jsonwebtoken,但我无法正确存根 Role.find(... 这是我当前使用 Mocha 和 Chai、Sinon 和 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();
});
关于如何正确使用 proxyquire 模拟和存根 Role.find 方法的任何内部信息,以便我可以正确地对函数进行单元测试。