功能上的sinon间谍无法正常工作 [英] sinon spy on function not working

查看:88
本文介绍了功能上的sinon间谍无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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
}

这不起作用

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

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

Why isn't spying on just the function working?

推荐答案

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

Sinon cannot change content of existing function, so all spies it creates are just wrappers over existing function that count calls, memoize args etc.

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

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!

您的第二个示例等于:

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

So, they key to 'spying' and 'stubbing' in sinon is that you have to use spied/stubbed function in test. Your original code just used original, non-spied function.

这篇关于功能上的sinon间谍无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆