Asserting ObjectId equality in test cases

Viewed 154

I have a test case that wants to assert that the mongoose document returned from the method under test is the same as one I already have. To check that they are equal, my intent is to simply verify that they have the same _id property.

const expected = MyModel.find(/*...*/);
const actual = await foo(); // method under test
expect(actual._id).to.deep.equal(expected._id)

However, I have found that the deep.equal check passes even when the _ids of the documents are not the same.

I reproduced the problem into this small example:

import { expect } from 'chai';
import { Types } from 'mongoose';

const a = new Types.ObjectId();
const b = new Types.ObjectId();

expect(a).to.deep.equal(b); // unexpectedly passes

I have verified that I can work around the problem by comparing the string representation of each ObjectId instead:

expect(a.toString()).equals(b.toString()); // fails (as expected)

Why does chai incorrectly assert that the two ObjectIds, which are different object instances with different values, are deeply equal in the original example?

0 Answers
Related