我正在尝试测试这个简单的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
TypeError: res.status is not a function
为什么res.status不是函数?在我看来,这显然是一种功能。
sinon.spy 返回新创建的间谍,而不是 res 已经申请了新间谍。
sinon.spy
res
所以在你的情况下: resSpy === res.status 也不像你想象的那样 resSpy === res ,那就没道理了。
resSpy === res.status
resSpy === res
换言之,你还是应该通过原件 物件 对于您的中间件:
物件
const result = middleware.onlyInternal(req, res);