【发布时间】:2019-05-20 01:01:00
【问题描述】:
我正在尝试测试特定路线的行为。即使我创建了一个存根,它也会继续运行中间件。我希望事件身份验证暂时通过。我知道此时它并不是真正的“单元”测试。我快到那里了。我还稍微简化了代码。这是要测试的代码:
const { rejectUnauthenticated } = require('../modules/event-authentication.middleware');
router.get('/event', rejectUnauthenticated, (req, res) => {
res.sendStatus(200);
});
这是我要跳过的中间件:
const rejectUnauthenticated = async (req, res, next) => {
const { secretKey } = req.query;
if (secretKey) {
next();
} else {
res.status(403).send('Forbidden. Must include Secret Key for Event.');
}
};
module.exports = {
rejectUnauthenticated,
};
测试文件:
const chai = require('chai');
const chaiHttp = require('chai-http');
const sinon = require('sinon');
let app;
const authenticationMiddleware = require('../server/modules/event-authentication.middleware');
const { expect } = chai;
chai.use(chaiHttp);
describe('with correct secret key', () => {
it('should return bracket', (done) => {
sinon.stub(authenticationMiddleware, 'rejectUnauthenticated')
.callsFake(async (req, res, next) => next());
app = require('../server/server.js');
chai.request(app)
.get('/code-championship/registrant/event')
.end((err, response) => {
expect(response).to.have.status(200);
authenticationMiddleware.rejectUnauthenticated.restore();
done();
});
});
});
我尝试过其他类似的问题,例如:How to mock middleware in Express to skip authentication for unit test? 和这个:node express es6 sinon stubbing middleware not working 但我仍然从应该跳过的中间件中获得 403。我还在调试模式下运行了测试,所以我知道应该存根的中间件函数仍在运行。
这是我的代码存根的问题吗?这是 ES6 的问题吗?
我可以重组我的代码或测试以使其工作吗?
【问题讨论】:
标签: node.js unit-testing mocha.js sinon chai