.toMatchObject(object)

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.

  1. const houseForSale = {
  2. bath: true,
  3. bedrooms: 4,
  4. kitchen: {
  5. amenities: ['oven', 'stove', 'washer'],
  6. area: 20,
  7. wallColor: 'white',
  8. },
  9. };
  10. const desiredHouse = {
  11. bath: true,
  12. kitchen: {
  13. amenities: ['oven', 'stove', 'washer'],
  14. wallColor: expect.stringMatching(/white|yellow/),
  15. },
  16. };
  17. test('the house has my desired features', () => {
  18. expect(houseForSale).toMatchObject(desiredHouse);
  19. });
  1. describe('toMatchObject applied to arrays', () => {
  2. test('the number of elements must match exactly', () => {
  3. expect([{foo: 'bar'}, {baz: 1}]).toMatchObject([{foo: 'bar'}, {baz: 1}]);
  4. });
  5. // .arrayContaining "matches a received array which contains elements that
  6. // are *not* in the expected array"
  7. test('.toMatchObject does not allow extra elements', () => {
  8. expect([{foo: 'bar'}, {baz: 1}]).toMatchObject([{foo: 'bar'}]);
  9. });
  10. test('.toMatchObject is called for each elements, so extra object properties are okay', () => {
  11. expect([{foo: 'bar'}, {baz: 1, extra: 'quux'}]).toMatchObject([
  12. {foo: 'bar'},
  13. {baz: 1},
  14. ]);
  15. });
  16. });