代码之家  ›  专栏  ›  技术社区  ›  Catfish

希农试图监视快车目标

  •  0
  • Catfish  · 技术社区  · 7 年前

    我正在尝试测试这个简单的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不是函数?在我看来,这显然是一种功能。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Zbigniew Zagórski    7 年前

    sinon.spy 返回新创建的间谍,而不是 res 已经申请了新间谍。

    所以在你的情况下: resSpy === res.status 也不像你想象的那样 resSpy === res ,那就没道理了。

    换言之,你还是应该通过原件 物件 对于您的中间件:

    const result = middleware.onlyInternal(req, res);
    
    推荐文章