使用Sinon对auth功能进行存根和恢复仍会导致使用存根进行Mocha测试
我们试图在一些快速应用程序中存在一个身份验证中间件,而不是我们的所有测试,我们在为我们制作存根工作时遇到了麻烦。
我们的mocha测试看起来像这样:describe('primaryDeal routes unit test',()=> {
describe('Authentication allows for data fetching', () => {
let app;
let getPrimaryDealData;
let queryParams;
let isAuthenticated;
let count = 0;
beforeEach(() => {
// console.log(isAuthenticated);
if (count === 0) {
isAuthenticated = sinon.stub(authCheck, 'isAuthenticated');
isAuthenticated.callsArg(2);
}
app = require('../../lib/index.js');
});
afterEach(() => {
if (count === 0) {
isAuthenticated.restore();
}
app.close();
count++;
});
it(('should send an API request, validate input and return 200 response'), () => {
return chai.request(app)
.get('/api/contracts/')
.then((res) => {
expect(res).to.have.status(200);
});
});
it(('should respond with forbidden'), () => {
app = require('../../lib/index.js');
return chai.request(app)
.get('/api/contracts/')
.catch((res, err) => {
expect(res).to.have.status(403);
});
});
});
});
我们的存根就像第一个it
一样工作,但是存根似乎没有为第二个it
恢复,我们的身份验证中间件没有被运行。如果另一个被注释掉,两个测试都有效。
我们已经尝试在不同的文件中分离这些块,并且在不同的describe
块中,我们也尝试切换it
块的顺序,我们尝试给两个chai.request(app)
单独的服务器,但我们不知所措。
为什么我们的第二个it
声明不会调用我们的Auth中间件?
我建议你使用沙盒。使用起来更优雅。无需单独恢复存根。这是一个示例:
let sandbox;
beforeEach(() => {
sandbox = sinon.sandbox.create();
isAuthenticated = sandbox.stub(authCheck, 'isAuthenticated');
});
afterEach(() => {
sandbox.restore();
});