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

sinon间谍功能不起作用

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

    我试图为这个简单的中间件函数编写一个独立的测试

    function onlyInternal (req, res, next) {
      if (!ReqHelpers.isInternal(req)) {
        return res.status(HttpStatus.FORBIDDEN).send()
      }
      next()
    }
    
    // Expose the middleware functions
    module.exports = {
      onlyInternal
    }
    

    这不起作用

    describe('success', () => {
    
      let req = {
        get: () => {return 'x-ciitizen-token'}
      }
      let res = {
        status: () => {
          return {
            send: () => {}
          }
        }
      }
      function next() {}
      let spy
    
      before(() => {
        spy = sinon.spy(next)
      })
    
      after(() => {
        sinon.restore()
      })
    
      it('should call next', () => {
        const result = middleware.onlyInternal(req, res, next)
        expect(spy.called).to.be.true <-- SPY.CALLED IS ALWAYS FALSE EVEN IF I LOG IN THE NEXT FUNCTION SO I KNOW IT'S GETTING CALLED
      })
    })
    

    但这是…

    describe('success', () => {
    
      let req = {
        get: () => {return 'x-ciitizen-token'}
      }
      let res = {
        status: () => {
          return {
            send: () => {}
          }
        }
      }
      let next = {
        next: () => {}
      }
      let spy
    
      before(() => {
        spy = sinon.spy(next, 'next')
      })
    
      after(() => {
        sinon.restore()
      })
    
      it('should call next', () => {
        const result = middleware.onlyInternal(req, res, next.next)
        expect(spy.called).to.be.true
      })
    })
    

    为什么监视功能不起作用?

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

    Sunon不能改变现有函数的内容,所以它创建的所有间谍都只是对现有函数的计数,对调用、回忆录ARG等进行计数。

    所以,你的第一个例子等于:

    function next() {}
    let spy = sinon.spy(next);
    next(); // assuming that middleware is just calling next
    // spy is not used!
    

    第二个例子等于:

    let next = { next: () => {} }
    next.next = sinon.spy(next.next); // sinon.spy(obj, 'name') just replaces obj.name with spy on it
    next.next(); // you actually call spy which in in turn calls original next.next
    //spy is called. YaY
    

    所以,在sinon中,它们的关键在于必须在测试中使用spied/stubbed函数你的原始代码只是使用了原始的,非间谍功能。