我正在使用摩卡咖啡,柴和Sinon测试一些已验证的API路由。我正在使用Passport.authenticate()作为中间件来验证路线:
const router = require('express').Router();
const passport = require('passport');
router.post('/route',
passport.authenticate('jwt', {session:false}),
function(req,res) {
return res.status(200);
});
module.exports = router;
然后,在我的测试套件中,我正在使用Sinon固定护照。
const chai = require('chai');
const chaiHttp = require('chai-http');
const sinon = require('sinon');
const passport = require('passport');
const server = require('../../app');
const expect = chai.expect;
chai.use(chaiHttp);
describe('route', function() {
before(function(done) {
sinon.stub(passport, 'authenticate').callsFake(function(test, args) {
console.log('Auth stub');
});
console.log('stub registered');
passport.authenticate('jwt', {session:false});
done();
});
after(function(done) {
console.log('after hook');
passport.authenticate.restore();
done();
});
describe('POST /route', function() {
it('should post', function(done) {
console.log('starting test');
chai.request(server)
.post('/route')
.end(function(err,res) {
expect(res).to.have.status(200);
done();
});
});
});
});
现在,当我运行测试套件时,我会看到它打印出以下内容:
route
stub registered
Auth stub
POST /route
starting test
1) should post
after hook
1 failing
1) route
POST /route
should post:
Uncaught AssertionError: expected { Object (_events, _eventsCount, ...) } to have status code 200 but got 401
从中,我们可以看到存根后的注册后,我可以在测试文件中称其为未经固执的文件。但是,当Passport.authenticate()在Route.Post()中调用时,它是实际的Passport.authenticate(),并以状态401发送响应,因为我没有认证。
对正在发生的事情有什么想法?
您的代码在运行后立即调用 因为您在 为了使这样的代码调用passport.authenticate
,并且一旦需要,它就会运行。stub
创建之前在测试开始时需要代码,您的代码最终调用了真实的passport.authenticate
。stub
,您必须在需要代码之前设置stub
::const chai = require('chai');
const chaiHttp = require('chai-http');
const sinon = require('sinon');
const passport = require('passport');
// const server = require('../../app'); <= don't require your code here...
const expect = chai.expect;
chai.use(chaiHttp);
describe('route', function () {
before(function (done) {
sinon.stub(passport, 'authenticate').callsFake(function (test, args) {
console.log('Auth stub');
});
console.log('stub registered');
passport.authenticate('jwt', { session: false });
done();
});
after(function (done) {
console.log('after hook');
passport.authenticate.restore();
done();
});
describe('POST /route', function () {
it('should post', function (done) {
console.log('starting test');
const server = require('../../app'); // <= require it AFTER creating the stub
chai.request(server)
.post('/route')
.end(function (err, res) {
expect(res).to.have.status(200);
done();
});
});
});
});
与辛农(Sinon
passport.authenticate = sinon.stub( passport, 'authenticate' )
.returns(
( req, res, next ) => {
const user = {
username: 'test user',
email: 'testuser@mail.com',
displayName: 'Test User',
provider: 'testCase',
roles: [ 'admin' ]
}
req.user = user;
next()
}
);
主要事项是:
- 将用户数据添加到req.user
- 执行next()代码流以继续进入下一个中间件
回顾一下,这不是实际测试您的身份验证策略的一种方式,而是绕过它,以防您要测试路由器结果。