【问题标题】:Comparing objects using Jasmine Specs使用 Jasmine Specs 比较对象
【发布时间】:2014-05-20 04:55:12
【问题描述】:

嘿,今天我在玩 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', age : 24 } Jasmine 的 toEqual 匹配器不应该适用于对象吗?我在这里遗漏了什么吗?

谢谢!

【问题讨论】:

    标签: javascript testing jasmine specs


    【解决方案1】:

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

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

    ...annnndeq 函数在调用util.equals 时被toEqual.js 匹配器使用。

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

    注意事项:使用您的代码,我得到的测试结果略有不同:

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

    这与 Jasmine 对 hasOwnProperty 的用法一致,使得 someone 在原型属性被忽略时显示为空。

    【讨论】:

      猜你喜欢
      • 2013-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-11
      相关资源
      最近更新 更多