Reputation: 131
is there a way how to partially match object with array property? Let's suppose that I'd like to test this object
{ "groups": [ { "id": 1, "name": "Group 1", "people": [ { "firstName": "John", "age": 23 }, { "firstName": "Ethan", "age": 18 } ] }, { "id": 2, "name": "Group 2", "people": [ { "firstName": "Peter", "age": 47 }, { "firstName": "Henry", "age": 55 } ] } ] }
and ensure that it contains group with name Group 1
that contains John
and Ethan
.
I'm aware of jasmine.objectContaining but I don't know how to apply to this particular case.
Thank for any advice.
Upvotes: 6
Views: 5347
Reputation: 1975
You can achieve the desired result by using jasmine.arrayContaining
and jasmine.objectContaining
like below.
Please note: 'foo' is variable in which your test data resides as you wrote above.
describe("Array comparison", function () {
it("matches objects with the expect key/value pairs", function() {
expect(foo).toEqual(jasmine.objectContaining({
groups: jasmine.arrayContaining([
jasmine.objectContaining({name: "Group 2"}),
jasmine.objectContaining({
people: jasmine.arrayContaining([
jasmine.objectContaining({firstName: "Peter"}),
jasmine.objectContaining({firstName: "Henry"})
])
})
])
}));
Here is a jsFiddle for above working code.
Upvotes: 10
Reputation: 2999
you mean something like this ? assume obj is ur object
var res = obj["groups"].find(function(a) { return a["name"] == "group 1"; });
res = res["people"].filter(function(person) {
return ["Ethan","John"].includes(person["name"]);
});
now you can check if ( res["people"].length == 2 )
Upvotes: 0