【问题标题】:SinonJS: calledWith() with exact objectSinonJS:用精确对象调用With()
【发布时间】:2018-01-05 17:02:57
【问题描述】:

我正在尝试测试我的 Sinon 测试中的一个间谍是否正在使用一个确切的对象进行调用:没有丢失的属性,没有其他属性,也没有更改的属性。

我有这个:

assert( viewer.entities.add.calledWith( completeEntityObject ) );

但如果我省略了completeEntityObject 中的一些属性,则测试成功。我希望它失败。我想要一个深入的比较。

我已经尝试查看sinon.match 方法,但是,虽然有对数组进行深度相等的测试,但没有对对象进行这样的测试。我怎样才能做到这一点?

【问题讨论】:

  • 你可以尝试使用ng-test-runner来测试angular组件中的http通信。 Example from documentation。在该库中测试 http 通信使用 SinonJS,但它的 api 比普通的 SinonJS 更好。
  • 这不是我想要的,但还是谢谢你。

标签: angular unit-testing sinon


【解决方案1】:

对于任何寻找如何断言您的 sinon 间谍是使用某些参数调用的人,这里有一个简单的示例。

  const spy = sinon.spy();

  // If spy is ever called in your code with some arguments, like so:
  spy({ hello: 'world'});

  // You can assert for it in your tests like this:
  expect(spy.getCall(0).calledWith(sinon.match({ hello: 'world' }))).to.be.true;

  // Breaking this down a bit:
  // spy.getCall(0) gives us the first time our spy function was called (because it can be called more than once)

  // Bonus: While debugging, you can use spy.getCalls()[0].args[0] to get the arguments that your spy function was called with.

我希望这会有所帮助 - 这是我的第一个 SO 回复,如果我违反规则或没有详细解释事情,请原谅我。

【讨论】:

    【解决方案2】:

    我找到了解决方案。我用这个:

    sinon.assert.calledWith( addStub, sinon.match( cesiumPartialEntityObject ) );
    

    如果缺少属性或附加属性,此操作将失败。

    【讨论】:

    • 你能解释一下吗?或者传递一些链接?
    • @VladimirVukanac 我在下面发布了一个示例,以防万一。
    • 这个解决方案是不正确的,sinon.match(object),根据文档,Requires the value to be not null or undefined and have at least the same properties as expectation. 并不能保证“没有丢失的属性,没有额外的属性,没有改变的属性”。 ,正如你的问题所提到的。诗侬文档:sinonjs.org/releases/latest/matchers
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-02
    • 1970-01-01
    • 2021-01-27
    • 2023-02-25
    • 2012-09-22
    • 1970-01-01
    • 2016-04-20
    相关资源
    最近更新 更多