我正在尝试测试这个简单的 express 中间件功能
function onlyInternal (req, res, next) {
if (!ReqHelpers.isInternal(req)) {
return res.status(HttpStatus.FORBIDDEN).send() <-- TRYING TO ASSERT THIS LINE
}
next()
}
这是我目前的测试
describe.only('failure', () => {
let resSpy
before(() => {
let res = {
status: () => {
return {
send: () => {}
}
}
}
resSpy = sinon.spy(res, 'status')
})
after(() => {
sinon.restore()
})
it('should call next', () => {
const result = middleware.onlyInternal(req, resSpy)
expect(resSpy.called).to.be.true
})
})
我收到这个错误:TypeError: res.status is not a function
为什么 res.status 不是函数?对我来说它显然像是一个函数..
最佳答案
sinon.spy
返回新创建的 spy ,而不是 res
应用了新的 spy 。
所以在你的情况下:resSpy === res.status
而不是你所期望的resSpy === res
,那是没有意义的。
换句话说,你仍然应该传递原始的 res
给你的中间件:
const result = middleware.onlyInternal(req, res);
关于javascript - sinon 试图监视 express res 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51448072/