使用Jasmine Specs比较对象

时间:2014-04-07 19:13:41

标签: javascript testing jasmine specs

嘿所以今天我和Jasmine一起玩,我写了这个简单的Person对象

function Person() {}
Person.prototype.name = "Alex";
Person.prototype.age = 24;

这是我的规范测试

describe("Person", function() { 
var someone = new Person();
it('should be equal to other people', function() {
var another = {
name: "Joe",
age: 25,
};
expect(someone).toEqual(another);
});
});

然而,它失败了,期望{}等于{name:' Alex',年龄:24} 茉莉花不应该为对象做相同的匹配吗?我在这里错过了什么吗?

谢谢!

1 个答案:

答案 0 :(得分:3)

如果您浏览源代码,您会看到Jasmine的toEqual匹配器在比较对象时最终使用hasOwnProperty。您可以在matchersUtil.js中的代码片段中看到这一点。

function has(obj, key) {
  return obj.hasOwnProperty(key);
}

函数用于同一文件eq function中的in this way

  // Deep compare objects.
  for (var key in a) {
    if (has(a, key)) {
      // Count the expected number of properties.
      size++;
      // Deep compare each member.
      if (!(result = has(b, key) && eq(a[key], b[key], aStack, bStack, customTesters))) { break; }
    }
  }

... annnnd 调用eq时,toEqual.js匹配器会使用util.equals函数。

所以,因为toEqual匹配器使用hasOwnProperty,当它进行比较时,它不会"看到"属性链上的属性,但只有当前对象的属性。

一个注释:使用您的代码,测试结果略有不同但显着不同:

Expected { } to equal {name: 'Joe', age: 25 }

当忽略原型属性时,使用Jasmine的hasOwnProperty someone使用{{1}}时显示为空。