sinon 试图监视 express res 对象
sinon trying to spy express res object
我正在尝试测试这个简单的 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
returns 新创建的间谍,而不是应用了新间谍的 res
。
因此在您的情况下:resSpy === res.status
与您预期的不同 resSpy === res
,这没有意义。
换句话说,您仍然应该将原始 res
传递给您的中间件:
const result = middleware.onlyInternal(req, res);
我正在尝试测试这个简单的 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
returns 新创建的间谍,而不是应用了新间谍的 res
。
因此在您的情况下:resSpy === res.status
与您预期的不同 resSpy === res
,这没有意义。
换句话说,您仍然应该将原始 res
传递给您的中间件:
const result = middleware.onlyInternal(req, res);