How to test for object keys and values with Jest?

Sometimes, we want to test for object keys and values with Jest.

In this article, we’ll look at how to test for object keys and values with Jest.

How to test for object keys and values with Jest?

To test for object keys and values with Jest, we can use the toMatchObject method.

For instance, we write:

const expected = {
  name: 'foo'
}
const actual = {
  name: 'foo',
  type: 'bar'
}
expect(actual).toMatchObject(expected)

to check if the expected.name property matches the actual.name property.

The type property is ignored in the test since type isn’t in actual.

Conclusion

To test for object keys and values with Jest, we can use the toMatchObject method.