new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Vitest · API reference · all subjects

expect api

84 notes in this subject, read out of this brain and free to use. This is page 1 of 2.

Custom matcher type example with toBeFoo

Example of extending Matchers for a custom toBeFoo matcher: declare module 'vitest' { interface Matchers<T = any> extends CustomMatchers<T> {} }. Then implement expect.extend({ toBeFoo(actual, arg) { return { pass: true, message: () => '' } } }). This enables type-safe usage of expect('foo').toBeFoo('foo') and expect.toBeFoo('foo').

Matchers type for custom matcher type support

Vitest 3.2 introduces a Matchers type that can be extended to add type support for custom matchers across all use cases: expect().to*, expect.to*, and expect.extend({ to* }). To use it, declare a module augmentation extending the Matchers interface with a CustomMatchers interface containing your custom matcher signatures.

expect.assert for type-aware assertions

Vitest exposes expect.assert method for easy access to Chai's assert function. This is especially useful for narrowing down types, since expect.to* methods do not support that. Example: expect.assert(animal.__type === 'Dog') allows type narrowing that expect().toBe() would not.

toMatchScreenshot assertion for visual regression testing

The toMatchScreenshot assertion captures screenshots of UI components and pages, then compares them against reference images to detect unintended visual changes. Usage: await expect(page.getByTestId('hero')).toMatchScreenshot('hero-section')

expect.schemaMatching asymmetric matcher for Standard Schema v1

expect.schemaMatching is an asymmetric matcher that accepts a Standard Schema v1 object and validates values against it, passing the assertion when the value conforms to the schema. It can be used with toEqual, toStrictEqual, toMatchObject, toContainEqual, toThrow, toHaveBeenCalledWith, toHaveReturnedWith and toHaveBeenResolvedWith. Example: expect(user).toEqual({ email: expect.schemaMatching(z.string().email()) })

Chai-style mock assertions supported

Vitest supports chai-style assertions for mocks: expect(fn).to.have.been.called (equivalent to toHaveBeenCalled), expect(fn).to.have.been.calledWith('example') (equivalent to toHaveBeenCalledWith), expect(fn).to.have.returned (equivalent to toHaveReturned), and expect(fn).to.have.callCount(1) (equivalent to toHaveBeenCalledTimes(1)).

expect.poll.timeout config option

expect.poll.timeout is a number configuration option (default: 1000) that sets the polling timeout in milliseconds for the expect.poll global configuration.

expect.requireAssertions config option

expect.requireAssertions is a boolean configuration option (default: false) that, when set to true, automatically calls expect.hasAssertions() at the start of every test. This ensures that no test will pass accidentally without making assertions. It only works with Vitest's expect; other assertion libraries like assert or .should will not count toward this requirement and will cause tests to fail due to lack of expect assertions.

expect.requireAssertions with concurrent tests warning

When you run tests with sequence.concurrent and expect.requireAssertions set to true, you should use local expect from test context instead of the global one to avoid false negatives.

expect.poll.interval config option

expect.poll.interval is a number configuration option (default: 50) that sets the polling interval in milliseconds for the expect.poll global configuration.

toMatchScreenshot argument path resolution

The arg parameter in resolveScreenshotPath is derived from arguments passed to toMatchScreenshot: if called without arguments it is an auto-generated name (e.g. 'calls-onclick-1'); if called with a path like 'foo/bar/baz.png' the arg is 'foo/bar/baz' (without extension, sanitized and relative to test file, with leading ../ removed); the extension is always sanitized to '.png' if unsupported.

Custom comparator declaration example

To create a custom comparator named 'myCustomComparator', first declare its options type in a module declaration for ScreenshotComparatorRegistry interface, then register the comparator function in browser.expect.toMatchScreenshot.comparators. The comparator receives reference image, actual image, and options object containing createDiff plus the custom options (sensitivity, ignoreColors, etc.). It returns an object with pass (boolean), diff (TypedArray or null), and message (string or null) properties.

browser.expect.toMatchScreenshot.resolveDiffPath function

Type: (data: PathResolveData) => string. Default output: path.resolve(root, attachmentsDir, testFileDirectory, testFileName, `${arg}-${browserName}-${platform}${ext}`). A customizable function that determines where diff images are stored when screenshot comparisons fail. Receives the same data object as resolveScreenshotPath.

browser.expect.toMatchScreenshot.resolveScreenshotPath function

Type: (data: PathResolveData) => string. Default output: path.resolve(root, testFileDirectory, screenshotDirectory, testFileName, `${arg}-${browserName}-${platform}${ext}`). A customizable function that determines where reference screenshots are stored. It receives data containing: arg (sanitized path without extension), ext (extension with dot, defaults to '.png'), browserName (browser instance name), platform (process.platform value), screenshotDirectory (directory name for screenshots), root (project root absolute path), testFileDirectory (path to test file relative to root), testFileName (test's filename), testName (test name including parent describe, sanitized), attachmentsDir (attachments directory), and project (TestProject the test belongs to, experimental 4.1.6).

browser.expect.toMatchScreenshot.screenshotDirectory

Type: string | undefined. Default: '__screenshots__'. This option specifies the directory name used for storing reference screenshots. The value is passed to resolveScreenshotPath and resolveDiffPath functions and is used in the default path resolution.

toMatchScreenshot default options configuration

Default options for toMatchScreenshot can be configured at browser.expect.toMatchScreenshot to apply consistently across all screenshot assertions in the test suite. Individual tests can still override these defaults when needed.

browser.expect.toMatchScreenshot.comparators registration

Type: Record<string, Comparator>. Custom screenshot comparison algorithms can be registered by providing a record mapping comparator names to comparator functions. To use TypeScript, declare the comparator's options in the ScreenshotComparatorRegistry interface using module declaration.

Comparator function signature and pixel data format

Comparator functions have signature: (reference, actual, options) => Promise<{pass, diff, message}> | {pass, diff, message}. Reference and actual objects contain metadata (height, width) and data (TypedArray in RGBA format). Pixel data is a flat TypedArray with 4 bytes per pixel (red, green, blue, alpha from 0-255 each), stored in row-major order (left-to-right, top-to-bottom), with total length of width × height × 4 bytes. Alpha channel is always present; images without transparency have alpha set to 255 (fully opaque). The options parameter includes createDiff (boolean indicating if diff image is needed) plus any custom comparator options. All comparator options must be optional with default values.

createDiff performance optimization flag

The createDiff option in comparators indicates whether a diff image is needed. During stable screenshot detection, Vitest calls comparators with createDiff: false to avoid unnecessary work. Comparator implementations should respect this flag to keep tests fast.

Custom matcher currentTestName property

Inside a custom matcher function, this.currentTestName provides the full name of the current test including describe block.

Custom matcher testPath property

Inside a custom matcher function, this.testPath provides the file path to the current test.

Custom matcher environment property

Inside a custom matcher function, this.environment provides the name of the current environment, for example 'jsdom'.

Custom matcher soft property

Inside a custom matcher function, this.soft indicates whether the assertion was called as a soft assertion. You do not need to respect it; Vitest will always catch the error.

Custom matcher assertion property

Inside a custom matcher function, this.assertion (available since version 5.0.0) provides the underlying Chai assertion object. This is the same instance that Chai plugins receive, giving access to Chai's flag system and chainable methods. It is useful for building custom matchers that need to interact with Chai's internals.

Custom matcher with received value comparison

When declaring custom matchers in TypeScript where an argument should have the same type as the received value, use the generic type T in the Matchers interface. For example: toEqualTyped: (expected: T) => R

Vitest types for custom matchers

Since version 4.1, Vitest exports three types for custom matchers: Matcher (the function type), MatcherResult (the return value), and MatcherState (state available as this).

expect.extend basic example

Example of a simple custom matcher: ```ts expect.extend({ toBeFoo(received) { const { isNot } = this return { pass: received === 'foo', message: () => `${received} is${isNot ? ' not' : ''} foo` } } }) ```

Asynchronous custom matcher example

Example of an asynchronous custom matcher: ```ts expect.extend({ async toBeAsyncAssertion(received) { return { pass: received === 'foo', message: () => `expected ${received} to be foo`, } } }) declare module 'vitest' { interface Matchers<R, T> { toBeAsyncAssertion: () => Promise<void> } } await expect('foo').toBeAsyncAssertion() ``` For asynchronous matchers, declare return type as Promise<void> instead of R and await the matcher in the test.

Custom matcher with Matcher type example

Example using Vitest's exported types: ```ts import type { Matcher, MatcherResult, MatcherState } from 'vitest' import { expect } from 'vitest' const customMatcher: Matcher = function (received) { // simple matcher } const customMatcher: Matcher<MatcherState, [arg1: unknown, arg2: unknown]> = function (received, arg1, arg2) { // matcher with arguments } function customMatcher(this: MatcherState, received: unknown, arg1: unknown, arg2: unknown): MatcherResult { return { pass: false, message: () => 'something went wrong!', } } expect.extend({ customMatcher }) ```

Custom snapshot matchers

To build custom snapshot matchers (wrappers around toMatchSnapshot(), toMatchInlineSnapshot(), or toMatchFileSnapshot()), use the Snapshots type exported from vitest.

Custom matcher isNot property

Inside a custom matcher function, this.isNot returns true if the matcher was called with .not (e.g., expect(received).not.toBeFoo()). Do not alter the pass value based on isNot; Vitest reverses it automatically.

expect.extend basic usage

To extend default matchers in Vitest, call expect.extend with an object containing your matchers. The matcher function receives the received value as the first argument and should return an object with pass (boolean), message (function returning string), and optionally actual, expected, and meta properties.

expect.extend matcher return value interface

A matcher's return value should be compatible with SyncMatcherResult or Promise<SyncMatcherResult>. SyncMatcherResult has: pass (boolean, required), message (() => string, required), actual (unknown, optional), expected (unknown, optional), and meta (object, optional).

expect.extend TypeScript declaration

To add TypeScript support for custom matchers, extend the Matchers interface in an ambient declaration file (e.g., vitest.d.ts). Import vitest to ensure it's treated as an ES module. The Matchers interface is generic with R (assertion return type) and T (type of received value). Use R for synchronous matchers, which returns void for regular assertions and Promise<void> for .resolves, .rejects, expect.poll, or expect.element.

Custom matcher promise property

Inside a custom matcher function, this.promise contains the name of the modifier if the matcher was called on .resolves or .rejects, otherwise it is an empty string.

Custom matcher equals utility

Inside a custom matcher function, this.equals is a utility function for comparing two values. It returns true if values are equal, false otherwise. It supports objects with asymmetric matchers by default and is used internally for almost every matcher.

Custom matcher utils property

Inside a custom matcher function, this.utils contains a set of utility functions for displaying messages.

Custom matcher task property

Inside a custom matcher function, this.task (available since version 4.1.0) contains a reference to the Test runner task when available. When using the global expect with concurrent tests, this.task is undefined; use context.expect instead to ensure task is available in custom matchers.

toContainEqual matcher - array element structural matching

The toContainEqual matcher checks that an array contains an object with a particular structure. It works like toEqual but for individual items inside an array.

.not modifier for negating matchers

Any matcher can be negated by inserting .not before it. This verifies that something is not the case, for example: expect(1 + 2).not.toBe(0)

toBeNull matcher - matches only null

The toBeNull matcher matches only null and nothing else.

toBeUndefined matcher - matches only undefined

The toBeUndefined matcher matches only undefined and nothing else.

toBeDefined matcher - opposite of toBeUndefined

The toBeDefined matcher passes for anything that isn't undefined. It is the opposite of toBeUndefined.

toBeTruthy matcher - matches truthy values

The toBeTruthy matcher matches anything that an if statement would treat as true.

toBeFalsy matcher - matches falsy values

The toBeFalsy matcher matches anything that an if statement would treat as false.

toBeGreaterThanOrEqual matcher - greater than or equal comparison

The toBeGreaterThanOrEqual matcher checks if a number is greater than or equal to a given value.

toBeLessThanOrEqual matcher - less than or equal comparison

The toBeLessThanOrEqual matcher checks if a number is less than or equal to a given value.

toBe matcher - exact equality with Object.is

The toBe matcher checks that a value is exactly equal using Object.is comparison. It checks identity for objects (whether they're the exact same object in memory), not whether they have the same shape. Use toBe for primitives like numbers, strings, and booleans.

toEqual matcher - recursive deep comparison

The toEqual matcher recursively compares every field of an object or element of an array, ignoring object identity. Two objects with the same content are toEqual but not toBe. Use toEqual for comparing structure.

toStrictEqual matcher - stricter than toEqual

The toStrictEqual matcher is stricter than toEqual in three ways: it checks undefined properties, distinguishes sparse arrays from undefined values, and verifies that objects have the same type (not just the same shape).

toBeCloseTo matcher - floating point comparison

The toBeCloseTo matcher compares numbers within a small rounding error. Use this for floating point arithmetic because in JavaScript 0.1 + 0.2 doesn't equal 0.3 exactly (it equals 0.30000000000000004).

toMatch matcher - regex string matching

The toMatch matcher tests strings against regular expressions. It is useful when you care about a pattern rather than an exact value, like checking that an error message contains a certain word or that a URL matches a particular format.

toContain matcher - array/iterable membership

The toContain matcher checks that an array or any iterable like a Set includes a particular item. It uses === for comparison, so it works well for primitives.

toMatchObject matcher - partial object matching

The toMatchObject matcher verifies that an object contains at least the properties you specify, and ignores any additional ones. Use it when you want to check only a few important fields without specifying every property.

toHaveProperty matcher - object property checking

The toHaveProperty matcher checks individual properties, especially nested ones. You pass a dot-separated path and optionally an expected value. For example: expect(user).toHaveProperty('address.city', 'Paris')

expect.any(Constructor) asymmetric matcher

The expect.any(Constructor) asymmetric matcher matches any value created with the given constructor, such as Number, String, or Array. It works inside matchers that do deep comparison like toEqual or toMatchObject.

expect.stringContaining(str) asymmetric matcher

The expect.stringContaining(str) asymmetric matcher matches a string that includes the given substring. It works inside matchers that do deep comparison like toEqual or toMatchObject.

expect.stringMatching(regex) asymmetric matcher

The expect.stringMatching(regex) asymmetric matcher matches a string against a regular expression. It works inside matchers that do deep comparison like toEqual or toMatchObject.

expect.arrayContaining(arr) asymmetric matcher

The expect.arrayContaining(arr) asymmetric matcher matches an array that includes all items in the expected array. Order doesn't matter and extra items are allowed. It works inside matchers that do deep comparison like toEqual or toMatchObject.

expect.objectContaining(obj) asymmetric matcher

The expect.objectContaining(obj) asymmetric matcher matches an object that includes at least the specified properties. It works inside matchers that do deep comparison like toEqual or toMatchObject.

Give your agent this brain