2

嘿,所以我今天在玩 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);
});
});

然而它失败了 Expected { } to equal { name : 'Alex', age : 24 } Jasmine 的 toEqual 匹配器不应该适用于对象吗?我在这里错过了什么吗?

谢谢!

4

1 回答 1

3

如果您浏览源代码,您将看到 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使显示为空的用法一致。someone

于 2014-04-08T03:47:40.197 回答