首页 > 解决方案 > 在NodeJS测试中将值与strictEqual进行比较时,“输入对象相同但引用不相等”?

问题描述

我有一个 Node.js 测试,我在其中断言 Date 类型的两个值应该相等,但是测试意外地以AssertionError [ERR_ASSERTION]: Input objects identical but not reference equal.

(简化的)测试代码是:

it('should set the date correctly', () => {
  // (Code that gets "myActualDate" from the page under test goes here)

  const myExpectedDate = new Date('2020-05-06');

  assert.strictEqual(myActualDate, myExpectedDate);
});

我应该如何更改此测试代码以使测试通过?

标签: javascriptnode.jsunit-testing

解决方案


测试失败是因为assert.strictEqual,根据文档,使用SameValue 比较,对于 Dates (以及大多数其他类型),如果要比较的两个值不是完全相同的对象引用,则该比较失败。

备选方案 1:使用assert.deepStrictEqual而不是 strictEqual:

assert.deepStrictEqual(myActualDate, myExpectedDate); // Passes if the two values represent the same date

备选方案 2:在比较之前使用 .getTime()

assert.strictEqual(myActualDate.getTime(), myExpectedDate.getTime()); // Passes if the two values represent the same date

推荐阅读