.toHaveProperty(keyPath, value)

Use .toHaveProperty to check if property at provided reference keyPath exists for an object. For checking deeply nested properties in an object you may use dot notation or an array containing the keyPath for deep references.

Optionally, you can provide a value to check if it's equal to the value present at keyPath on the target object. This matcher uses 'deep equality' (like toEqual()) and recursively checks the equality of all fields.

The following example contains a houseForSale object with nested properties. We are using toHaveProperty to check for the existence and values of various properties in the object.

  1. // Object containing house features to be tested
  2. const houseForSale = {
  3. bath: true,
  4. bedrooms: 4,
  5. kitchen: {
  6. amenities: ['oven', 'stove', 'washer'],
  7. area: 20,
  8. wallColor: 'white',
  9. 'nice.oven': true,
  10. },
  11. 'ceiling.height': 2,
  12. };
  13. test('this house has my desired features', () => {
  14. // Simple Referencing
  15. expect(houseForSale).toHaveProperty('bath');
  16. expect(houseForSale).toHaveProperty('bedrooms', 4);
  17. expect(houseForSale).not.toHaveProperty('pool');
  18. // Deep referencing using dot notation
  19. expect(houseForSale).toHaveProperty('kitchen.area', 20);
  20. expect(houseForSale).toHaveProperty('kitchen.amenities', [
  21. 'oven',
  22. 'stove',
  23. 'washer',
  24. ]);
  25. expect(houseForSale).not.toHaveProperty('kitchen.open');
  26. // Deep referencing using an array containing the keyPath
  27. expect(houseForSale).toHaveProperty(['kitchen', 'area'], 20);
  28. expect(houseForSale).toHaveProperty(
  29. ['kitchen', 'amenities'],
  30. ['oven', 'stove', 'washer'],
  31. );
  32. expect(houseForSale).toHaveProperty(['kitchen', 'amenities', 0], 'oven');
  33. expect(houseForSale).toHaveProperty(['kitchen', 'nice.oven']);
  34. expect(houseForSale).not.toHaveProperty(['kitchen', 'open']);
  35. // Referencing keys with dot in the key itself
  36. expect(houseForSale).toHaveProperty(['ceiling.height'], 'tall');
  37. });