Skip to content

Commit

Permalink
fix: preserve constructor in toMatchObject diff
Browse files Browse the repository at this point in the history
  • Loading branch information
hi-ogawa committed Oct 3, 2024
1 parent be6abe8 commit d939c1a
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 12 deletions.
8 changes: 8 additions & 0 deletions packages/expect/src/jest-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -709,6 +709,14 @@ export function getObjectSubset(
const trimmed: any = {}
seenReferences.set(object, trimmed)

// preserve constructor for toMatchObject diff
if (typeof object.constructor === 'function' && typeof object.constructor.name === 'string') {
Object.defineProperty(trimmed, 'constructor', {
enumerable: false,
value: object.constructor,
})
}

for (const key of getObjectKeys(object)) {
if (hasPropertyInObject(subset, key)) {
trimmed[key] = seenReferences.has(object[key])
Expand Down
44 changes: 32 additions & 12 deletions test/core/test/jest-expect.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1062,11 +1062,11 @@ it('toMatchObject error diff', () => {

// https://github.com/vitest-dev/vitest/issues/6543
class Foo {
constructor(public value: number) {}
constructor(public value: any) {}
}

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

expect(new Foo(0)).toMatchObject(new Bar(0))
Expand All @@ -1081,7 +1081,7 @@ it('toMatchObject error diff', () => {
- Bar {
- "value": 1,
+ Object {
+ Foo {
+ "value": 0,
}",
]
Expand All @@ -1093,8 +1093,9 @@ it('toMatchObject error diff', () => {
"- Expected
+ Received
Object {
- Object {
- "value": 1,
+ Foo {
+ "value": 0,
}",
]
Expand All @@ -1116,30 +1117,49 @@ it('toMatchObject error diff', () => {

expect(getError(() =>
expect({
bad: new Bar(1),
good: new Bar(0),
}).toMatchObject({
bad: new Foo(2),
bad: new Foo(1),
good: new Foo(0),
}).toMatchObject({
bad: new Bar(2),
good: new Bar(0),
}),
)).toMatchInlineSnapshot(`
[
"expected { bad: Bar{ value: 1 }, …(1) } to match object { bad: Foo{ value: 2 }, …(1) }",
"expected { bad: Foo{ value: 1 }, …(1) } to match object { bad: Bar{ value: 2 }, …(1) }",
"- Expected
+ Received
Object {
- "bad": Foo {
- "bad": Bar {
- "value": 2,
+ "bad": Object {
+ "bad": Foo {
+ "value": 1,
},
"good": Foo {
"good": Bar {
"value": 0,
},
}",
]
`)

expect(getError(() =>
expect(new Foo(new Foo(1))).toMatchObject(new Bar(new Bar(0))),
)).toMatchInlineSnapshot(`
[
"expected Foo{ value: Foo{ value: 1 } } to match object Bar{ value: Bar{ value: +0 } }",
"- Expected
+ Received
- Bar {
- "value": Bar {
- "value": 0,
+ Foo {
+ "value": Foo {
+ "value": 1,
},
}",
]
`)
})

it('toHaveProperty error diff', () => {
Expand Down

0 comments on commit d939c1a

Please sign in to comment.