使用 sinon 匹配数组内的对象

Matching objects inside an array with sinon

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

let f = function(arr) {}

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

我想在我的测试中使用 sinon matchers.

f 的调用内容执行断言

我在 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")));

测试失败。

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

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

'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();
    });

});

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

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

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