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

fix: don't mutate the sample in expect.objectContaining() #10711

Merged
merged 3 commits into from Oct 26, 2020
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 @@ -6,6 +6,8 @@

### Fixes

- `[expect]` Stop modifying the sample in `expect.objectContaining()` ([#10711](https://github.com/facebook/jest/pull/10711))

### Chore & Maintenance

- `[jest-cli]` chore: standardize files and folder names ([#10698](https://github.com/facebook/jest/pull/1098))
Expand Down
8 changes: 8 additions & 0 deletions packages/expect/src/__tests__/asymmetricMatchers.test.ts
Expand Up @@ -211,6 +211,14 @@ test('ObjectContaining throws for non-objects', () => {
jestExpect(() => objectContaining(1337).asymmetricMatch()).toThrow();
});

test('ObjectContaining does not mutate the sample', () => {
jeysal marked this conversation as resolved.
Show resolved Hide resolved
const sample = {foo: {bar: {}}};
const sample_json = JSON.stringify(sample);
expect({foo: {bar: {}}}).toEqual(expect.objectContaining(sample));

expect(JSON.stringify(sample)).toEqual(sample_json);
});

test('ObjectNotContaining matches', () => {
[
objectNotContaining({}).asymmetricMatch('jest'),
Expand Down
11 changes: 4 additions & 7 deletions packages/expect/src/asymmetricMatchers.ts
Expand Up @@ -178,18 +178,15 @@ class ObjectContaining extends AsymmetricMatcher<Record<string, unknown>> {
return true;
} else {
for (const property in this.sample) {
if (
const expected =
typeof this.sample[property] === 'object' &&
!(this.sample[property] instanceof AsymmetricMatcher)
) {
this.sample[property] = objectContaining(
this.sample[property] as Record<string, unknown>,
);
}
? objectContaining(this.sample[property] as Record<string, unknown>)
: this.sample[property];

if (
!hasProperty(other, property) ||
!equals(this.sample[property], other[property])
!equals(expected, other[property])
) {
return false;
}
Expand Down