sinon间谍功能不起作用

时间:2018-07-18 17:29:27

标签: javascript unit-testing mocha sinon chai

我正在尝试为此简单的中间件功能编写独立测试

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
  })
})

但是确实如此。

getAdapterPosition()

为什么不仅仅监视功能正常工作?

1 个答案:

答案 0 :(得分:1)

Sinon无法更改现有函数的内容,因此它创建的所有间谍程序都只是对现有函数的包装,这些函数可以对调用进行计数,记住args等。

因此,您的第一个示例与此相同:

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中“间谍”和“存根”的关键在于您必须在测试中使用间谍/存根功能。您的原始代码只是使用了原始的非间谍功能。