我试图在我的Node App中使用Sinon设置中间件的存根。当我运行mocha测试并直接指向测试文件时,它会正确地存根。当我指向我的所有测试文件夹并以递归方式运行测试时,它不会中断中间件并失败。
文件结构:
test
functional
checklist
test.spec.js
lib
middleware
auth.js (this is what is being stubbed out)
test.spec.js
const chai = require('chai');
const chaiHttp = require('chai-http');
const sinon = require('sinon');
chai.use(chaiHttp);
const should = chai.should();
// Requirements
const auth = require('../../../lib/middleware/auth')
describe('/checklist/checklistItemLevel',function() {
let checkTokenStub;
beforeEach(function(){
checkTokenStub = sinon.stub(auth,'checkToken').callsFake((req,res,next)=>{
console.log('Stubbed')
next()
});
})
afterEach(function(){
auth.checkToken.restore();
})
context('/ POST',function() {
it('should return hello',function(done){
chai.request(require('../../../server'))
.post('/api/v1/checklist/checklistItemLevel')
.end((err,res)=>{
res.should.have.status(200);
res.text.should.be.eql('Hello');
done(err);
})
})
})
})
router.js
const router = require('express').Router();
const controller = require('./controller')
const auth = require('../../../lib/middleware/auth')
router.post('/',auth.checkToken,(req,res,next)=>{
res.send('Hello');
});
module.exports = router;
摩卡打电话
mocha "**/*.spec.js" // <- Doesnt stub out middleware
mocha "test/functional/checklist/*.spec.js" // <- Stubs out successfully
找到了答案。摩卡工作正常。但该应用程序正在被另一个测试用例缓存,因此它在没有存根的情况下运行