Scope: Deep-dive into the
expectassertion engine across Jest and Vitest, equality algorithms (toBevstoEqualvstoStrictEqual), asymmetric matchers, soft assertions, async polling (expect.poll), and custom matcher authoring (expect.extend).
- Assertions, Matchers & Expect API Architecture (Jest & Vitest)
- Table of Contents
- 1. The Equality Spectrum:
toBevs.toEqualvs.toStrictEqual - 2. Asymmetric Matchers & Partial Object Matching
- 3. Modern Vitest Expect Capabilities
- 4. Promise Assertions:
.resolves&.rejects - 5. Authoring Custom Matchers with
expect.extend - 6. Complete Matchers Quick-Reference Matrix
- 7. Official Documentation & Authoritative References
Choosing the wrong equality matcher causes false passes or confusing test failures:
+-----------------------+------------------------------------+------------------------------------+
| Matcher | Comparison Algorithm | Edge Case Handling |
+-----------------------+------------------------------------+------------------------------------+
| **`toBe(val)`** | `Object.is(a, b)` (Primitive / | Checks memory reference equality. |
| | Strict reference identity) | `{ a: 1 } !== { a: 1 }` (Fails!) |
+-----------------------+------------------------------------+------------------------------------+
| **`toEqual(val)`** | Deep recursive value equality | ⚠️ Ignores `undefined` object |
| | | keys & class prototypes. |
+-----------------------+------------------------------------+------------------------------------+
| **`toStrictEqual()`** | Strict deep value & type equality | ✅ Checks prototypes, array holes, |
| | (Gold standard for objects) | and explicit `undefined` fields. |
+-----------------------+------------------------------------+------------------------------------+
class User {
name: string;
constructor(name: string) {
this.name = name;
}
}
const obj1 = { name: 'Atul' };
const obj2 = new User('Atul');
// ⚠️ toEqual PASSES (ignores class prototype difference!):
expect(obj1).toEqual(obj2); // PASSES
// ✅ toStrictEqual FAILS (catches class prototype mismatch!):
expect(obj1).toStrictEqual(obj2); // FAILS (Correct behavior!)When asserting on complex objects containing dynamic timestamps, auto-incrementing IDs, or random UUIDs, use Asymmetric Matchers instead of fragile exact object snapshots:
it('creates user with dynamic server timestamps', () => {
const user = createUser('atul@example.com');
expect(user).toEqual(
expect.objectContaining({
id: expect.stringMatching(/^usr_[a-z0-9]{12}$/),
email: 'atul@example.com',
createdAt: expect.any(Date),
roles: expect.arrayContaining(['USER']),
metadata: expect.anything(),
}),
);
});expect.anything(): Matches anything exceptnullorundefined.expect.any(Constructor): Matches any value created with the given constructor (e.g.expect.any(Number),expect.any(Function)).expect.stringContaining(str)/expect.stringMatching(regex).expect.arrayContaining(array): Matches arrays containing a subset of items in any order.expect.objectContaining(obj): Matches objects containing a subset of key-value pairs.expect.not.objectContaining(obj).
By default, an assertion failure immediately terminates test execution, skipping all subsequent checks. expect.soft() marks the failure but continues running subsequent assertions, allowing you to see all errors in a single test run:
it('validates entire user response structure', () => {
const res = fetchUserProfile();
expect.soft(res.status).toBe(200);
expect.soft(res.body.name).toBe('Atul');
expect.soft(res.body.role).toBe('Staff Engineer');
expect.soft(res.body.isActive).toBe(true);
// All failing assertions are reported together at test completion!
});Instead of writing manual retry loops, expect.poll(fn, options) continuously re-evaluates a callback until the assertion passes or times out:
it('polls job status until completion', async () => {
submitAsyncJob('job_123');
// Polls getJobStatus('job_123') every 100ms up to 3000ms
await expect
.poll(() => getJobStatus('job_123'), {
timeout: 3000,
interval: 100,
})
.toBe('COMPLETED');
});Ensures that guarded code branches are never reached:
it('throws a specific validation error', async () => {
try {
await processPayment({ amount: -50 });
expect.unreachable('Payment with negative amount should have thrown!');
} catch (err: any) {
expect(err.message).toMatch(/invalid amount/i);
}
});Always await promise assertion chains to avoid unhandled async rejections:
it('handles async resolutions and rejections', async () => {
// 1. Resolves
await expect(fetchUser(10)).resolves.toEqual({ id: 10, name: 'Atul' });
// 2. Rejects
await expect(fetchUser(-1)).rejects.toThrow('User not found');
await expect(fetchUser(-1)).rejects.toThrowError(NotFoundError);
});Create reusable, domain-specific matchers to drastically improve test readability and error reporting:
// matchers/toBeWithinRange.ts
import { expect } from 'vitest';
expect.extend({
toBeWithinRange(received: number, floor: number, ceiling: number) {
const pass = received >= floor && received <= ceiling;
if (pass) {
return {
message: () => `expected ${received} not to be within range ${floor} - ${ceiling}`,
pass: true,
};
} else {
return {
message: () => `expected ${received} to be within range ${floor} - ${ceiling}`,
pass: false,
};
}
},
});
// TypeScript declaration merging
declare module 'vitest' {
interface Assertion<T = any> {
toBeWithinRange(floor: number, ceiling: number): void;
}
}// Usage in tests:
it('computes response time within acceptable SLA range', () => {
const latencyMs = calculateLatency();
expect(latencyMs).toBeWithinRange(10, 50);
});| Matcher Category | Methods | Example |
|---|---|---|
| Identity & Values | toBe, toEqual, toStrictEqual, toBeDefined, toBeUndefined, toBeNull, toBeNaN |
expect(val).toBeNull() |
| Truthiness | toBeTruthy, toBeFalsy |
expect(isActive).toBeTruthy() |
| Numbers & Math | toBeGreaterThan, toBeGreaterThanOrEqual, toBeLessThan, toBeCloseTo |
expect(0.1 + 0.2).toBeCloseTo(0.3, 5) |
| Strings & Regex | toMatch, toContain |
expect('Hello World').toMatch(/world/i) |
| Arrays & Iterables | toContain, toContainEqual, toHaveLength |
expect(users).toHaveLength(3) |
| Exceptions | toThrow, toThrowError |
expect(() => parse('')).toThrow(TypeError) |
| Mock Functions | toHaveBeenCalled, toHaveBeenCalledTimes, toHaveBeenCalledWith, toHaveReturnedWith |
expect(spy).toHaveBeenCalledTimes(1) |
| Snapshots | toMatchSnapshot, toMatchInlineSnapshot, toThrowErrorMatchingSnapshot |
expect(dom).toMatchSnapshot() |