Jasmine: how to check that array contains an object?
Solution 1
It won't contain that object (remember, two objects with the same properties are not the same object for the purposes of equality), so toContain
will never pass.
You need to use another test, like toEqual
or (if you only want to check for a subset of properties), toEqual
combined with jasmine.objectContaining
.
Here's the toEqual
example from the Jasmine documentation on that page:
describe("The 'toEqual' matcher", function() {
it("works for simple literals and variables", function() {
var a = 12;
expect(a).toEqual(12);
});
it("should work for objects", function() {
var foo = {
a: 12,
b: 34
};
var bar = {
a: 12,
b: 34
};
expect(foo).toEqual(bar);
});
});
Note now foo
equals bar
.
Here's their example using jasmine.objectContaining
:
describe("jasmine.objectContaining", function() {
var foo;
beforeEach(function() {
foo = {
a: 1,
b: 2,
bar: "baz"
};
});
it("matches objects with the expect key/value pairs", function() {
expect(foo).toEqual(jasmine.objectContaining({
bar: "baz"
}));
expect(foo).not.toEqual(jasmine.objectContaining({
c: 37
}));
});
// ...
});
Note how the object with several properties matches the partial object supplied to jasmine.objectContaining
.
Solution 2
The syntax you need is:
const obj = {"_t":"user","id":1978569710,"email":"[email protected]","name":"Manage"};
expect(array).toContain(jasmine.objectContaining(obj));
See fiddle: https://jsfiddle.net/bblackwo/4o5u5Lmo/16/
Solution 3
@T.J.Crowder already explained precisely the problem. Just to help you a tad more, if you want to adapt your example, you'd need something like this:
var userA = {"_t":"user","id":1978569710,"email":"[email protected]","name":"Manage"}
array =
[
{"_t":"user","id":1073970419,"email":"[email protected]","name":"Spectator"},
{"_t":"user","id":4464992042,"email":"[email protected]","name":"Collaborator"},
userA
]
expect(array).toContain(userA);
Comments
-
hakunin over 3 years
This check used to pass:
expect(array).toContain(value)
Array:
[ {"_t":"user","id":1073970419,"email":"[email protected]","name":"Spectator"}, {"_t":"user","id":4464992042,"email":"[email protected]","name":"Collaborator"}, {"_t":"user","id":1978569710,"email":"[email protected]","name":"Manage"} ]
Value:
{"_t":"user","id":1978569710,"email":"[email protected]","name":"Manage"}
But no longer passes. Whats the new way to write the same test?