Explain Codes LogoExplain Codes Logo

How can I test for object keys and values equality using Jest?

javascript
matchers
object-equality
jest
Nikita BarsukovbyNikita Barsukov·Feb 11, 2025
TLDR

To check object equality in Jest, expect().toEqual() is instrumental for ensuring matched keys and values.

expect({ name: 'Alice', age: 30 }).toEqual({ name: 'Alice', age: 30 });

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:

// What's in a name? Jest doesn't care about 'job' here. expect({ name: 'Alice', age: 30, job: 'Developer' }).toMatchObject({ name: 'Alice', age: 30 });

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:

// toStrictEqual: enforcing the fine line between being stood up and a random no-show. expect({ name: 'Alice', age: null }).not.toStrictEqual({ name: 'Alice', age: undefined });

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:

// Good news: 'age' is 30, not 'undefined going on 31' expect({ name: 'Alice', age: 30 }).toHaveProperty('age', 30);

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:

// When in doubt, Boolean it out: expect(Boolean(object['key'])).toBe(true);

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:

// Because 'expecting' Alice's age would be creepy and weird. expect({ name: 'Alice', age: 30 }).toEqual(expect.objectContaining({ name: 'Alice' }));

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:

// Nested validation? Jest.prototype.noProblem(). expect({ person: { name: 'Alice', age: 30 } }).toEqual({ person: { name: 'Alice', age: 30 } });

Verifying string patterns

When string patterns add a plot twist to your testing scenario, expect.stringContaining and expect.stringMatching arrive to save the day:

// String detectives, uncovering 'Hell'...o there. expect({ message: 'Hello, world!' }).toEqual({ message: expect.stringContaining('Hello') }); // Regex police, zooming in on the 'http:' in the url. expect({ url: 'http://example.com' }).toEqual({ url: expect.stringMatching(/^http:/) });

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:

// Multiple keys? Not on our watch! expect(object).toHaveProperty('key1'); expect(object).toHaveProperty('key2'); // Using OR operator to save the day when only one key is needed: expect(object).toHaveProperty('key1') || expect(object).toHaveProperty('key2');