Jest 22 ๐ Asymmetric Matchers โ expect.any, expect.objectContaining, and expect.arrayOf in v30
Jest’s equality check is strict. When expect(received).toEqual(expected) runs, every property of the received value must match the expected value exactly, and a value the test does not know in advanceโa generated ID, a timestamp, a random tokenโbreaks the comparison. Asymmetric matchers are the escape hatch: they are objects that stand in for a value and match against a rule instead of an exact equality. expect.any(Number) matches any number, expect.objectContaining({ id: 1 }) matches an object that has at least that property, and expect.stringMatching(/^tok_/) matches a string against a pattern.
The matchers were introduced early in Jest’s life and have grown with each major version. Jest 30, released in June 2025, added expect.arrayOf and expect.arrayContaining gained the ability to combine with expect.objectContaining more cleanly, and the type definitions in @types/jest and jest itself were updated to reflect the new API. The matchers compose: an asymmetric matcher can nest inside another, and the whole tree is evaluated recursively.
This chapter covers the asymmetric matcher family, how toEqual and toStrictEqual differ in their handling of them, the v30 additions of expect.arrayOf and the improved expect.closeTo, and the patterns for using asymmetric matchers inside toHaveBeenCalledWith and expect.objectContaining. The sections that follow walk through expect.any and the type matchers, the structural matchers objectContaining and arrayContaining, the string matchers, and the v30-specific behavior.
Key point: Asymmetric matchers are stand-in values that match against a rule rather than an exact equality; they are the way to assert on a value whose exact content the test cannot know in advance, and they compose recursively inside toEqual, toStrictEqual, and the mock matchers.
Why asymmetric matchers exist
The unknown-value problem. A test that calls a function returning { id: crypto.randomUUID(), name: "Alice" } cannot write expect(result).toEqual({ id: "a1b2c3", name: "Alice" }) because the ID changes every run. The test cares that the result is an object with a name of "Alice" and an id that is a string, and the asymmetric matcher is the way to express that intent. expect.objectContaining({ id: expect.any(String), name: "Alice" }) says exactly what the test means.
The partial-match problem. A large objectโan HTTP response, a database row, a config objectโoften has dozens of fields, and the test cares about two of them. toEqual demands the full object, and the full object is fragile: a new field breaks the test even though the assertion is still valid. expect.objectContaining is the partial match, and it asserts only the fields the test names. The pattern is the default for API response assertions.
The composition problem. A value can be nested and every level can have an unknown part. A response { user: { id: <unknown>, posts: [<unknown>, <unknown>] } } needs an asymmetric matcher at each level, and the matchers must compose. expect.objectContaining({ user: expect.objectContaining({ id: expect.any(Number), posts: expect.arrayOf(expect.objectContaining({ title: expect.any(String) })) }) }) is the composed form, and the composition is what makes the matcher family useful.
The mock-argument problem. toHaveBeenCalledWith compares the arguments a mock received against the expected arguments. The arguments often include a generated valueโa request ID, a timestampโand the strict comparison fails. The asymmetric matcher in the expected argument list is the fix: expect(mock).toHaveBeenCalledWith(expect.objectContaining({ id: expect.any(String) })) passes regardless of the ID.
The trade-off. Asymmetric matchers loosen the assertion. expect.any(String) passes for the empty string, for a string of the wrong format, and for a string that breaks a downstream consumer. The matcher is a tool for the value whose exact content is genuinely unknowable, not a shortcut for the assertion the test is too lazy to write. The rule is to use the tightest matcher that still passes: expect.stringMatching(/^tok_[a-z0-9]{32}$/) is better than expect.any(String) when the format is known.
a. The type matchers: expect.any and expect.anything
expect.any(Constructor) matches a value that is an instance of the given constructor. It works with the built-in constructorsโNumber, String, Boolean, Object, Array, Function, Symbol, BigIntโand with custom classes.
// Matches any Number, including NaN and Infinity
expect(42).toEqual(expect.any(Number)); // โ
expect(NaN).toEqual(expect.any(Number)); // โ
expect("42").toEqual(expect.any(Number)); // โ (string, not number)
// Matches any String, including the empty string
expect("").toEqual(expect.any(String)); // โ
expect("hello").toEqual(expect.any(String)); // โ
// Matches any instance of a custom class
class User {
constructor(name) {
this.name = name;
}
}
expect(new User("Alice")).toEqual(expect.any(User)); // โ
expect({ name: "Alice" }).toEqual(expect.any(User)); // โ (plain object)
The check is instanceof, not a structural check, so a plain object never matches expect.any(User) even when it has the same shape. The expect.anything() matcher is the looser sibling: it matches any value except null and undefined.
// Matches anything except null and undefined
expect(0).toEqual(expect.anything()); // โ
expect("").toEqual(expect.anything()); // โ
expect(false).toEqual(expect.anything()); // โ
expect(null).toEqual(expect.anything()); // โ
expect(undefined).toEqual(expect.anything()); // โ
The expect.anything() matcher is the right tool for the field whose presence is asserted but whose value is genuinely irrelevantโa createdAt that is always a timestamp, a requestId that is always a UUID. The expect.any matcher is tighter because it asserts the type, and it should be preferred when the type is known.
The toStrictEqual variant treats expect.any differently from toEqual. The toEqual ignores undefined properties and sparse arrays, and toStrictEqual does not. The asymmetric matcher behavior is the same in both, but the strict check applies to the non-matcher parts of the object, so a test that asserts an object with an expect.any field should use toStrictEqual when the object’s own properties matter.
b. The structural matchers: objectContaining and arrayContaining
expect.objectContaining(subset) matches an object that has at least the properties in the subset, with matching values. Extra properties on the received object are allowed, and the subset is checked recursively, so an expect.any inside the subset is evaluated as an asymmetric matcher.
// Matches an object with at least these properties
const response = { id: 1, name: "Alice", email: "alice@example.com", role: "admin" };
expect(response).toEqual(
expect.objectContaining({
id: expect.any(Number), // โ
any number
name: "Alice", // โ
exact string
})
);
The matcher is not deep in the toEqual senseโit is deep in the sense that every property in the subset is compared with toEqual semantics, and an asymmetric matcher at any depth is honored. The expect.objectContaining inside another expect.objectContaining composes, and the composed form is the way to assert a nested structure.
// Composed: nested objectContaining inside objectContaining
const payload = {
user: { id: 7, name: "Bob", settings: { theme: "dark", lang: "en" } },
meta: { requestId: "req_abc123" },
};
expect(payload).toEqual(
expect.objectContaining({
user: expect.objectContaining({
settings: expect.objectContaining({ theme: "dark" }),
}),
meta: expect.anything(),
})
);
The arrayContaining(subset) matcher is the array sibling. It matches an array that contains every element in the subset, in any order, and it does not require the arrays to have the same length.
// Matches an array that contains these elements, in any order
expect([1, 2, 3, 4]).toEqual(expect.arrayContaining([3, 1])); // โ
expect([1, 2, 3, 4]).toEqual(expect.arrayContaining([5])); // โ
// Nested: array of objects with a matcher
expect([
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
]).toEqual(
expect.arrayContaining([
expect.objectContaining({ name: "Bob" }),
])
);
The arrayContaining is order-insensitive and subset-based, so [3, 1] matches [1, 2, 3, 4]. The length of the expected array is the number of required elements, not the required length of the received array, and the test that needs an exact length uses toHaveLength separately. The expect.arrayOf matcher, added in Jest 30, is the different tool: it matches an array whose every element matches a single matcher, which is the “array of T” assertion.
// Jest 30: every element matches the matcher
expect([1, 2, 3]).toEqual(expect.arrayOf(expect.any(Number))); // โ
expect([1, "two", 3]).toEqual(expect.arrayOf(expect.any(Number))); // โ
expect([]).toEqual(expect.arrayOf(expect.any(Number))); // โ
(vacuously)
The arrayOf is the universal quantifier where arrayContaining is the existential one, and the pair covers the two assertions an array test needs: at least these elements (arrayContaining) and all elements are of this kind (arrayOf).
c. The string matchers and the v30 additions
expect.stringContaining(substring) matches a string that contains the given substring, and expect.stringMatching(regexp | string) matches a string that matches the pattern.
// Substring match
expect("hello world").toEqual(expect.stringContaining("world")); // โ
expect("hello world").toEqual(expect.stringContaining("xyz")); // โ
// Regex match
expect("tok_abc123").toEqual(expect.stringMatching(/^tok_[a-z0-9]+$/)); // โ
expect("tok_abc123").toEqual(expect.stringMatching("abc")); // โ
(string is treated as regex source)
The stringMatching with a string argument treats the string as a regular expression source, not a literal, so expect.stringMatching("a.b") matches "a.b" and "axb". The regex argument is the safer form when the pattern contains characters that are regex metacharacters.
Jest 30 added expect.arrayOf and expect.closeTo, and it updated expect.arrayContaining to compose with the toStrictEqual check. The closeTo matcher is the floating-point comparison that toBeCloseTo exposes as a matcher, and the asymmetric form is the way to use it inside an object.
// Jest 30: floating-point comparison as an asymmetric matcher
expect({ temperature: 21.4999 }).toEqual({
temperature: expect.closeTo(21.5, 2), // โ
within 2 decimal places
});
// Without closeTo, the floating-point comparison fails
expect(0.1 + 0.2).toEqual(0.3); // โ (0.30000000000000004)
expect(0.1 + 0.2).toEqual(expect.closeTo(0.3)); // โ
(default precision 2)
The closeTo takes the expected value and an optional precision, defaulting to 2. The precision is the number of decimal places, and the comparison is Math.abs(received - expected) < Math.pow(10, -precision) / 2. The matcher is the asymmetric form of toBeCloseTo, and the object test that has a floating-point field uses it rather than the exact toEqual.
The expect.not namespace is the negation. expect.not.objectContaining({...}) matches a value that does not contain the subset, and the negation composes the same way the positive matcher does.
// Negation: the object must not contain the admin role
expect({ id: 1, role: "user" }).toEqual(
expect.not.objectContaining({ role: "admin" }) // โ
);
The expect.not is the v30 form of the negation. Earlier versions had expect.not.objectContaining as well, but the v30 release added expect.not.arrayOf to complete the family. The negated matcher is the assertion that the value is genuinely absent, and it is the right tool when the test checks that a sensitive fieldโa password, an admin flagโis not in the response.
Complete Example Session
// ============================================
// PART 1: THE TYPE MATCHERS
// ============================================
test("creates a user with a generated id", () => {
const user = createUser("Alice");
// The id is generated, the name is known
expect(user).toEqual({
id: expect.any(String), // any string passes
name: "Alice", // exact match
createdAt: expect.any(Date), // any Date instance
});
});
// ============================================
// PART 2: THE STRUCTURAL MATCHERS
// ============================================
test("returns the expected user fields", () => {
const response = { id: 1, name: "Alice", email: "a@x.com", role: "admin" };
// Only the fields the test cares about
expect(response).toEqual(
expect.objectContaining({
name: "Alice",
role: "admin",
})
);
});
// ============================================
// PART 3: THE COMPOSED FORM
// ============================================
test("returns a nested structure", () => {
const payload = {
user: { id: 7, name: "Bob", posts: [{ id: 1, title: "Hello" }] },
};
// Matchers nested inside matchers
expect(payload).toEqual(
expect.objectContaining({
user: expect.objectContaining({
id: expect.any(Number),
posts: expect.arrayContaining([
expect.objectContaining({ title: "Hello" }),
]),
}),
})
);
});
// ============================================
// PART 4: THE STRING MATCHERS
// ============================================
test("returns a token with the expected format", () => {
const { token } = login("alice@example.com");
// The token is generated, the format is known
expect(token).toEqual(expect.stringMatching(/^tok_[a-z0-9]{32}$/));
});
// ============================================
// PART 5: THE ARRAY MATCHERS
// ============================================
test("returns an array of users", () => {
const users = [{ id: 1, name: "Alice" }, { id: 2, name: "Bob" }];
// Every element is an object with a name
expect(users).toEqual(
expect.arrayOf(expect.objectContaining({ name: expect.any(String) }))
);
});
// ============================================
// PART 6: THE MOCK ARGUMENT MATCH
// ============================================
test("calls the logger with the right shape", () => {
const logger = jest.fn();
logger({ level: "info", message: "hello", timestamp: Date.now() });
// The timestamp is generated, the rest is known
expect(logger).toHaveBeenCalledWith(
expect.objectContaining({
level: "info",
message: "hello",
timestamp: expect.any(Number),
})
);
});
// ============================================
// PART 7: THE NEGATION
// ============================================
test("does not leak the password", () => {
const response = { id: 1, name: "Alice", role: "user" };
// The password must not be present
expect(response).toEqual(expect.not.objectContaining({ password: expect.anything() }));
});
// ============================================
// PART 8: THE FLOATING-POINT MATCH (v30)
// ============================================
test("computes the average within precision", () => {
const stats = { average: 0.1 + 0.2 };
// closeTo handles the floating-point imprecision
expect(stats).toEqual({ average: expect.closeTo(0.3, 2) });
});
// ============================================
// PART 9: THE STRICT VARIANT
// ============================================
test("the strict variant still honors matchers", () => {
const user = { id: 1, name: "Alice" };
// toStrictEqual ignores nothing; the matcher still works
expect(user).toStrictEqual({
id: expect.any(Number),
name: "Alice",
});
});
// ============================================
// PART 10: THE CUSTOM MATCHER
// ============================================
test("a custom asymmetric matcher", () => {
// The asymmetricMatcher property makes the object a matcher
const isEven = {
asymmetricMatch: (n) => typeof n === "number" && n % 2 === 0,
toString: () => "isEven",
};
expect(4).toEqual(isEven); // โ
expect(3).toEqual(isEven); // โ
});
The ten parts covered the type matchers, the structural matchers, the composed form, the string matchers, the array matchers, the mock argument match, the negation, the floating-point matcher, the strict variant, and the custom matcher.
Quick Reference
The Matcher Family
| Matcher | Matches |
|---|---|
expect.any(C) | An instance of constructor C |
expect.anything() | Any value except null/undefined |
expect.objectContaining(s) | An object with at least subset s |
expect.arrayContaining(a) | An array containing every element of a |
expect.arrayOf(m) | An array whose every element matches m (v30) |
expect.stringContaining(s) | A string containing substring s |
expect.stringMatching(r) | A string matching regex r |
expect.closeTo(n, p) | A number within p decimal places of n (v30) |
expect.not.<matcher> | The negation of any matcher |
The Array Matchers
| Matcher | Quantifier | Order | Length |
|---|---|---|---|
arrayContaining | Existential (at least) | Any | Not required |
arrayOf | Universal (every) | N/A | Not required |
toHaveLength | Exact | N/A | Exact |
The Equality Matchers and Asymmetric Matchers
| Matcher | Ignores undefined | Honors Asymmetric |
|---|---|---|
toEqual | Yes | Yes |
toStrictEqual | No | Yes |
toHaveBeenCalledWith | Yes | Yes |
toMatchObject | Yes | Yes |
Best Practices
โ Do This:
// Use the tightest matcher that still passes
expect(token).toEqual(expect.stringMatching(/^tok_[a-z0-9]{32}$/)); // โ
// Use objectContaining for partial matches
expect(response).toEqual(expect.objectContaining({ id: 1 })); // โ
// Use arrayOf for every-element assertions
expect(users).toEqual(expect.arrayOf(expect.objectContaining({}))); // โ
// Use closeTo for floating-point fields
expect(stats).toEqual({ avg: expect.closeTo(0.3, 2) }); // โ
// Use the composed form for nested structures
expect(payload).toEqual(expect.objectContaining({ // โ
user: expect.objectContaining({ id: expect.any(Number) }),
}));
โ Don’t Do This:
// Use any(String) when the format is known
expect(token).toEqual(expect.any(String)); // โ
// Use arrayContaining when the length matters
expect(list).toEqual(expect.arrayContaining([1, 2, 3])); // โ
// Use toEqual for a floating-point comparison
expect(0.1 + 0.2).toEqual(0.3); // โ
// Use a loose matcher to skip the assertion
expect(user).toEqual(expect.anything()); // โ
// Forget that toStrictEqual still checks undefined properties
expect({ a: 1, b: undefined }).toStrictEqual({ a: 1 }); // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Matcher passes for the wrong value | expect.any(String) accepts any string | Use expect.stringMatching |
arrayContaining passes with wrong length | It is a subset match | Add toHaveLength |
| Floating-point assertion fails | toEqual is exact | Use expect.closeTo |
expect.any(User) fails for a plain object | It is an instanceof check | Use objectContaining |
| Mock argument mismatch | The argument has a generated value | Use objectContaining in toHaveBeenCalledWith |
| Nested matcher not honored | Wrong matcher at the wrong depth | Nest objectContaining / arrayContaining |
toStrictEqual fails on undefined | undefined properties are compared | Remove the property or use toEqual |
| Custom matcher does not match | asymmetricMatch returns non-boolean | Return a strict boolean |
Real-World Examples
1. Generated ID in a response
expect(response).toEqual({ id: expect.any(String), name: "Alice" });
2. Partial API response
expect(body).toEqual(expect.objectContaining({ status: "ok" }));
3. Token format
expect(token).toEqual(expect.stringMatching(/^tok_[a-z0-9]{32}$/));
4. Array of every element
expect(items).toEqual(expect.arrayOf(expect.objectContaining({ id: expect.any(Number) })));
5. Mock argument with a timestamp
expect(logger).toHaveBeenCalledWith(expect.objectContaining({ ts: expect.any(Number) }));
6. No password leaked
expect(user).toEqual(expect.not.objectContaining({ password: expect.anything() }));
7. Floating-point average
expect(stats).toEqual({ avg: expect.closeTo(0.3, 2) });
8. Nested structure
expect(payload).toEqual(expect.objectContaining({ user: expect.objectContaining({ id: expect.any(Number) }) }));
9. Anything-but-null
expect(value).toEqual(expect.anything());
10. Custom matcher
const isEven = { asymmetricMatch: (n) => n % 2 === 0, toString: () => "isEven" };
Visual
The Matcher Family Tree
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ASYMMETRIC MATCHERS โ
โ โ
โ Type Structural String โ
โ โโโโโโโโโ โโโโโโโโโโ โโโโโโ โ
โ expect.any objectContaining stringContaining โ
โ expect. arrayContaining stringMatching โ
โ anything arrayOf โ
โ closeTo โ
โ โ
โ Negation: expect.not.<matcher> โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
objectContaining vs toEqual
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ RECEIVED: { id: 1, name: "A", email: "x", role: "u" } โ
โ EXPECTED: { id: 1, name: "A" } โ
โ โ
โ toEqual โ โ (extra fields) โ
โ objectContaining โ โ
(subset) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
arrayContaining vs arrayOf
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ arrayContaining([1, 2]) โ
โ "at least 1 and 2, any order" โ
โ [1, 2, 3] โ โ
[1] โ โ โ
โ [2, 1] โ โ
[1, 2, 3, 9] โ โ
โ
โ โ
โ arrayOf(any(Number)) โ
โ "every element is a number" โ
โ [1, 2, 3] โ โ
[1, "x"] โ โ โ
โ [] โ โ
(vacuous) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Composition
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ expect.objectContaining({ โ
โ user: expect.objectContaining({ โ
โ id: expect.any(Number), โ
โ posts: expect.arrayOf( โ
โ expect.objectContaining({ โ
โ title: expect.any(String), โ
โ }) โ
โ ), โ
โ }), โ
โ }) โ
โ โ
โ The outer matcher delegates to the inner matchers, โ
โ and the whole tree is evaluated recursively. โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Type matcher | expect.any(Constructor) |
| Anything matcher | expect.anything() (excludes null/undefined) |
| Partial object | expect.objectContaining(subset) |
| Array subset | expect.arrayContaining(elements) |
| Array every | expect.arrayOf(matcher) (v30) |
| String substring | expect.stringContaining(s) |
| String pattern | expect.stringMatching(regex) |
| Float comparison | expect.closeTo(n, precision) (v30) |
| Negation | expect.not.<matcher> |
| Custom matcher | Object with asymmetricMatch method |
Key takeaways:
- Asymmetric matchers are stand-in values matched by rule, not equality. They are the way to assert on a value whose exact content is unknownโa generated ID, a timestamp, a tokenโand the assertion still names the shape the test requires.
expect.objectContainingis the partial match. It asserts only the properties the test names, allows extra properties, and is the default for API response assertions where a new field must not break the test.expect.arrayContainingandexpect.arrayOfare the two array quantifiers. The first is existential (at least these elements, any order) and the second is universal (every element matches the matcher, added in v30), and the test that needs both uses both.- The matchers compose recursively. An
objectContaininginside anobjectContaininginside anarrayOfis evaluated at every depth, and the composed form is how a nested structure is asserted without writing a full literal. expect.closeToin v30 is the floating-point matcher. It takes a precision argument and replaces the exacttoEqualfor numeric fields, and it composes withobjectContainingso a stats object is asserted in one call.
Remember: The asymmetric matcher is the tool for the value the test cannot know in advance, and the assertion is only as strong as the tightest matcher that still passes. Use expect.stringMatching over expect.any(String) when the format is known, expect.objectContaining over a full toEqual when the extra fields are irrelevant, expect.arrayOf over arrayContaining when every element matters, and expect.closeTo for every floating-point field. The matcher family is small, and the discipline is picking the one that asserts exactly the intent.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!