How can I test for object keys and values equality using Jest?
To check object equality in Jest, expect().toEqual() is instrumental for ensuring matched keys and values.
This assertion checks and passes if both objects are, in essence, identical clones of each other.
But oh, Jest has more tricks up its sleeve! It disowns comparability by providing you toMatchObject for partial matches and toStrictEqual for strict type and value comparisons.
Methodology in-depth: Using matchers
Partial verification with toMatchObject
When all you need to do is verify that an object has certain properties, Jest's toMatchObject becomes your partial-match best friend:
This only checks the properties we've outlined in the assertion, thereby ignoring any additional ones.
Strict type and value assessment with toStrictEqual
If preciseness is a priority and you need to certify both the type and value equality, toStrictEqual is an excellent choice:
The fun part? This test factors in the difference between null and undefined.
Isolating property verity with toHaveProperty
Sometimes, performing assertions on the existence and value of a single property, becomes a necessity. Meet toHaveProperty, the matcher that does just that:
The nitty-gritty: Dealing with object and key existence
Ensuring existence of non-null keys or values
When you're in a situation where keys truly matter and need to check for a truthy value, or ensure it's not null or undefined, Jasmin has a trick, and it's a pretty old one — typecasting to a boolean:
Expecting optional keys with objectContaining
If an exact match isn't your cup of tea and you need a matcher that's less picky, expect.objectContaining might be your new best friend:
This is most useful when dealing with objects that embrace optional keys.
Going the extra mile: Handling nested and complex objects
Matching patterns with nested objects
When nested objects are part of your scenery, you need a recusive pattern. Both toEqual and toMatchObject got your back here:
Verifying string patterns
When string patterns add a plot twist to your testing scenario, expect.stringContaining and expect.stringMatching arrive to save the day:
Pro-tips: Guardrails for robust testing
Fending off unintended assertions
Careful selection between toMatchObject and toStrictEqual can save you from test passes you never bargained for. Consider your case's particulars before choosing a matcher.
Combining the odds
Where multiple keys warrant validation, combine conditions with a smart strategy:
Was this article helpful?