What's the best way to assert that the expected results matches the actual results when both are arrays of objects? My immediate thought was to use Array prototype filter and check that the intersection is the same size as expected, i.e.:
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);
});
});
Does this approach make sense? Is there a better way to assert the query results match expectations?
members becomes more obvious when comparing arrays of objects. Mentioned before, eql is an equality assertion in Chai. js which will perform a deep equal instead of a strict equal. An third way to compare two arrays of primitive values is to use the flagging property deep.
Mocha is a JavaScript test framework running on Node. js and in the browser. Mocha allows asynchronous testing, test coverage reports, and use of any assertion library. Chai is a BDD / TDD assertion library for NodeJS and the browser that can be delightfully paired with any javascript testing framework.
Chai is an assertion library that is mostly used alongside Mocha. It can be used both as a BDD / TDD assertion library for NodeJS and can be paired with any JavaScript testing framework. It has several interfaces that a developer can choose from and looks much like writing tests in English sentences.
As you noted, for sets, you can use:
expect(actual).to.have.members(expected);
This will fail if there are any members in expected
that are not in actual
, and vice versa.
You can also do:
expect(actual).to.contain.members(expected);
Which will fail if there are members in expected
that are not in actual
, but will not fail if there are members in actual
that are not in expected
. (In other words, actual
must be a superset of expected
).
If you're comparing objects, you probably want to deep compare:
expect(actual).to.deep.have.same.members(expected);
e.g.:
expect([{a:'a'}, {a:'b'}]).to.deep.have.same.members([{a:'a'}, {a:'b'}]);
(edited: to.have.same.members()
is actually the same as to.have.members()
.)
Chai has a members matcher that does what I need:
expect(actual).to.have.members(expected);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With