繁体   English   中英

使用Jasmine Specs比较对象

[英]Comparing objects using Jasmine Specs

嘿,所以我今天在玩茉莉花,我写了这个简单的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',age:24} Jasmine的toEqual匹配器不适合对象吗? 我在这里想念什么吗?

谢谢!

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

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

函数通过以下方式在同一文件的eq函数中使用:

  // 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; }
    }
  }

... annnndeq功能使用toEqual.js匹配时util.equals被调用。

因此,因为toEqual匹配器使用hasOwnProperty ,所以当它进行比较时,它将不会“看到”原型链中的属性,而只会“看到”直接对象上的属性。

注意事项 :使用您的代码,测试结果略有不同,但有明显不同:

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

这与Jasmine的hasOwnProperty用法相hasOwnProperty ,当原型属性被忽略时,此someone会使someone显得为空。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM