javascript - 身份验证中间件不调用存根 - NodeJS,sinon
问题描述
之前也有人问过类似的问题,我看过并关注了它们,但没有运气:
我从这些得到的一般答案是,在 auth 中间件方法被存根之后app.js
,应该需要模块(在我的情况下) 。我已经这样做了,但仍然调用原始中间件:
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中加载),所以我不确定为什么仍然调用原始方法。
我还尝试在模拟之前手动清除缓存,但仍然无法正常工作。
解决方案
我认为解决方案将使用Rewire代替(或与)Supertest。Rewire 允许您模拟模块的顶级组件。尽管您需要在传递给 Supertest 之前模拟中间件。
推荐阅读
- powershell - 作为脚本的一部分执行时,Start-Job 不起作用
- javascript - 如何查看多边形开放层
- docker - Docker rabbitmq 映像失败并显示 [error] Too short cookie string
- python - 如何制作一个 5 分钟的循环计时器,在与其他应用程序一起打开时始终“保持在最前面”?
- c++ - Apache Thrift 超时
- python - C++ last_write_time 与 Python 的比较
- javascript - 使用多个数组解析 JSON 并在 HTML 中显示结果
- javascript - 使用 initComplete 在 Shiny 应用程序中使用 Javascript 定位特定的 DT::datatable 表
- python - Python 程序有时会以“IndexError: string index out of range”退出,有时运行良好
- javascript - 续集多对多深层嵌套关联