【问题标题】:Sinon Spy is never called诗乃间谍从未被召唤
【发布时间】:2017-04-18 00:50:51
【问题描述】:

我正在测试一个方法 A,它根据条件使用不同的参数调用另一个方法 B。所以我想监视 B 以便我可以检查它是否被调用。但是间谍永远不会被召唤。

import parent from '../something.js'
describe('Testing A', () => {
  it('should make proper calls to B', () => {
      var spy = sinon.spy(parent, 'B')
      parent.A()
      expect(spy.calledOnce).to.be.true
  })
})

而测试函数 A 就是

export const A = () => {
    B()
}

似乎在测试中,B 的间谍版本永远不会被调用,因为 A 直接调用 B。如何让A的测试函数调用B的Sinon版本?

【问题讨论】:

  • B从哪里来,是模块内部的,来自另一个模块?
  • A 和 B 都来自parent

标签: javascript reactjs sinon spy


【解决方案1】:

对我来说,您的代码不可测试。您应该将被测模块视为黑匣子,而不是尝试对其内部进行调整。在您的情况下,您正试图监视 something.js 模块内部的方法。

将 B 作为参数传递给 A:

export const A = (B) => {
    B();
}

在这种情况下,它是很容易测试的回调:

import parent from '../something.js'
describe('Testing A', () => {
  it('should make proper calls to B', () => {
      var B = sinon.spy();
      parent.A(B);
      expect(B.calledOnce).to.be.true;
  })
})

【讨论】:

  • 这似乎是最好的主意。谢谢。
猜你喜欢
  • 2013-11-21
  • 1970-01-01
  • 1970-01-01
  • 2015-08-29
  • 2022-07-01
  • 2016-08-04
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
相关资源
最近更新 更多