Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Include symbol keys when diffing objects #13810

Merged
merged 2 commits into from Jan 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Expand Up @@ -4,6 +4,8 @@

### Fixes

- `[@jest/expect-utils]` `toMatchObject` diffs should include `Symbol` properties ([#13810](https://github.com/facebook/jest/pull/13810))

### Chore & Maintenance

### Performance
Expand Down
15 changes: 13 additions & 2 deletions packages/expect-utils/src/utils.ts
Expand Up @@ -43,6 +43,17 @@ const hasPropertyInObject = (object: object, key: string | symbol): boolean => {
);
};

// Retrieves an object's keys for evaluation by getObjectSubset. This evaluates
// the prototype chain for string keys but not for symbols. (Otherwise, it
// could find values such as a Set or Map's Symbol.toStringTag, with unexpected
// results.)
//
// Compare with subsetEquality's use of Reflect.ownKeys.
const getObjectKeys = (object: object) => [
...Object.keys(object),
...Object.getOwnPropertySymbols(object),
];

export const getPath = (
object: Record<string, any>,
propertyPath: string | Array<string>,
Expand Down Expand Up @@ -131,7 +142,7 @@ export const getObjectSubset = (
const trimmed: any = {};
seenReferences.set(object, trimmed);

Object.keys(object)
getObjectKeys(object)
.filter(key => hasPropertyInObject(subset, key))
.forEach(key => {
trimmed[key] = seenReferences.has(object[key])
Expand All @@ -144,7 +155,7 @@ export const getObjectSubset = (
);
});

if (Object.keys(trimmed).length > 0) {
if (getObjectKeys(trimmed).length > 0) {
return trimmed;
}
}
Expand Down
Expand Up @@ -4140,13 +4140,13 @@ exports[`toMatchObject() {pass: false} expect({"a": "a", "c": "d"}).toMatchObjec
exports[`toMatchObject() {pass: false} expect({"a": "b", "c": "d", Symbol(jest): "jest"}).toMatchObject({"a": "c", Symbol(jest): Any<String>}) 1`] = `
<d>expect(</><r>received</><d>).</>toMatchObject<d>(</><g>expected</><d>)</>

<g>- Expected - 2</>
<g>- Expected - 1</>
<r>+ Received + 1</>

<d> Object {</>
<g>- "a": "c",</>
<g>- Symbol(jest): Any<String>,</>
<r>+ "a": "b",</>
<d> Symbol(jest): Any<String>,</>
<d> }</>
`;

Expand Down