From 632db4140110d829087a2556292fe44676850025 Mon Sep 17 00:00:00 2001 From: Dan Dascalescu Date: Mon, 10 Jul 2017 02:47:57 -0700 Subject: [PATCH] Add that toMatchObject can match arrays (#3994) https://repl.it/JT0C --- docs/en/ExpectAPI.md | 40 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/docs/en/ExpectAPI.md b/docs/en/ExpectAPI.md index 4ed905cea775..410175591253 100644 --- a/docs/en/ExpectAPI.md +++ b/docs/en/ExpectAPI.md @@ -707,7 +707,11 @@ describe('grapefruits are healthy', () => { ### `.toMatchObject(object)` -Use `.toMatchObject` to check that a JavaScript object matches a subset of the properties of an object. You can match properties against values or against matchers. +Use `.toMatchObject` to check that a JavaScript object matches a subset of the properties of an object. It will match received objects with properties that are **not** in the expected object. + +You can also pass an array of objects, in which case the method will return true only if each object in the received array matches (in the `toMatchObject` sense described above) the corresponding object in the expected array. This is useful if you want to check that two arrays match in their number of elements, as opposed to `arrayContaining`, which allows for extra elements in the received array. + +You can match properties against values or against matchers. ```js const houseForSale = { @@ -732,6 +736,40 @@ test('the house has my desired features', () => { }); ``` +```js +describe('toMatchObject applied to arrays arrays', () => { + test('the number of elements must match exactly', () => { + expect([ + { foo: 'bar' }, + { baz: 1 } + ]).toMatchObject([ + { foo: 'bar' }, + { baz: 1 } + ]); + }); + + // .arrayContaining "matches a received array which contains elements that are *not* in the expected array" + test('.toMatchObject does not allow extra elements', () => { + expect([ + { foo: 'bar' }, + { baz: 1 } + ]).toMatchObject([ + { foo: 'bar' } + ]); + }); + + test('.toMatchObject is called for each elements, so extra object properties are okay', () => { + expect([ + { foo: 'bar' }, + { baz: 1, extra: 'quux' } + ]).toMatchObject([ + { foo: 'bar' }, + { baz: 1 } + ]); + }); +}); +``` + ### `.toHaveProperty(keyPath, value)` Use `.toHaveProperty` to check if property at provided reference `keyPath` exists for an object.