我正在尝试测试特定路线的行为。即使我创建存根,它也会继续运行中间件。我希望事件认证暂时通过。我了解到,这并不是真正的“单元”测试。我快到那里了。我还简化了代码。这是要测试的代码:
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(); }); }); });
我尝试过其他类似的问题,但是我仍然从中间件中获取403,应该跳过它。我还以调试模式运行测试,因此我知道应该存根的中间件功能仍在运行。
这是存根我的代码的问题吗?这是ES6问题吗?
我可以重组我的代码或测试以使其正常工作吗?
存根代码确实存在问题。
当您需要服务器文件时
const app = require('../server/server.js');
您的应用是通过包括在内的整套中间件创建的,并且在中间rejectUnauthenticated存储了对中间件的引用app。
rejectUnauthenticated
app
当你做
sinon.stub(authenticationMiddleware, 'rejectUnauthenticated') .callsFake(async (req, res, next) => next());
您将替换模块的rejectUnauthenticated导出方法authenticationMiddleware,而不是替换rejectUnauthenticated已存储的原始引用。
authenticationMiddleware
解决方案是 在 模拟外部中间件方法 后 创建应用程序(即require('../server/server.js');): __
require('../server/server.js');
const chai = require('chai'); const chaiHttp = require('chai-http'); const sinon = require('sinon'); // don't create app right away 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()); // method is stubbed, you can create app now 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(); }); }); });