Which equality matcher would you make your team's Jest 30 default for API responses and domain objects, and when would you allow partial matching instead?
answer
- exact matchers fail on an extra defined key
- partial matchers pass any extra key
- toStrictEqual adds undefined keys, sparseness, class type
- asymmetric matchers inside an exact match
- partial only for named 'at least these fields' cases
basics
~20 sDefault to an exact matcher over the whole object, ideally toStrictEqual, for anything crossing a trust boundary: partial matchers pass a leaked extra field such as a password hash. Allow partial matching only for "at least these fields" contracts.
solid answer
~40 sBoth exact matchers, `toEqual` and `toStrictEqual`, fail when the received object has an extra key with a real value. `toMatchObject` and `expect.objectContaining` never do, so a response test written with them passes the day a serializer starts sending `passwordHash`. For responses, events and logs, the default should therefore be an exact matcher over the whole object. Volatile fields stay loose through asymmetric matchers inside it, as in `toStrictEqual({ id: expect.any(Number), email })`. Between the two exact matchers, `toStrictEqual` also catches `undefined`-valued keys, sparse arrays and a class instance compared with a plain object, at the cost of churn on harmless refactors. Fixture builders keep that churn down. Partial matching is for named cases, such as pass-through third-party payloads, each with a comment. Shared custom matchers are registered in `setupFilesAfterEnv`.
code
javascript · 13 linestest('profile response exposes only public fields', async () => {
const body = await getProfile(7);
// passes even if body also carries passwordHash
expect(body).toMatchObject({ id: 7, email: '[email protected]' });
// fails the day an extra field appears; loose only where values vary
expect(body).toStrictEqual({
id: 7,
email: '[email protected]',
createdAt: expect.any(Date),
});
});go deeper
Know that toEqual and toStrictEqual compare whole objects, while toMatchObject checks only the listed keys.
Explain what toStrictEqual adds over toEqual, and how asymmetric matchers loosen a single value.
Spot a response test whose partial matcher would pass a leaked field, and rewrite it exactly.
Set the team's equality default, the named exceptions for partial matching, and how the rule is enforced.
## The decision Jest 30 offers several ways to compare a result with what you expect, and a team ends up with whichever one each author reaches for first. A lead can set a default instead, and the choice affects what the tests catch. ## The candidates | Matcher | Passes when | Misses | |---|---|---| | `toEqual` | every key matches recursively | an extra key whose value is `undefined`; `undefined` array items and sparseness; a class instance compared with a plain object | | `toStrictEqual` | the above, plus those cases | nothing on that list | | `toMatchObject`, `expect.objectContaining` | the listed keys match | **any extra key**, whatever its value | Both exact matchers fail on an extra key that has a real value. The partial ones never do. That one difference decides most of the policy. ## Why exactness is a security property Take a test of a profile endpoint's response body. If it asserts `expect(body).toMatchObject({ id: 7, email })`, it still passes on the day a serializer change starts sending `passwordHash`. An exact assertion fails that same day, because the body now has a key the expected object does not. For anything that crosses a trust boundary, such as API responses, emitted events and log payloads, the default should be an exact matcher over the whole object. Volatile values stay exact in shape through asymmetric matchers placed inside it: `toStrictEqual({ id: expect.any(Number), createdAt: expect.any(Date), email })` is exact about which keys exist and loose only about those values. ## toEqual or toStrictEqual as the default `toStrictEqual` also catches the smaller drifts: a mapper that starts returning a class instance instead of a plain object, an optional field that turns up as `undefined` instead of being absent, a sparse array. The cost is churn. A harmless refactor that changes an object's prototype fails tests that never cared about it. Teams that pick `toStrictEqual` usually pair it with fixture builders, so the expected objects are written once. Teams that pick `toEqual` accept the blind spots and save strictness for domain types where the class matters. ## When partial matching is allowed Partial matchers are honest where the contract really is "at least these fields": a large third-party payload the code passes through, a log line with many generated fields, or an error object carrying a stack. The rule should name those cases and ask for a comment on each use. A partial matcher picked to avoid updating a test is how an unexpected field ships. ## Custom matchers Domain matchers such as `toBeValidCents` make tests read better, but each one is code the team maintains. Register them once in a `setupFilesAfterEnv` module so every file sees them, add the TypeScript declaration next to it, and keep the set small. A matcher defined in one test file and assumed everywhere is the failure the senior question on this leaf diagnoses. ## Enforcing it - Write the default and the allowed exceptions into the contributing guide. - Add a lint rule from the team's test lint plugin that prefers the chosen equality matcher, so the default is the easy path. - In review, ask of every partial match: what extra field would this let through? ## Choosing A service with public APIs and sensitive fields should default to an exact matcher on response bodies, `toStrictEqual` where churn is acceptable and `toEqual` with fixture builders where it is not, and allow partial matching only for named cases. A library whose outputs are internal values can afford `toEqual` and save the debate for the types where structure matters.
- How would you roll a toStrictEqual default out to a suite with thousands of toEqual assertions?Not in one sweep. First replace partial matchers on response bodies, events and logs with exact ones, since that is where a leaked field slips through. Then move `toEqual` to `toStrictEqual` as files are touched, with the lint rule on for changed files. Each assertion that starts failing exposes an `undefined` key, a sparse array or a changed type; decide case by case whether the test or the code is wrong.
- How do you keep a timestamp from breaking an exact response assertion?Put an asymmetric matcher in that position inside the exact match, for example `createdAt: expect.any(Date)`, or control the clock. The assertion stays exact about which keys exist and loose only about that value, which a partial matcher over the rest would not be.
- toMatchObject fails when the response gains a new field.
- toEqual and toStrictEqual differ on extra keys with real values.
- Partial matching is safer because tests break less often.
- toStrictEqual cannot be combined with expect.any.
- Custom matchers belong in the first test file that needs them.
Assumes Jest 30, where toStrictEqual differs from toEqual on undefined-valued keys, undefined and sparse array items, and object types.