12

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?

Jon Schneider
  • 25,758
  • 23
  • 142
  • 170

1 Answers1

19

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
Jon Schneider
  • 25,758
  • 23
  • 142
  • 170
  • Which testing suite have you used? Mocha,Testcafe? – Richard Rublev May 06 '20 at 15:46
  • @RichardRublev, the example code I provided in the question above uses the Mocha framework (https://mochajs.org/). – Jon Schneider May 07 '20 at 13:50
  • @JonSchneider so basically deepEqual algorithm only results in true values if the inner objects are referring to the same thing? this is what I got - AssertionError [ERR_ASSERTION]: Values have the same structure but are not reference-equal. I have two instances of a class, but since they have their own functions, have obviously the same structure, but both functions are two different things. – Ace Aug 28 '23 at 12:23