为什么这个QUnit测试失败了?

时间:2014-12-01 05:29:56

标签: javascript unit-testing qunit

我试图了解单元测试,我发现了Ben Alman的overview。在幻灯片23上,他展示了包含对象actual的名为{a: 1}的变量如何不等于对象本身。那是什么意思?他们的价值相同吗?对象如何不同?

test("deepEqual", 7, function() {
  var actual = {a: 1};

  equal(    actual, {a: 1},   "fails because objects are different");
  deepEqual(actual, {a: 1},   "passes because objects are equivalent");
  deepEqual(actual, {a: "1"}, "fails because '1' !== 1");

  var a = $("body > *");
  var b = $("body").children();

  equal(    a,       b,       "fails because jQuery objects are different");
  deepEqual(a,       b,       "fails because jQuery objects are not equivalent");
  equal(    a.get(), b.get(), "fails because element arrays are different");
  deepEqual(a.get(), b.get(), "passes because element arrays are equivalent");
});

1 个答案:

答案 0 :(得分:0)

JS中的对象即使它们的值看起来也是不一样的。主要归结为不同的实例。详细了解Sameness in JavaScript。关于StackOverflow的真实细节,还有much better个答案。

您可以看到deepEqual如何确定一个对象"同一性" here。另一个好看的是lodash's implementation