【问题标题】:Matching objects inside an array with sinon用 sinon 匹配数组内的对象
【发布时间】:2017-05-08 14:42:10
【问题描述】:

我正在用 sinon.js 测试一个方法调用,它需要一个对象数组,如下所示:

let f = function(arr) {}

f([{foo: "bar"}, {baz: "quux"}];

我想在我的测试中使用sinon matchersf 的调用内容执行断言。

我在f 上有一个间谍,叫fSpy,我已经可以了

sinon.assert.calledOnce(fSpy);
sinon.assert.calledWith(fSpy, sinon.match.array);

但是,如果我测试类似的东西

sinon.assert.calledWith(fSpy, sinon.match.array.contains(sinon.match.has("foo")));

测试失败。

我猜这是因为匹配器的参数不能是匹配器本身,那么测试这个的正确方法是什么?

【问题讨论】:

  • 是的,但是 sinon 匹配器只有在作为参数传递给 sinon 函数 AFAIK 时才有效,因此将其传递给 contains 不起作用

标签: javascript unit-testing sinon


【解决方案1】:

不要将头撞到 'matchers' 墙上 - 除非你提供自定义匹配器,否则这是相当有限的 - 我建议你遵循干净简单的路径,像这样。 p>

'use strict';

const chai = require('chai');
const sinon = require('sinon');
const SinonChai = require('sinon-chai');

var sinonStubPromise = require('sinon-stub-promise');
sinonStubPromise(sinon);

chai.use(SinonChai);
chai.should();


context('Test', () => {

  this.f = function(arr) {

  };


  beforeEach(() => {
    if (!this.sandbox) {
      this.sandbox = sinon.sandbox.create();
    } else {
      this.sandbox.restore();
    }
  });


  it('should pass the test',
    (done) => {

      const fSpy = this.sandbox.spy(this, 'f');

      this.f([{
        foo: 'bar'
      }, {
        baz: 'quux'
      }]);


      fSpy.should.have.been.calledOnce;
      fSpy.should.have.been.calledWith(sinon.match.array);

      const args = fSpy.getCall(0).args[0];
      args.should.have.deep.include.any.members([{foo: 'bar'}]);
      args.should.have.deep.property('[0].foo', 'bar');
      args.should.have.deep.property('[1].baz', 'quux');

      done();
    });

});

在第一次调用时访问传递给方法的参数,并直接在该输入上使用任何断言库。这很简单,您的选择不受限制。

【讨论】:

  • 这将是一个很好的解决方案,但我无法使用它,因为我实际上正在测试一个在内部调用 f 的函数,而不是直接调用 f
【解决方案2】:

您可以使用存根替换方法实现并在该方法中移动参数的断言。

sinon.stub(an_object, 'a_method', function(args) {
  expect(args)....
  done();
});

【讨论】:

    猜你喜欢
    • 2020-10-23
    • 2019-07-16
    • 2018-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-06
    • 1970-01-01
    相关资源
    最近更新 更多