存根代码确实存在问题。
当您需要服务器文件时
const app = require('../server/server.js');
您的应用是通过包括在内的整套中间件创建的,并且在中间rejectUnauthenticated
存储了对中间件的引用app
。
当你做
sinon.stub(authenticationMiddleware, 'rejectUnauthenticated')
.callsFake(async (req, res, next) => next());
您将替换模块的rejectUnauthenticated
导出方法authenticationMiddleware
,而不是替换rejectUnauthenticated
已存储的原始引用。
解决方案是 在 模拟外部中间件方法 后 创建应用程序(即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();
});
});
});