Skip to content

Expect toMatchObject diff to match object type #6580

@msteen

Description

@msteen

Describe the bug

When I use expect(testObject).toMatchObject(expectedObject) I expect the diff to report the correct type for Received as it does for Expected.

For example, say I have the two classes Foo and Bar:

class Foo {
  constructor(public value: number) {}
}
class Bar {
  constructor(public value: number) {}
}

Then I expect the following test:

test("foo", () => {
  expect(new Bar(2)).toMatchObject(new Foo(1))
})

To report the types as it does in the AssertionError

 FAIL  src/test.ts > foo
AssertionError: expected Bar{ value: 2 } to match object Foo{ value: 1 }

- Expected
+ Received

- Foo {
-   "value": 1,
+ Object {
+   "value": 2,
  }

 ❯ src/test.ts:44:22
     42| }
     43| test("foo", () => {
     44|   expect(new Bar(2)).toMatchObject(new Foo(1))
       |                      ^
     45| })
     46| 

Yet it shows expecting a Foo and receiving an Object, while I would expect Object to be Bar here.

Now there have been cases (when this problem occurs in a nested object) where I had to add additional logging on failure to determine that Object is in fact Bar to pinpoint the cause of the error, which would have been unnecessary if the diff reported the correct type.

Reproduction

https://stackblitz.com/edit/vitest-dev-vitest-qmrkzs?file=test%2Fbasic.test.ts

System Info

vitest/1.6.0 linux-x64 node-v22.7.0

  System:
    OS: Linux 6.8 Ubuntu 22.04.4 LTS 22.04.4 LTS (Jammy Jellyfish)
    CPU: (8) x64 Intel(R) Core(TM) i7-8565U CPU @ 1.80GHz
    Memory: 2.94 GB / 31.06 GB
    Container: Yes
    Shell: 5.1.16 - /bin/bash
  Binaries:
    Node: 22.7.0 - ~/.nvm/versions/node/v22.7.0/bin/node
    npm: 10.8.2 - ~/.nvm/versions/node/v22.7.0/bin/npm
    pnpm: 9.9.0 - ~/.nvm/versions/node/v22.7.0/bin/pnpm
    bun: 1.1.26 - ~/.nvm/versions/node/v22.7.0/bin/bun

Used Package Manager

pnpm

Validations

Metadata

Metadata

Assignees

No one assigned

    Labels

    p3-minor-bugAn edge case that only affects very specific usage (priority)

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions