#8475·Jest

"Received: serializes to the same string" on object equality checking

Author: sabrieleCreated May 20, 2019Updated Sep 26, 2026
LabelsNeeds TriageBug ReportStale

Bug Report

Using .toMatchObject() returns failing test with message Received: serializes to the same string

image

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: "[email protected]",
      friends: [],
      followers: [],
      following: [],
      blocked: []
    },
    {
      email: "[email protected]",
      friends: ["[email protected]", "[email protected]"],
      followers: [],
      following: [],
      blocked: []
    },
    {
      email: "[email protected]",
      friends: [],
      followers: [],
      following: [],
      blocked: ["[email protected]"]
    }
  ];
  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

bash
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