当两者都是对象数组时,断言预期结果与实际结果相匹配的最佳方法是什么?我的直接想法是使用Array原型过滤器并检查交叉点是否与预期的大小相同,即:
describe('select',function(){
it("should return selected columns", function(done) {
var query = "select lunchTime, name";
var actual = ... results of the query, an array of anonymous objects ...
// expected results
var expected = [{"lunchTime": "12:00:00", "name": "John"},
{"lunchTime": "12:00:00", "name": "Dave"},
{"lunchTime": "13:00:00", "name": "Sally"},
{"lunchTime": "12:00:00", "name": "Ben"},
{"lunchTime": "12:00:00", "name": "Dana"},
{"lunchTime": "13:00:00", "name": "Mike"}];
var intersection = actual.filter(function(n) {
return expected.indexOf(n) != -1
});
expect(intersection).to.have.length(expected.length);
expect(actual).to.have.length(expected.length);
});
});
这种方法有意义吗?有没有更好的方法断言查询结果符合预期?
答案 0 :(得分:11)
如您所述,对于集合,您可以使用:
expect(actual).to.have.members(expected);
如果您想确保actual
中没有expected
之内的成员,那么:
expect(actual).to.have.same.members(expected);
最后,如果您要比较对象,您可能需要深入比较:
expect(actual).to.deep.have.same.members(expected);
e.g:
expect([{a:'a'}, {a:'b'}]).to.deep.have.same.members([{a:'a'}, {a:'b'}]);
答案 1 :(得分:7)
Chai有members matcher可以满足我的需要:
expect(actual).to.have.members(expected);