Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Input objects identical but not reference equal" when comparing values with strictEqual in a NodeJS test?

I have a Node.js test where I'm asserting that two values of type Date should be equal, but the test is unexpectedly failing with AssertionError [ERR_ASSERTION]: Input objects identical but not reference equal.

The (simplified) test code is:

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

How should I change this test code such that the test passes?

like image 566
Jon Schneider Avatar asked May 06 '20 15:05

Jon Schneider


1 Answers

The test is failing because assert.strictEqual, per the docs, uses the SameValue comparison, which, for Dates (as well as for most other types), fails if the two values being compared aren't the exact same object reference.

Alternative 1: Use assert.deepStrictEqual instead of strictEqual:

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

Alternative 2: Use .getTime() before comparing:

assert.strictEqual(myActualDate.getTime(), myExpectedDate.getTime()); // Passes if the two values represent the same date
like image 121
Jon Schneider Avatar answered Nov 10 '22 22:11

Jon Schneider