【发布时间】:2019-10-06 18:59:57
【问题描述】:
之前有人问过类似的问题,我已经查看并关注了它们,但没有运气:
- Sinon stub being skipped as node express middleware
- node express es6 sinon stubbing middleware not working
- How to mock middleware in Express to skip authentication for unit test?
我从这些得到的一般答案是模块(在我的情况下为app.js)应该是必需的之后 auth 中间件方法已被存根。我已经这样做了,但仍然调用原来的中间件:
src/app.js
const authentication = require('./authentication')
...
app.use(['/api/users', '/api/groups'], authentication.ensureAuthenticed])
module.exports = app
src/authentication.js
const { isValidAuth } = require('./lib')
exports.ensureAuthenticated = (req, res, next) => {
...
}
__helpers__/supertest.js
// This file just calls endpoints with supertest but this is the only file
// that includes 'app'
const app = require('../../src/app')
module.exports = {
post: {
...
},
get: {
...
},
put: {
...
},
delete: {
...
}
}
users.spec.js
const authentication = require('../../src/authentication')
const authenticationStubs = require('../__stubs__/authentication')
let supertest
let ensureAuthStub
describe('Users', () => {
before(() => {
ensureAuthStub = sinon.stub(authentication, 'ensureAuthenticated').callsFake(authenticationStubs.ensureAuthenticated)
supertest = require('../__helpers__/supertest')
})
// tests
after(() => {
ensureAuthStub.restore()
})
})
__stubs__/authentication.js
exports.ensureAuthenticated = (req, res, next) => {
...
}
在 users.spec.js 中,我在 supertest.js 中加载(在 src/app.js 中加载)之后该方法已被模拟,因此我不确定为什么仍在调用原始方法。
我也尝试在模拟之前手动清除缓存,但仍然不起作用。
【问题讨论】:
标签: javascript node.js unit-testing sinon