| | |

Jest 22 ๐Ÿƒ Asymmetric Matchers โ€” expect.any, expect.objectContaining, and expect.arrayOf in v30

โฑ๏ธ Estimated read: 15 min | |

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

MatcherMatches
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

MatcherQuantifierOrderLength
arrayContainingExistential (at least)AnyNot required
arrayOfUniversal (every)N/ANot required
toHaveLengthExactN/AExact

The Equality Matchers and Asymmetric Matchers

MatcherIgnores undefinedHonors Asymmetric
toEqualYesYes
toStrictEqualNoYes
toHaveBeenCalledWithYesYes
toMatchObjectYesYes

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

PitfallWhy It HappensFix
Matcher passes for the wrong valueexpect.any(String) accepts any stringUse expect.stringMatching
arrayContaining passes with wrong lengthIt is a subset matchAdd toHaveLength
Floating-point assertion failstoEqual is exactUse expect.closeTo
expect.any(User) fails for a plain objectIt is an instanceof checkUse objectContaining
Mock argument mismatchThe argument has a generated valueUse objectContaining in toHaveBeenCalledWith
Nested matcher not honoredWrong matcher at the wrong depthNest objectContaining / arrayContaining
toStrictEqual fails on undefinedundefined properties are comparedRemove the property or use toEqual
Custom matcher does not matchasymmetricMatch returns non-booleanReturn 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

ItemValue
Type matcherexpect.any(Constructor)
Anything matcherexpect.anything() (excludes null/undefined)
Partial objectexpect.objectContaining(subset)
Array subsetexpect.arrayContaining(elements)
Array everyexpect.arrayOf(matcher) (v30)
String substringexpect.stringContaining(s)
String patternexpect.stringMatching(regex)
Float comparisonexpect.closeTo(n, precision) (v30)
Negationexpect.not.<matcher>
Custom matcherObject 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.objectContaining is 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.arrayContaining and expect.arrayOf are 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 objectContaining inside an objectContaining inside an arrayOf is evaluated at every depth, and the composed form is how a nested structure is asserted without writing a full literal.
  • expect.closeTo in v30 is the floating-point matcher. It takes a precision argument and replaces the exact toEqual for numeric fields, and it composes with objectContaining so 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.

Was this helpful?


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!