此检查过去通过:
expect(array).toContain(value)
阵列:
[
{"_t":"user","id":1073970419,"email":"email3@example.org","name":"Spectator"},
{"_t":"user","id":4464992042,"email":"email4@example.org","name":"Collaborator"},
{"_t":"user","id":1978569710,"email":"email5@example.org","name":"Manage"}
]
值:
{"_t":"user","id":1978569710,"email":"email5@example.org","name":"Manage"}
但不再过去了。什么是编写相同测试的新方法?
答案 0 :(得分:12)
它不会包含那个对象(请记住,为了相等,两个具有相同属性的对象不是同一个对象),因此toContain
永远不会通过。
您需要使用其他测试,例如toEqual
或(如果您只想检查属性的子集),toEqual
结合jasmine.objectContaining
。
以下是该页面上Jasmine文档中的toEqual
示例:
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);
});
});
现在注意foo
等于bar
。
以下是使用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
}));
});
// ...
});
请注意具有多个属性的对象如何与提供给jasmine.objectContaining
的部分对象匹配。
答案 1 :(得分:10)
您需要的语法是:
const obj = {"_t":"user","id":1978569710,"email":"email5@example.org","name":"Manage"};
expect(array).toContain(jasmine.objectContaining(obj));
答案 2 :(得分:1)
@ T.J.Crowder已经准确地解释了这个问题。只是为了帮助你更多,如果你想调整你的例子,你需要这样的东西:
var userA = {"_t":"user","id":1978569710,"email":"email5@example.org","name":"Manage"}
array =
[
{"_t":"user","id":1073970419,"email":"email3@example.org","name":"Spectator"},
{"_t":"user","id":4464992042,"email":"email4@example.org","name":"Collaborator"},
userA
]
expect(array).toContain(userA);