Expect
expect is used to assert values in tests. It provides a rich set of matchers, supports chainable modifiers, soft assertions, polling, and snapshot testing.
You can import the expect API from the @rstest/core package:
You can also get the expect API from the test context, which is helpful for tracing assertion belonging in concurrent tests.
expect
- Type:
<T>(actual: T, message?: string) => Assertion<T>
Creates an assertion object for the given value.
actual: The value under test.message: Optional custom message shown when the assertion fails.
expect.element (Browser Mode)
- Type:
(locator: Locator) => BrowserElementExpect
In Browser Mode, expect.element is used to assert against a Locator provided by @rstest/browser (for example, toBeVisible, toHaveText, toHaveValue).
expect.element is only available in Browser Mode and requires importing @rstest/browser to install the browser-side adapter. See Assertion (Browser Mode) for the complete reference.
expect.not
Negates the assertion.
expect.soft
- Type:
<T>(actual: T, message?: string) => Assertion<T>
Performs a soft assertion. The test will continue even if the assertion fails, and all failures will be reported at the end.
expect.poll
- Type:
<T>(actual: () => T | Promise<T>, options?: { interval?: number, timeout?: number, message?: string }) => PromiseLike<Assertion<Awaited<T>>>
Repeatedly calls actual and retries the matcher until it passes or times out.
- Default
interval:50(ms) - Default
timeout:1000(ms)
options:
interval: Time between retry attempts (in milliseconds).timeout: Maximum total polling time before failing (in milliseconds).message: Custom assertion message shown when the poll assertion fails.
Notes:
expect.poll(...)assertions are asynchronous and must be awaited.expect.poll(...)does not supportresolves/rejects,toThrow*, or snapshot matchers. Userstest.waitFor()for those unstable conditions.
expect.unreachable
- Type:
(message?: string) => never
Marks a code path as unreachable. Throws if called.
expect.assertions
- Type:
(expected: number) => void
Asserts that a certain number of assertions are called during a test, typically used to verify async code or expected exceptions.
expect.hasAssertions
- Type:
() => void
Asserts that at least one assertion is called during a test.
Useful for tests where assertion count can vary, but at least one assertion must run.
expect.addEqualityTesters
- Type:
(testers: Array<Tester>) => void
Adds custom equality testers for use in assertions.
Each tester can return:
true: values are considered equalfalse: values are considered not equalundefined: defer to the next tester/default equality
expect.addSnapshotSerializer
- Type:
(serializer: SnapshotSerializer) => void
Adds a custom serializer for snapshot testing.
expect.getState / expect.setState
- Type:
getState: () => MatcherStatesetState: (state: Partial<MatcherState>) => void
Gets or sets the internal matcher state.
Matchers
Common matchers
Common matchers are the primary tools for value, structure, and type assertions.
Equality and identity:
toBe(value): strict equality withObject.is.toEqual(value): deep equality for object/array shapes.toStrictEqual(value): stricter deep equality (includesundefinedkeys and sparse arrays).toBeOneOf(array): value must be one of the provided candidates.
Type and existence:
toBeTruthy()/toBeFalsy(): truthiness checks.toBeNull()/toBeUndefined()/toBeDefined(): null/undefined checks.toBeNaN():NaNcheck.toBeInstanceOf(class): instance check.toBeTypeOf(type): runtime type check (for example'string').
Numbers:
toBeGreaterThan(number)/toBeGreaterThanOrEqual(number).toBeLessThan(number)/toBeLessThanOrEqual(number).toBeCloseTo(number, numDigits?): floating-point tolerant comparison.
Collections and strings:
toContain(item): array/string contains a value or substring.toContainEqual(item): array contains an item by deep equality.toMatch(stringOrRegExp): string matches regex or substring.toMatchObject(object): object contains a subset of properties.toHaveLength(length): has expected.length.toHaveProperty(path, value?): has property at path, optionally with expected value.
Custom predicate and errors:
toSatisfy(fn): passes a user-defined predicate.toThrowError(expected?): function throws an error (string/regex/error type supported).
Mock matchers
Mock matchers verify interactions with rstest.fn / rstest.spyOn: calls, call order, return values, and async outcomes.
Call assertions:
toHaveBeenCalled(): called at least once.toHaveBeenCalledTimes(times): called exact number of times.toHaveBeenCalledWith(...args): called with specified args (any call).toHaveBeenLastCalledWith(...args): last call args match.toHaveBeenNthCalledWith(n, ...args): nth call args match.toHaveBeenCalledExactlyOnceWith(...args): called exactly once with args.toHaveBeenCalledBefore(mock)/toHaveBeenCalledAfter(mock): relative call order.
Return assertions:
toHaveReturned(): returned at least once.toHaveReturnedTimes(times): returned exact number of times.toHaveReturnedWith(value): returned specific value in any call.toHaveLastReturnedWith(value): last return value matches.toHaveNthReturnedWith(n, value): nth return value matches.
Promise resolution assertions:
toHaveResolved(): resolved at least once.toHaveResolvedTimes(times): resolved exact number of times.toHaveResolvedWith(value): resolved to value in any call.toHaveLastResolvedWith(value): last resolved value matches.toHaveNthResolvedWith(n, value): nth resolved value matches.
Notes:
Nthmatchers are 1-based (1= first call).toHaveBeenCalledWithchecks any call; useLastorNthvariants for strict position checks.- These matchers require a mock/spied function, not a plain function.
Snapshot matchers
Snapshot matchers are used to compare values, errors, or files against previously recorded snapshots, making it easy to track changes in output over time.
toMatchSnapshot(). Compares the value to a saved snapshot.toMatchInlineSnapshot(). Compares the value to an inline snapshot in the test file.toThrowErrorMatchingSnapshot(). Checks if a thrown error matches a saved snapshot.toThrowErrorMatchingInlineSnapshot(). Checks if a thrown error matches an inline snapshot in the test file.toMatchFileSnapshot(filepath). Compares the value to a snapshot saved in a specific file.
Promise matchers
resolves. Asserts on the resolved value of a Promise.rejects. Asserts on the rejected value of a Promise.
Asymmetric matchers
Asymmetric matchers are helpers that allow for flexible matching of values, such as partial matches, type matches, or pattern matches. They are useful for writing more expressive and less brittle tests.
expect.anything(). Matches any value except null or undefined.expect.any(constructor). Matches any value of the given type.expect.closeTo(number, precision?). Matches a number close to the expected value.expect.arrayContaining(array). Matches an array containing the expected elements.expect.objectContaining(object). Matches an object containing the expected properties.expect.stringContaining(string). Matches a string containing the expected substring.expect.stringMatching(stringOrRegExp). Matches a string matching the expected pattern.
Custom matchers
You can extend expect with custom matchers:
If you want to add TypeScript typings for your custom matchers, you can extend the Assertion interface in the @rstest/core module: