14

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?

1 Answer 1

25

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
Sign up to request clarification or add additional context in comments.

4 Comments

Which testing suite have you used? Mocha,Testcafe?
@RichardRublev, the example code I provided in the question above uses the Mocha framework (mochajs.org).
@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.
assert.deepStrictEqual does NOT fix this problem when comparing values inside two objects though. It's so silly that there is no function to test for same content that can allow the references to differ.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.