| | |

Vitest 05 🧪 Assertions — toBe, toEqual, and Deep Equality

⏱️ Estimated read: 9 min | |

The assertion is where a test states what it expects. Vitest provides two equality matchers that look similar and behave differently: toBe uses Object.is and fails on any value that is not the same reference or primitive; toEqual performs a deep structural comparison and passes when two distinct objects have the same contents. Choosing the wrong one produces either a false failure (a deep comparison where reference equality was intended) or a false pass (a reference comparison that happens to match on a primitive). The distinction is the most common source of confusion in a new Vitest suite, and it is the first thing to get right.

This chapter covers the equality matchers, the deep comparison rules that toEqual applies, and the matchers that assert on parts of a value rather than the whole. The sections that follow walk through reference versus structural equality, the asymmetric matchers, and the comparison traps that make toEqual pass when toBe should have failed.

Key point: toBe is Object.is and asserts the same reference or primitive; toEqual is deep structural equality and asserts the same contents; use toBe for primitives and toEqual for objects and arrays.


a. toBe and Object.is semantics

toBe wraps Object.is. For primitives, Object.is behaves like === except for two cases: NaN is equal to itself, and +0 and -0 are not equal. For objects, arrays, and functions, Object.is compares references, so two structurally identical objects fail toBe because they are different allocations.

import { expect } from "vitest";

// Primitives: passes when values are identical
expect(2 + 2).toBe(4);
expect("hello").toBe("hello");
expect(true).toBe(true);
expect(null).toBe(null);
expect(undefined).toBe(undefined);

// NaN is equal to itself
expect(NaN).toBe(NaN); // passes

// +0 and -0 are not equal
expect(0).not.toBe(-0); // passes (not equal)

// Objects: fails because references differ
const a = { x: 1 };
const b = { x: 1 };
expect(a).toBe(b); // fails — different references
expect(a).toBe(a); // passes — same reference

The Object.is semantics are why toBe is the correct matcher for primitives and the wrong matcher for objects. Two numbers with the same value are the same number; two objects with the same fields are not the same object. A test that asserts expect({ id: 1 }).toBe({ id: 1 }) fails, and the failure message shows two identical-looking objects, which is the confusing part.


b. toEqual and deep equality rules

toEqual compares the values recursively. It checks that both values have the same type, the same keys (for objects), the same length and elements (for arrays), and recursively equal values at each position. It ignores undefined properties, which is the one rule that surprises people: { a: 1, b: undefined } is toEqual to { a: 1 }, because the b key with an undefined value is treated as absent.

import { expect } from "vitest";

// Objects: deep comparison
expect({ id: 1, name: "Ana" }).toEqual({ id: 1, name: "Ana" });

// Arrays: element-by-element
expect([1, 2, 3]).toEqual([1, 2, 3]);

// Nested structures
expect({ user: { id: 1, tags: ["a"] } }).toEqual({
  user: { id: 1, tags: ["a"] },
});

// undefined properties are ignored
expect({ a: 1, b: undefined }).toEqual({ a: 1 }); // passes

// Type distinctions matter
expect({ a: 1 }).not.toEqual({ a: "1" }); // number vs string
expect([1, 2]).not.toEqual([2, 1]); // order matters

The undefined-ignoring rule is the reason toEqual is not a strict deep equal. The strict variant is toStrictEqual, which checks that the objects have the same type (class instances fail against plain objects), that undefined properties are present on both sides, and that sparse arrays have the same sparseness. toStrictEqual is the correct matcher when the difference between “absent” and “present with undefined” matters.

// toStrictEqual: undefined properties must match
expect({ a: 1, b: undefined }).toStrictEqual({ a: 1 }); // fails

// toStrictEqual: class instances fail against plain objects
class User { constructor(public name: string) {} }
expect(new User("Ana")).toStrictEqual({ name: "Ana" }); // fails

c. Asymmetric matchers and partial assertions

A test often needs to assert that a value has certain fields without specifying every field. The asymmetric matchers—expect.any(), expect.anything(), expect.stringContaining(), expect.objectContaining(), expect.arrayContaining(), expect.stringMatching()—are used inside toEqual (and toStrictEqual) to assert on parts of the value.

import { expect } from "vitest";

// Any number in the id field
expect({ id: 42, name: "Ana" }).toEqual({
  id: expect.any(Number),
  name: "Ana",
});

// Object containing at least these fields
expect({ id: 1, name: "Ana", role: "admin" }).toEqual(
  expect.objectContaining({ name: "Ana" })
);

// Array containing at least these elements
expect([1, 2, 3, 4]).toEqual(
  expect.arrayContaining([2, 4])
);

// String containing a substring
expect({ message: "User not found" }).toEqual({
  message: expect.stringContaining("not found"),
});

// String matching a regex
expect({ id: "usr_123" }).toEqual({
  id: expect.stringMatching(/^usr_/),
});

expect.anything() matches any value except null and undefined. expect.any(Constructor) matches any instance of the constructor, including primitives for String, Number, and Boolean. The asymmetric matchers compose: expect.objectContaining({ tags: expect.arrayContaining(["a"]) }) asserts that the object has a tags array that includes "a".

The asymmetric matchers are also usable with expect() directly, not only inside toEqual. expect(value).toEqual(expect.any(Number)) passes when value is a number. This is the pattern for asserting on a single value with a partial matcher.


Complete Example Session

// ============================================
// PART 1: THE MODULE UNDER TEST
// ============================================
// src/user.ts
export type User = { id: number; name: string; email: string };

export function createUser(id: number, name: string): User {
  return { id, name, email: `${name.toLowerCase()}@example.com` };
}

// ============================================
// PART 2: toBe FOR PRIMITIVES
// ============================================
import { describe, it, expect } from "vitest";
import { createUser } from "./user";

describe("createUser", () => {
  it("returns the given id", () => {
    expect(createUser(1, "Ana").id).toBe(1);
  });

  it("returns the given name", () => {
    expect(createUser(1, "Ana").name).toBe("Ana");
  });
});

// ============================================
// PART 3: toEqual FOR OBJECTS
// ============================================
describe("createUser (object)", () => {
  it("returns the full user object", () => {
    expect(createUser(1, "Ana")).toEqual({
      id: 1,
      name: "Ana",
      email: "ana@example.com",
    });
  });
});

// ============================================
// PART 4: ASYMMETRIC MATCHERS
// ============================================
describe("createUser (partial)", () => {
  it("returns a user with a generated email", () => {
    expect(createUser(1, "Ana")).toEqual(
      expect.objectContaining({
        email: expect.stringMatching(/@example\.com$/),
      })
    );
  });
});

// ============================================
// PART 5: toStrictEqual FOR PRESENCE
// ============================================
describe("toStrictEqual", () => {
  it("distinguishes absent from undefined", () => {
    const withUndefined = { a: 1, b: undefined };
    expect(withUndefined).toEqual({ a: 1 }); // passes
    expect(withUndefined).toStrictEqual({ a: 1 }); // fails
  });
});

The parts covered toBe for primitive fields, toEqual for the full object, asymmetric matchers for partial assertions, and toStrictEqual for the presence distinction.


Quick Reference

Equality Matchers

MatcherComparisonUse For
toBe(v)Object.isPrimitives, same reference
toEqual(v)Deep, ignores undefinedObjects, arrays
toStrictEqual(v)Deep, checks types and undefinedStrict structural equality

Asymmetric Matchers

MatcherMatches
expect.any(Ctor)Instance of constructor
expect.anything()Any non-null value
expect.stringContaining(s)String containing s
expect.stringMatching(re)String matching regex
expect.objectContaining(o)Object with at least these fields
expect.arrayContaining(a)Array with at least these elements

Comparison Traps

ExpressiontoBetoEqual
{a:1} vs {a:1}FailPass
{a:1,b:undefined} vs {a:1}FailPass
NaN vs NaNPassPass
0 vs -0FailPass
[1,2] vs [2,1]FailFail

Best Practices

✅ Do This:

// Primitives with toBe
expect(user.id).toBe(1);                                      // ✅

// Objects with toEqual
expect(user).toEqual({ id: 1, name: "Ana", email: "..." });   // ✅

// Partial objects with asymmetric matchers
expect(user).toEqual(expect.objectContaining({ name: "Ana" })); // ✅

// Presence-sensitive with toStrictEqual
expect(obj).toStrictEqual({ a: 1 });                          // ✅

❌ Don’t Do This:

// toBe for objects
expect({ a: 1 }).toBe({ a: 1 }); // always fails                // ❌

// toEqual when presence matters
expect({ a: 1, b: undefined }).toEqual({ a: 1 }); // hides bug  // ❌

// Asserting on every field when only one matters
expect(user).toEqual({ id: expect.any(Number), name: "Ana", email: "..." }); // brittle // ❌

Common Pitfalls

PitfallWhy It HappensFix
toBe fails on identical objectsReference comparisonUse toEqual
toEqual passes when a field is missingundefined ignoredUse toStrictEqual
expect.any() does not matchUsed outside toEqualUse inside a matcher or directly
Order-insensitive array comparisontoEqual checks orderSort before comparing or use arrayContaining

Real-World Examples

1. Primitive comparison

expect(count).toBe(3);

2. Deep object comparison

expect(user).toEqual({ id: 1, name: "Ana" });

3. Strict comparison

expect(obj).toStrictEqual({ a: 1 });

4. Any number

expect(response).toEqual({ id: expect.any(Number) });

5. Object containing

expect(user).toEqual(expect.objectContaining({ role: "admin" }));

6. Array containing

expect(tags).toEqual(expect.arrayContaining(["a", "b"]));

7. String matching

expect(id).toEqual(expect.stringMatching(/^usr_/));

8. NaN comparison

expect(result).toBe(NaN);

9. Order-sensitive array

expect([1, 2]).toEqual([1, 2]);

10. Order-insensitive assertion

expect([2, 1]).toEqual(expect.arrayContaining([1, 2]));

Visual

toBe vs toEqual

┌─────────────────────────────────────────────────────────┐
│  toBe: Object.is                                        │
│  {a:1} ──► reference A                                  │
│  {a:1} ──► reference B                                  │
│  A !== B → FAIL                                         │
│                                                         │
│  toEqual: deep                                          │
│  {a:1} ──► keys equal, values equal                     │
│  → PASS                                                 │
└─────────────────────────────────────────────────────────┘

toEqual vs toStrictEqual

┌─────────────────────────────────────────────────────────┐
│  const obj = { a: 1, b: undefined }                     │
│                                                         │
│  toEqual({ a: 1 })                                      │
│    → b ignored → PASS                                   │
│                                                         │
│  toStrictEqual({ a: 1 })                                │
│    → b present but not in expected → FAIL               │
│                                                         │
│  Use strict when presence matters.                      │
└─────────────────────────────────────────────────────────┘

Asymmetric Matchers

┌─────────────────────────────────────────────────────────┐
│  expect(user).toEqual({                                 │
│    id: expect.any(Number),                              │
│    name: expect.stringContaining("An"),                 │
│    role: expect.stringMatching(/admin|owner/),          │
│  })                                                     │
│                                                         │
│  Asserts on parts of the value, not every field         │
└─────────────────────────────────────────────────────────┘

Matcher Selection

┌─────────────────────────────────────────────────────────┐
│  Is the value a primitive?                              │
│         │                                               │
│    ┌────┴────┐                                          │
│    ▼         ▼                                          │
│   YES        NO                                         │
│    │         │                                          │
│    ▼         ▼                                          │
│  toBe     Does presence matter?                         │
│               │                                         │
│          ┌────┴────┐                                    │
│          ▼         ▼                                    │
│         YES        NO                                   │
│          │         │                                    │
│          ▼         ▼                                    │
│     toStrictEqual  toEqual                              │
└─────────────────────────────────────────────────────────┘

Summary

ItemValue
Primitive equalitytoBe (Object.is)
Deep equalitytoEqual (ignores undefined)
Strict deep equalitytoStrictEqual (checks types, undefined)
Any valueexpect.any(Constructor)
Partial objectexpect.objectContaining({ ... })
Partial arrayexpect.arrayContaining([...])
String patternexpect.stringMatching(/re/)

Key takeaways:

  • toBe is Object.is, not ===. It treats NaN as equal to itself and +0 as different from -0, and it compares objects by reference. Two structurally identical objects fail toBe .
  • toEqual is deep and ignores undefined. It compares contents recursively, and a property with an undefined value is treated as absent. This is the behavior that hides a missing field if the expected object omits it .
  • toStrictEqual is the presence-sensitive variant. It checks that undefined properties are present on both sides and that class instances do not match plain objects. Use it when the difference between absent and undefined matters .
  • Asymmetric matchers assert on parts of a value. expect.any(Number), expect.objectContaining(), and expect.arrayContaining() compose inside toEqual and let the test specify only the fields it cares about .
  • Array order is significant in toEqual. [1, 2] is not equal to [2, 1]. Use expect.arrayContaining() for order-insensitive assertions, or sort both sides before comparing .

Remember: toBe asks “is this the same value?” and toEqual asks “does this have the same contents?” The two questions are different for objects and the same for primitives. Use toBe on the primitive fields and toEqual on the structure; use toStrictEqual when a missing field must fail; use asymmetric matchers when the test should not depend on every field. The failure message for toBe on objects shows two identical-looking values, which is why the matcher selection is the first thing to check when a test fails unexpectedly.

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!