如何使用sinon.js匹配一个对象数组?

时间:2016-12-19 21:42:21

标签: javascript node.js sinon

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

例如,此代码如何工作?

flex-direction: column

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

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

4 个答案:

答案 0 :(得分:2)

自定义匹配器。

我建议您编写自己的自定义sinon matcher

你可以用一般的方式编写它,并在使用时轻松阅读。

以下是一个示例方法:

// usage
...withArgs(sinon.match(deepMatch({
    val: 1,
    mylist: [{a:1}, {b:2}, {c:3,d:4}]
})));


// custom matcher
const deepMatch = (expectation) => (actual) => {
    return Object.keys(expectation).every(key => {
        if (checkIfItsObject(expectation[key])) {
            // value is also an object, go deeper and then compare etc.
        } else {
            // compare and return boolean value accordingly
        }
    });
};

// note: checkIfItsObject is pseudocode - there are many ways to
// check if an object is an object so I did not want to complicate
// this code example here

答案 1 :(得分:1)

这是旧文章,但是我找不到这个问题的正确答案。

Sinon支持嵌套匹配器。因此,要测试深度对象的匹配情况,可以执行以下操作:

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 }),
  ],
});

答案 2 :(得分:0)

已接受答案中的自定义匹配功能对于了解此简单用例非常有用,但总的来说过大了。要建立在the useful answer from 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));

答案 3 :(得分:0)

Sinon在数组的内容上具有匹配项,例如sinon.match.array.deepEquals

这有效:

var mystub = sinon.stub();

var myarg = { val: 1, mylist: [ {a:1}, {b:2}, {c:3,d:4} ] };

mystub(myarg);

sinon.assert.calledWith(mystub,
  sinon.match({
    val: 1,
    mylist: sinon.match.array.deepEquals([ {a:1}, {b:2}, {c:3,d:4} ])
  })
);