diff --git a/CHANGELOG.md b/CHANGELOG.md index fa8314e1b95e..bc4c3c1f8bde 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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)) diff --git a/packages/expect/src/__tests__/asymmetricMatchers.test.ts b/packages/expect/src/__tests__/asymmetricMatchers.test.ts index acdcab7b2189..dac1a7c1b804 100644 --- a/packages/expect/src/__tests__/asymmetricMatchers.test.ts +++ b/packages/expect/src/__tests__/asymmetricMatchers.test.ts @@ -211,6 +211,14 @@ test('ObjectContaining throws for non-objects', () => { jestExpect(() => objectContaining(1337).asymmetricMatch()).toThrow(); }); +test('ObjectContaining does not mutate the sample', () => { + 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'), diff --git a/packages/expect/src/asymmetricMatchers.ts b/packages/expect/src/asymmetricMatchers.ts index dd0026bc72de..280ebc9d5fe2 100644 --- a/packages/expect/src/asymmetricMatchers.ts +++ b/packages/expect/src/asymmetricMatchers.ts @@ -178,18 +178,15 @@ class ObjectContaining extends AsymmetricMatcher> { 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, - ); - } + ? objectContaining(this.sample[property] as Record) + : this.sample[property]; if ( !hasProperty(other, property) || - !equals(this.sample[property], other[property]) + !equals(expected, other[property]) ) { return false; }