简体   繁体   English

sinon间谍功能不起作用

[英]sinon spy on function not working

I'm trying to write a standalone test for this simple middleware function 我正在尝试为此简单的中间件功能编写独立测试

function onlyInternal (req, res, next) {
  if (!ReqHelpers.isInternal(req)) {
    return res.status(HttpStatus.FORBIDDEN).send()
  }
  next()
}

// Expose the middleware functions
module.exports = {
  onlyInternal
}

This does not work 这行不通

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

but this does.. 但这是..

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

Why isn't spying on just the function working? 为什么不仅仅监视功能正常工作?

Sinon cannot change content of existing function, so all spies it creates are just wrappers over existing function that count calls, memoize args etc. Sinon不能更改现有函数的内容,因此它创建的所有间谍程序都只是对计数调用,记忆args等的现有函数的包装。

So, your first example is equal to this: 因此,您的第一个示例等于:

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

Your second example, equals to this: 您的第二个示例等于:

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

So, they key to 'spying' and 'stubbing' in sinon is that you have to use spied/stubbed function in test. 因此,它们在sinon中“间谍”和“存根”的关键在于您必须在测试中使用间谍/存根功能。 Your original code just used original, non-spied function. 您的原始代码仅使用了原始的非间谍功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM