存根代码确实存在问题。
当您需要服务器文件时
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 awaylet 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('/pre-championship/registrant/event') .end((err, response) => { expect(response).to.have.status(200); authenticationMiddleware.rejectUnauthenticated.restore(); done(); }); });});
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)