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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With