In Jest 30, how do toMatchObject and asymmetric matchers such as expect.objectContaining and expect.any assert only part of a result?
answer
- subset versus whole
- placeholders inside the expected value
- how deep partial matching reaches
- arrays keep their length
basics
~20 stoMatchObject passes when the received object holds the expected properties, recursively, ignoring extras. Asymmetric matchers such as expect.any(Date) or expect.stringMatching(/^q_/) stand in for a single value inside toEqual or toMatchObject, so volatile fields need no exact value.
solid answer
~40 s`toMatchObject(expected)` checks a **subset**: every property in `expected` must exist on the received object with an equal value, nested objects are matched as subsets too, and extra properties are ignored. Arrays inside it are stricter: same length, each element matched as a subset. **Asymmetric matchers** are placeholders that sit where a literal would go: `expect.any(Date)`, `expect.anything()` (anything but `null` or `undefined`), `expect.stringMatching(/^q_/)`, `expect.closeTo(0.3)`, `expect.arrayContaining([...])` (a subset, any order) and Jest 30's `expect.arrayOf(...)` (every element matches). `expect.objectContaining({...})` is partial only at its own level: each listed property is compared with full deep equality. And for arrays, `toContain` compares items with `===`, while `toContainEqual` compares them deeply.
code
javascript · 31 linesfunction buildQuote(lines) {
return {
id: `q_${Date.now().toString(16)}`,
createdAt: new Date(),
lines,
total: lines.reduce((sum, line) => sum + line.qty * line.unit, 0),
currency: 'EUR',
};
}
test('buildQuote fills in the volatile fields', () => {
const quote = buildQuote([
{ sku: 'A1', qty: 1, unit: 0.1 },
{ sku: 'B2', qty: 1, unit: 0.2 },
]);
expect(quote).toEqual({
id: expect.stringMatching(/^q_[0-9a-f]+$/),
createdAt: expect.any(Date),
lines: expect.arrayOf(expect.objectContaining({ sku: expect.any(String) })),
total: expect.closeTo(0.3),
currency: 'EUR',
});
expect(quote).toMatchObject({
currency: 'EUR',
lines: [{ sku: 'A1' }, { sku: 'B2' }],
});
expect(quote.lines).toContainEqual({ sku: 'B2', qty: 1, unit: 0.2 });
});go deeper
Know that toMatchObject ignores extra properties and that expect.any and expect.stringMatching can stand in for values a test cannot predict.
Explain where partial matching stops: arrays in toMatchObject keep their length, objectContaining is partial one level deep, and toContain uses === on array items.
Keep partial assertions honest: a subset match on a response can miss an extra field that leaks data, so pair it with a strict check where the exact shape is the contract.
Agree when tests may assert subsets rather than whole objects, since over-partial suites stop catching shape regressions while over-strict ones churn on every added field.
## Why partial assertions exist Real results carry fields a test cannot predict. A quote builder might return a generated `id`, a `createdAt` timestamp, a floating-point `total` and the line items. Asserting that with `toEqual` and literal values is impossible, and asserting every field one line at a time buries the intent. Jest offers two tools for this: - **Subset matching**: `toMatchObject` checks only the properties you list. - **Asymmetric matchers**: placeholders such as `expect.any(Date)` that match a *kind* of value inside an otherwise exact expectation. They are called asymmetric because the comparison is one-directional: the placeholder sits in the expected value and decides for itself whether the received value fits. ## toMatchObject: a recursive subset `expect(received).toMatchObject(expected)` passes when every property in `expected` exists on `received` with an equal value. Its rules: - Extra properties on the received object are ignored, **at every nesting level**. - Arrays are not subsets: an array in `expected` must have the **same length** as the received one, and each element is matched as a subset of the element at the same position. - The constructor is not compared, so a class instance can match a plain object literal. - The received value must be a non-null object; anything else fails with *received value must be a non-null object*. - Any expected value can itself be an asymmetric matcher. When `toMatchObject` fails, the diff is printed against only the matching **subset** of the received object, not the whole thing, so the report shows the properties you asked about and how they differ rather than every unrelated field. That keeps failures on large objects readable, and it is one practical reason to prefer it over a long list of single-property assertions. ## Asymmetric matchers: placeholders for one value | Matcher | Matches | |---|---| | `expect.anything()` | any value except `null` and `undefined` | | `expect.any(Ctor)` | an instance of `Ctor`, or a primitive of that type, so `expect.any(Number)` matches `3` | | `expect.stringContaining(s)` | a string that contains `s` | | `expect.stringMatching(re)` | a string that matches the pattern | | `expect.closeTo(n, digits?)` | a number within two decimal digits of `n` by default | | `expect.arrayContaining(arr)` | an array containing every item of `arr`, in any order, extras allowed | | `expect.arrayOf(m)` | an array whose every element matches `m`, new in Jest 30 | | `expect.objectContaining(obj)` | a non-array object that has each listed property with an equal value | Most have an inverse under `expect.not`, such as `expect.not.stringMatching(re)`. They can be used inside `toEqual`, `toStrictEqual`, `toMatchObject`, as the argument to `toThrow`, and inside the call assertions on mock functions, which belong with mocking. ## The objectContaining trap `expect.objectContaining` is partial only at the level where you put it. The Jest 30 source compares each listed property with ordinary deep equality, so a nested plain object must match completely: 1. `expect({ a: { b: 1, c: 2 } }).toEqual(expect.objectContaining({ a: { b: 1 } }))` fails, because `a` is compared in full and `c` is extra. 2. `expect({ a: { b: 1, c: 2 } }).toMatchObject({ a: { b: 1 } })` passes, because subset matching recurses. 3. Nesting fixes the first form: `expect.objectContaining({ a: expect.objectContaining({ b: 1 }) })`. ## toContain versus toContainEqual Both ask whether a collection contains an item, but compare differently: - `toContain(item)` uses `===` for array items, so an object literal is never found in an array of objects. It also works on strings, as a substring check, and on other iterables such as a `Set`. - `toContainEqual(item)` compares each item with recursive equality, so `{ sku: 'B2', qty: 1 }` is found when an equal object is present. ## Picking the tool 1. Most fields predictable, a few volatile: `toEqual` with asymmetric matchers in the volatile fields. 2. Only a handful of fields matter: `toMatchObject`. 3. Membership in a list: `toContain` for primitives, `toContainEqual` for objects, `expect.arrayContaining` for several items. 4. A rule every element must satisfy: `expect.arrayOf`. Since Jest 30, object matching also ignores **non-enumerable** properties, which can change a result that compared hidden properties in Jest 29.
- Why does `expect({ a: { b: 1, c: 2 } }).toEqual(expect.objectContaining({ a: { b: 1 } }))` fail when `toMatchObject` with the same expectation passes?`expect.objectContaining` is partial only at its own level: each listed property is compared with ordinary deep equality, so `a` must equal `{ b: 1 }` exactly and the extra `c` breaks it. `toMatchObject` applies subset matching at every level. Nesting a second placeholder, `{ a: expect.objectContaining({ b: 1 }) }`, makes the inner level partial too.
- When is `toMatchObject` on an array stricter than `expect.arrayContaining`?`toMatchObject` with an array requires the same number of elements, in the same order, each matched as a subset of the element at that position. `expect.arrayContaining` only requires every expected item to appear somewhere in the received array, in any order, with extra elements allowed.
- toMatchObject ignores array length, so a missing line item still passes.
- expect.objectContaining makes every nested object partial as well.
- toContain finds an object in an array by comparing its fields.
- expect.anything() also matches null and undefined.
- expect.any(Number) only matches numbers created with new Number().
Assumes Jest 30, which added expect.arrayOf and excludes non-enumerable properties from object matching; the other matchers here behave as they did in Jest 29.