"Received: serializes to the same string" on object equality checking
See original GitHub issue🐛 Bug Report
Using .toMatchObject()
returns failing test with message Received: serializes to the same string
To Reproduce
I am trying to check the users
object I receive against my expectedUsers
. The received object coming back from MongoDB contains the fields "__v"
and "_id"
which I do not want to check for (they always change for every test). As such, I am using .toMatchObject()
and cannot use something else like .toEqual()
. My test snippet is below:
test("should show all existing users", async () => {
const expectedUsers = [
{
email: "andy@example.com",
friends: [],
followers: [],
following: [],
blocked: []
},
{
email: "john@example.com",
friends: ["andy@example.com", "mary@example.com"],
followers: [],
following: [],
blocked: []
},
{
email: "mary@example.com",
friends: [],
followers: [],
following: [],
blocked: ["john@example.com"]
}
];
await request(app)
.get(route(path))
.expect("Content-Type", /json/)
.expect(200);
const users = await User.find();
expect(users).toMatchObject(expectedUsers);
});
(request
is made with supertest
)
Expected behavior
As documented here,
Use .toMatchObject to check that a JavaScript object matches a subset of the properties of an object. It will match received objects with properties that are not in the expected object.
Since the expected
objects is a subset of received
objects, I expect my test to pass.
npx envinfo --preset jest
result
System:
OS: macOS 10.14.4
CPU: (12) x64 Intel(R) Core(TM) i9-8950HK CPU @ 2.90GHz
Binaries:
Node: 10.15.2 - ~/.asdf/shims/node
npm: 6.9.0 - ~/.asdf/shims/npm
npmPackages:
jest: ^24.8.0 => 24.8.0
Issue Analytics
- State:
- Created 4 years ago
- Reactions:90
- Comments:40 (8 by maintainers)
I’m also experiencing this issue. This is my workaround:
@sabriele From reading Jest code and guessing about MongoDB,
users
array might have non-index properties whichtoMatchObject
should (but does not) ignore.Here is a work-around to get rid of them:
If you can paste the received
users
before work-around, we can make a realistic regression test.