Categories
JavaScript Answers

How to test for object keys and values with Jest?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *