在 NodeJS 测试中将值与 strictEqual 进行比较时“输入对象相同但引用不相等”?

Jon*_*der 4 javascript unit-testing node.js

我有一个 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);
});
Run Code Online (Sandbox Code Playgroud)

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

Jon*_*der 9

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

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

assert.deepStrictEqual(myActualDate, myExpectedDate); // Passes if the two values represent the same date
Run Code Online (Sandbox Code Playgroud)

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

assert.strictEqual(myActualDate.getTime(), myExpectedDate.getTime()); // Passes if the two values represent the same date
Run Code Online (Sandbox Code Playgroud)