Skip to content

Commit f84a807

Browse files
authored
fix: don't mutate the sample in expect.objectContaining() (jestjs#10711)
1 parent 6dda424 commit f84a807

File tree

3 files changed

+14
-7
lines changed

3 files changed

+14
-7
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66

77
### Fixes
88

9+
- `[expect]` Stop modifying the sample in `expect.objectContaining()` ([#10711](https://github.com/facebook/jest/pull/10711))
10+
911
### Chore & Maintenance
1012

1113
- `[jest-cli]` chore: standardize files and folder names ([#10698](https://github.com/facebook/jest/pull/1098))

packages/expect/src/__tests__/asymmetricMatchers.test.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,14 @@ test('ObjectContaining throws for non-objects', () => {
211211
jestExpect(() => objectContaining(1337).asymmetricMatch()).toThrow();
212212
});
213213

214+
test('ObjectContaining does not mutate the sample', () => {
215+
const sample = {foo: {bar: {}}};
216+
const sample_json = JSON.stringify(sample);
217+
expect({foo: {bar: {}}}).toEqual(expect.objectContaining(sample));
218+
219+
expect(JSON.stringify(sample)).toEqual(sample_json);
220+
});
221+
214222
test('ObjectNotContaining matches', () => {
215223
[
216224
objectNotContaining({}).asymmetricMatch('jest'),

packages/expect/src/asymmetricMatchers.ts

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -178,18 +178,15 @@ class ObjectContaining extends AsymmetricMatcher<Record<string, unknown>> {
178178
return true;
179179
} else {
180180
for (const property in this.sample) {
181-
if (
181+
const expected =
182182
typeof this.sample[property] === 'object' &&
183183
!(this.sample[property] instanceof AsymmetricMatcher)
184-
) {
185-
this.sample[property] = objectContaining(
186-
this.sample[property] as Record<string, unknown>,
187-
);
188-
}
184+
? objectContaining(this.sample[property] as Record<string, unknown>)
185+
: this.sample[property];
189186

190187
if (
191188
!hasProperty(other, property) ||
192-
!equals(this.sample[property], other[property])
189+
!equals(expected, other[property])
193190
) {
194191
return false;
195192
}

0 commit comments

Comments
 (0)