如何将对象数组与 sinon.js 匹配?

Ane*_*apu 8 javascript node.js sinon

如何在 sinon 匹配器中匹配一组结果?

例如,这段代码如何工作?

var mystub = sinon.stub();
var myarg = { val: 1, mylist: [ {a:1}, {b:2}, {c:3,d:4} ] };

mystub(myarg);

sinon.assert.calledOnce(mystub).withArgs(
  sinon.match({val: 1, mylist: [{a:1},{b:2},{c:3,d:4}]}) // this doesn't work
);
Run Code Online (Sandbox Code Playgroud)

我怎样才能让它发挥作用?(请注意,在我的测试中,我无权访问 myarg - 所以我需要匹配它)。

显然,我可以编写自定义函数匹配器,但我正在寻找更易于阅读和编写的东西。

小智 7

这是一个旧帖子,但我找不到这个问题的正确答案。

Sinon 支持嵌套匹配器。所以要测试deep object的匹配,可以做如下操作:

const mystub = sinon.stub();
const myarg = {
  val: 1,
  mylist: [{ a: 1, x: 'foo' }, { b: 2, y: 'bar' }, { c: 3, d: 4, e: 5 } ],
};

mystub(myarg);

sinon.assert.calledOnce(mystub);
sinon.assert.calledWithMatch(mystub, {
  val: 1,
  mylist: [
    sinon.match({ a: 1 }),
    sinon.match({ b: 2 }),
    sinon.match({ c: 3, d: 4 }),
  ],
});
Run Code Online (Sandbox Code Playgroud)


Jon*_*n z 3

接受的答案中的自定义匹配函数对于了解很有用,但对于这个简单的用例来说完全是多余的。为了以Eryk Warren 的有用答案为基础,可以这样:

// match each element of the actual array against the corresponding entry in the expected array
sinon.assert.match(actual, expected.map(sinon.match));
Run Code Online (Sandbox Code Playgroud)