# Rstest > Rstest is a testing framework powered by Rspack. It delivers comprehensive, first-class support for the Rspack ecosystem, enabling seamless integration into existing Rspack-based projects. ## Guide - [Debugging](/guide/advanced/debugging.md) - [Profiling](/guide/advanced/profiling.md) - [CLI](/guide/basic/cli.md): Rstest comes with a lightweight CLI that includes commands such as rstest watch and rstest run. - [Configure Rstest](/guide/basic/configure-rstest.md) - [Test projects](/guide/basic/projects.md): Rstest supports running multiple test projects simultaneously within a single Rstest process. These projects can have different test configurations and test environments. - [Reporters](/guide/basic/reporters.md): Reporters in Rstest control how test results are displayed and processed. You can use built-in reporters to get different output formats or create custom reporters to integrate with your workflow. - [Snapshot testing](/guide/basic/snapshot.md): Snapshot Testing is a powerful testing method used to capture and compare serialized representations of component output. When your UI or data structures change, snapshot testing helps you detect these changes promptly. - [Filtering tests](/guide/basic/test-filter.md): Rstest provides a variety of flexible ways to filter and select which test files and test cases to run. You can precisely control the test scope via configuration files, command-line arguments, and test APIs. - [Upgrade Rstest](/guide/basic/upgrade-rstest.md): This section explains how to upgrade the project's Rstest dependencies to the latest version. :::info Rstest is still in 0.x version stage, and the API may change frequently. We recommend upgrading to the latest version to access new features and bug fixes. ::: - [VS Code extension](/guide/basic/vscode-extension.md): The Rstest VS Code extension keeps your project’s tests in sync inside the editor so you can browse, run, and debug them in VS Code. Demo of running Rstest tests inside the VS Code extension - [Framework guides](/guide/browser-testing/framework-guides.md): This guide provides testing configuration examples for various frontend frameworks in Browser Mode. :::tip Prerequisites Before continuing, make sure you've completed the basic Browser Mode setup. You can initialize using either method: Automatic initialization: Run npx rstest init browserManual configuration: Follow the Getting Started guide Then follow this guide for framework-specific configuration. ::: :::info Framework Support Currently, Browser Mode only provides out-of-the-box support for React. Other frameworks (Vue, Svelte, etc.) will be supported in the future. ::: - [Getting started](/guide/browser-testing/getting-started.md): This guide will help you configure and run Browser Mode tests in your project. - [Browser mode (experimental)](/guide/browser-testing/index.md): Rstest provides Browser Mode, allowing you to run tests in a real browser instead of simulated environments like jsdom or happy-dom. - [User interactions](/guide/browser-testing/user-interactions.md): This guide covers how to simulate user interactions in Browser Mode tests, and helps you choose between stability, maintainability, and control granularity. In Browser Mode, choose your interaction approach in the following priority order (only fall back when needed): Locator API (preferred): Use page.getBy* + expect.element for semantic queries, interactions, and assertions, suitable for the vast majority of interaction testsTesting Library: Best for migrating existing tests or reusing an established Testing Library toolchain; generally not the first choice for new testsNative DOM API (fallback): Lighter and allows precise control over event properties, but requires manual event sequencing — ideal for verifying low-level event logic or special interaction details - [React](/guide/framework/react.md): This guide covers how to test React applications and components with Rstest. Rstest supports testing React in multiple scenarios: Node (with happy-dom or jsdom): Fast, lightweight tests running in Node.js with a simulated DOMSSR (Server-Side Rendering): Test server render functions in pure Node.js environmentBrowser Mode: Real browser testing with Playwright for accurate DOM behavior - [Vue](/guide/framework/vue.md): This guide covers how to test Vue applications and components with Rstest. Rstest supports testing Vue in multiple scenarios: Node (with happy-dom or jsdom): Fast, lightweight tests running in Node.js with a simulated DOMBrowser Mode: Real browser testing with Playwright for accurate DOM behavior - [Adapters](/guide/integration/adapters.md): Adapters are a powerful feature that allows you to convert configurations from other tools (such as build tools or CLIs) into a format that Rstest supports. By creating a custom adapter, you can reuse existing configurations, avoid redundant definitions across multiple tools, and ensure project consistency. This guide will walk you through the process of creating and using custom Rstest adapters. - [Rsbuild](/guide/integration/rsbuild.md): This guide covers how to integrate Rstest with Rsbuild for seamless testing in your Rsbuild projects. - [Rslib](/guide/integration/rslib.md): This guide covers how to integrate Rstest with Rslib for seamless testing in your Rslib projects. - [Migrating from Jest](/guide/migration/jest.md): Rstest is designed to be Jest-compatible, making migration from Jest projects straightforward. Here's how to migrate your Jest project to Rstest: - [Migrating from Vitest](/guide/migration/vitest.md): If you are using the Rstack toolchain (Rsbuild / Rslib / Rspack, etc.), migrating to Rstest gives you a more consistent development experience. - [Features](/guide/start/features.md): Here you can learn about the key features supported by Rstest. - [Introduction](/guide/start/index.md): Rstest is a testing framework powered by Rspack. It delivers comprehensive, first-class support for the Rspack ecosystem, enabling seamless integration into existing Rspack-based projects. Rstest offers full Jest-compatible APIs while providing native, out-of-the-box support for TypeScript, ESM, and more, ensuring a modern and efficient testing experience. - [Quick start](/guide/start/quick-start.md) ## Config - [dev](/config/build/dev.md): Options for local development. - [output](/config/build/output.md) - [plugins](/config/build/plugins.md): plugins is used to register Rsbuild plugins. Rstest and Rsbuild share the same plugin system, so you can use Rsbuild plugins in Rstest. - [resolve](/config/build/resolve.md): Options for module resolution. - [source](/config/build/source.md): Options for input source code. - [tools](/config/build/tools.md): Options for low-level tools. - [Config overview](/config/index.md) - [bail](/config/test/bail.md): Type: numberDefault: 0CLI: --bail [number] (default: 1) Abort the test run after the specified number of test failures. This is useful for stopping test runs early when failures occur. Setting this to 0 (the default) means to run all tests regardless of failures. Setting this to 1 will stop the test run after the first test failure. export default defineConfig({ bail: 1, }); - [browser (experimental)](/config/test/browser.md): Type: Default: Browser Mode configuration. When enabled, tests run in a real browser instead of the Node.js environment. - [chaiConfig](/config/test/chai-config.md): Type: Default: undefined Customize the Chai config. truncateThreshold Sets the number of characters to display when showing large values in assertions. When an assertion fails and displays objects or arrays, Chai will truncate the output if it exceeds this threshold to keep error messages readable. Default: 40 A higher value shows more details in assertion failures, useful for debugging complex data structures: With the default value (40), long arrays or objects get truncated: If you set a higher threshold, you see the full structure: This allows you to see the exact values that don't match, making debugging easier. showDiff Show a diff of expected vs actual values in assertion failures. Default: true Disable this if you want to see plain assertion messages without diffs: By default, Rstest shows a diff of expected vs actual values in assertion failures: If you set showDiff: false, Rstest will show plain assertion messages without diffs: - [clearMocks](/config/test/clear-mocks.md): Type: booleanDefault: falseCLI: --clearMocks Automatically clear mock calls, instances, contexts and results before every test. When clearMocks enabled, rstest will call .clearAllMocks() before each test. export default defineConfig({ clearMocks: true, }); - [coverage](/config/test/coverage.md): Type: Default: undefinedVersion: >=0.4.0 Collect code coverage and generate coverage reports. - [disableConsoleIntercept](/config/test/disable-console-intercept.md): Type: booleanDefault: falseCLI: --disableConsoleIntercept Disable interception of console logs. By default, Rstest intercepts the console log, which will help track log sources. If you don't want Rstest to intercept console logs, you can set this configuration to true. export default defineConfig({ disableConsoleIntercept: true, }); - [env](/config/test/env.md): Type: PartialDefault: undefined Custom environment variables available on process.env during tests. After setting the above configuration, you can access the PRINT_LOGGER variable in your tests: - [exclude](/config/test/exclude.md): Type: string[] | { patterns: string[]; override?: boolean }Default: ['**/node_modules/**', '**/dist/**', '**/.{idea,git,cache,output,temp}/**']CLI: --exclude "**/node_modules/**" A list of glob patterns that should be excluded from your test files. - [extends](/config/test/extends.md): Type: ExtendConfig | ExtendConfigFnDefault: undefined The extends option allows you to extend your Rstest configuration from external sources, such as adapters that convert other build tools' configurations to Rstest-compatible format. This enables: Adapter Integration: Extend from adapters like @rstest/adapter-rslibAsync Configuration: Load configuration from external sources asynchronouslyConfig Merging: Automatically merge extended configuration with your local Rstest config - [globalSetup](/config/test/global-setup.md): Type: string | string[]Default: undefined The globalSetup option in Rstest allows you to run setup and teardown code that executes once before all tests and after all tests complete. This is useful for: Starting and stopping databasesInitializing test servicesCleaning up resources after test runs - [globals](/config/test/globals.md): Type: booleanDefault: falseCLI: --globals Provide global Rstest APIs for test files, such as expect, test, describe, etc. By default, Rstest does not provide global APIs. If you prefer to use the APIs globally like Jest, you can add globals: true in the config or pass the --globals option to CLI. export default defineConfig({ globals: true, }); - [hideSkippedTestFiles](/config/test/hide-skipped-test-files.md): Type: booleanDefault: falseCLI: --hideSkippedTestFiles Hide logs for skipped test files to reduce noise in the test output, especially when running tests with filters. export default defineConfig({ hideSkippedTestFiles: true, }); When you set hideSkippedTestFiles to true, Rstest will hide logs for all skipped test files after the test run is complete. The output will look like this: - [hideSkippedTests](/config/test/hide-skipped-tests.md): Type: booleanDefault: falseCLI: --hideSkippedTests Hide logs for skipped test cases to reduce noise in the test output, especially when running tests with filters. When you use the default reporter and run multiple test files, skipped tests from other files are already hidden by the reporter's display logic, even when hideSkippedTests remains at its default value of false. export default defineConfig({ hideSkippedTests: true, }); When you set hideSkippedTests to true, Rstest will hide logs for all skipped test cases after the test run is complete. The output will look like this: - [hookTimeout](/config/test/hook-timeout.md): Type: numberDefault: 10_000CLI: --hookTimeout=10000 Default timeout of hook in milliseconds. 0 will disable the timeout. export default defineConfig({ hookTimeout: 10000, }); - [includeSource](/config/test/include-source.md): Type: string[]Default: [] In-source testing is where the test code lives within the same file as the source code, similar to Rust's module tests. You can define a list of glob patterns that match your in-source test files via includeSource configuration. :::tip In-source testing is usually suitable for small functional functions and utilities, allowing for easy and rapid verification and debugging. For more complex functions and modules, independent test files are recommended. ::: Writing in-source tests When includeSource defined, Rstest will run all matched files with import.meta.rstest inside. You can get the Rstest test API via import.meta.rstest. For production Put the test code inside the if (import.meta.rstest) block, and define import.meta.rstest as false in your build configuration (e.g., rsbuild.config.ts), which will help the bundler eliminate dead code. TypeScript To get TypeScript support for import.meta.rstest, you can create a src/rstestEnv.d.ts file to reference: - [includeTaskLocation](/config/test/include-task-location.md): Type: booleanDefault: falseCLI: --includeTaskLocation Whether to include the location information of tests when collecting test information. When enabled, this configuration adds line and column number information to test cases and suites. This is useful for debugging and when reporters need to collect test information. Note that enabling this configuration may slightly decrease test execution performance. export default defineConfig({ includeTaskLocation: true, }); This will automatically enable includeTaskLocation and display the location information for each test case. - [include](/config/test/include.md): Type: string[]Default: ['**/*.{test,spec}.?(c|m)[jt]s?(x)']CLI: --include '**/*.test.ts' --include '**/*.spec.ts' A list of glob patterns that match your test files. These patterns will be resolved relative to the root (process.cwd() by default). export default defineConfig({ include: ['**/*.{test,spec}.?(c|m)[jt]s?(x)'], }); - [isolate](/config/test/isolate.md): Type: booleanDefault: trueCLI: --isolate, --isolate=false, --no-isolate Run tests in an isolated environment. By default, Rstest runs each test in an isolated environment, which avoids the impact of some module side effects and helps improve the stability of the test. If your code has no side effects, turning off this option will help improve performance because module caches can be reused between different test files. export default defineConfig({ isolate: false, }); - [logHeapUsage](/config/test/log-heap-usage.md): Type: booleanDefault: falseCLI: --logHeapUsage Log heap usage for each test, it can help to find memory leaks in tests. export default defineConfig({ logHeapUsage: true, }); - [maxConcurrency](/config/test/max-concurrency.md): Type: numberDefault: 5CLI: --maxConcurrency=10 A number limiting the number of test cases that are allowed to run at the same time when using test.concurrent or wrapped in describe.concurrent. Any test above this limit will be queued and executed once a slot is released. export default defineConfig({ maxConcurrency: 10, }); - [name](/config/test/name.md): Type: stringDefault: rstest The name of the test project. When you define multiple test projects via projects, it's recommended to give each project a unique name so that you can filter specific projects using the --project option. If a project's name is not provided, Rstest will use the name field from the current project's package.json. If it does not exist, the folder name will be used instead. - [onConsoleLog](/config/test/on-console-log.md): Type: (content: string) => boolean | voidDefault: undefined Custom handler for console log in tests, which is helpful for filtering out logs from third-party libraries. If you return false, Rstest will not print the log to the console. :::note When disableConsoleIntercept is set to true, onConsoleLog will not take effect. ::: - [passWithNoTests](/config/test/pass-with-no-tests.md): Type: booleanDefault: falseCLI: --passWithNoTests Pass when no tests are found. By default, Rstest marks test failures when no test suites are found. You can allow the test to pass when no tests are found by setting passWithNoTests to true. export default defineConfig({ passWithNoTests: true, }); - [pool](/config/test/pool.md): Type: Default: Options of pool used to run tests in. - [printConsoleTrace](/config/test/print-console-trace.md): Type: booleanDefault: falseCLI: --printConsoleTrace Print console traces when calling any console method, which is helpful for debugging. export default defineConfig({ printConsoleTrace: true, }); - [projects](/config/test/projects.md): Type: Default: [] Define multiple test projects. It can be an array of directories, configuration files, or glob patterns, or an object. Rstest will run the tests for each project according to the configuration defined in each project, and the test results from all projects will be combined and displayed. More information about projects can be found in Test projects. - [reporters](/config/test/reporters.md): Type: Reporter options reference: Reporter option types are defined in packages/core/src/types/reporter.tsDefault: CLI: --reporter= --reporter= Configure which reporters to use for test result output. :::info AI agent environments If you haven't explicitly configured any reporters (no reporters in config and no --reporter flags), Rstest defaults to ['md'] and outputs AI agent-friendly markdown to stdout. ::: Usage Basic example You can specify reporters in the rstest.config.ts file or via the CLI. Multiple reporters You can use multiple reporters to output test results in different formats simultaneously. This is useful when you want both console output and a file report for CI/CD pipelines. Configuring reporters with options Many reporters support configuration options. Pass them as a tuple [reporterName, options]: Using custom reporters You can create and use custom reporters by providing a reporter class or object that implements the reporter interface: Related documentation Reporters guide - Usage examples and built-in reporter detailsReporter API reference - Custom reporter implementation - [resetMocks](/config/test/reset-mocks.md): Type: booleanDefault: falseCLI: --resetMocks Automatically reset mock state before every test. When resetMocks enabled, rstest will call .resetAllMocks() before each test. export default defineConfig({ resetMocks: true, }); - [resolveSnapshotPath](/config/test/resolve-snapshot-path.md): Type: (testPath: string, snapExtension: string) => stringDefault: undefined Custom handler for resolving snapshot paths in tests. By default, Rstest saves snapshot files in the same directory as the test files, under a __snapshots__ folder. You can use resolveSnapshotPath to customize this behavior and specify a different location for your snapshot files. For example, store snapshots next to test files: - [restoreMocks](/config/test/restore-mocks.md): Type: booleanDefault: falseCLI: --restoreMocks Automatically reset mock state before every test. When restoreMocks enabled, rstest will call .restoreAllMocks() before each test. export default defineConfig({ restoreMocks: true, }); - [retry](/config/test/retry.md): Type: numberDefault: 0CLI: --retry Retry the test specific number of times if it fails. This is useful for some flaky or non-deterministic test failures. - [root](/config/test/root.md): Type: stringDefault: process.cwd()CLI: -r=, --root= Specify the project root directory. Can be an absolute path, or a path relative to process.cwd(). root determines the starting point for loading configuration files, searching test files, etc. Using in any path-based configuration settings will reference this value. - [setupFiles](/config/test/setup-files.md): Type: string[]Default: [] A list of paths to modules that run some code to configure or set up the testing environment, they will be run before each test file. - [shard](/config/test/shard.md): Type: { count: number; index: number }Default: undefinedCLI: --shard / Shards test files for parallel execution. count represents the total number of shards, and index represents the index of the current shard (1-based). This option can only be set at the root level of your configuration, not within individual projects. This is particularly useful for parallelizing tests in CI/CD environments, allowing you to split the test suite into multiple parts and run them independently across different jobs, thereby reducing overall test time. :::warning Important Notes When using the --shard option, ensure that the count and index values are valid.Test files will be sorted by their path to ensure consistent sharding across different runs.Sharding occurs during the test file scanning phase, prior to the build process, to optimize performance. ::: export default defineConfig({ shard: { count: 3, index: 1, }, }); - [slowTestThreshold](/config/test/slow-test-threshold.md): Type: numberDefault: 300CLI: --slowTestThreshold=300 The number of milliseconds after which a test or suite is considered slow and reported as such in the results. export default defineConfig({ slowTestThreshold: 300, }); - [snapshotFormat](/config/test/snapshot-format.md): Type: PrettyFormatOptionsDefault: undefined Customize the snapshot format using options from the pretty-format. - [testEnvironment](/config/test/test-environment.md): Type: 'node' | 'jsdom' | 'happy-dom' | { name: EnvironmentName, options?: EnvironmentOptions }Default: 'node'CLI: --testEnvironment=node The environment that will be used for testing. The default environment in Rstest is a Node.js environment. If you are building a web application, you can use a browser-like environment through jsdom or happy-dom instead. export default defineConfig({ testEnvironment: 'jsdom', }); You also need to install the corresponding package: For jsdom For happy-dom After enabling DOM testing, you can write tests that use browser APIs like document and window. Environment options You can also pass options to the test environment. This is useful for configuring jsdom or happy-dom. For example, you can set the url for jsdom: The options object is passed directly to the environment's constructor. For jsdom, it's passed to the JSDOM constructor. You can find available options in the jsdom documentation.For happy-dom, it's passed to the Window constructor. You can find available options in the happy-dom documentation. Examples Rstest + nodeRstest + jsdom + react - [testNamePattern](/config/test/test-name-pattern.md): Type: string | RegExpDefault: undefinedCLI: -t=, --testNamePattern= Run only tests with a name that matches the regex / string. If you set testNamePattern to bar, tests not containing the word bar in the test name will be skipped. It should be noted that the test name consists of the test case name and the name of the test suite that wraps it. If a test suite name contains bar, all test cases in that test suite will be run. export default defineConfig({ testNamePattern: 'bar', }); If you want to exclude certain tests instead, you can use a negative regex. For example, /^(?!.*bar).*$/ skips every test whose name contains bar. - [testTimeout](/config/test/test-timeout.md): Type: numberDefault: 5_000CLI: --testTimeout=5000 Default timeout of a test in milliseconds. 0 will disable the timeout. export default defineConfig({ testTimeout: 5000, }); - [unstubEnvs](/config/test/unstub-envs.md): Type: booleanDefault: falseCLI: --unstubEnvs Restores all process.env values that were changed with rstest.stubEnv before every test. export default defineConfig({ unstubEnvs: true, }); - [unstubGlobals](/config/test/unstub-globals.md): Type: booleanDefault: falseCLI: --unstubGlobals Restores all global variables that were changed with rstest.stubGlobal before every test. export default defineConfig({ unstubGlobals: true, }); - [update](/config/test/update.md): Type: booleanDefault: falseCLI: -u, --update Update snapshot. When update is enabled, Rstest will update all changed snapshots and delete obsolete ones. It should be noted that when you test in local, the newly added snapshot will be automatically updated regardless of whether the update configuration is enabled. export default defineConfig({ update: true, }); ## API - [Assertion](/api/runtime-api/browser-mode/assertion.md): expect.element is the API for Locator assertions in Browser Mode. It accepts a Locator and returns a chainable assertion object. Unlike expect(value) which primarily compares JS values, expect.element targets the real element state on the page, suitable for verifying visibility, text, form values, count, and other user-observable results. :::tip Auto-retry With the Playwright provider, all expect.element matchers automatically retry until the assertion passes or the timeout is reached. You do not need to write manual waitFor or polling logic — just assert the expected state and the framework handles the waiting. ::: When you import @rstest/browser in a Browser Mode test (e.g., importing page), expect automatically gains the element capability. This allows queries, interactions, and assertions to be organized around the same Locator, focusing failure messages on element state. The following minimal example demonstrates common usage: first assert visibility, then verify a checked state change, and finally validate an element attribute. - [Browser mode](/api/runtime-api/browser-mode/index.md): The Browser Mode API is provided by @rstest/browser, designed to let you use a Playwright-style Locator workflow in browser tests. - [Locator](/api/runtime-api/browser-mode/locator.md): Locator is the core API for element querying and interaction in Browser Mode. You can build query chains via page.getBy* or page.locator(), then execute interaction actions. Concrete execution semantics are provided by the configured browser provider. :::tip Auto-wait With the Playwright provider, Locator interaction methods (such as click, fill, check) automatically wait for the element to become actionable (visible, enabled, stable) before executing. You do not need to manually wait for elements before performing actions. This is distinct from the auto-retry behavior of expect.element assertions. ::: The following example demonstrates the typical workflow: query elements, perform interactions, and combine with expect.element for assertions. - [Runtime API Overview](/api/runtime-api/index.md) - [Fake timers](/api/runtime-api/rstest/fake-timers.md): The fake timers may be useful when a piece of code sets a long timeout that we don't want to wait for in a test. Rstest provides some utility functions to help you fake timers powered by @sinonjs/fake-timers. - [Rstest Utility](/api/runtime-api/rstest/index.md): Rstest provides utility functions to help you out through its rstest helper. You can import it from @rstest/core directly, and you can also use its alias rs. Or, you can access it globally like jest (when globals configuration is enabled). - [Mock functions](/api/runtime-api/rstest/mock-functions.md): Rstest provides some utility functions to help you mock functions powered by tinyspy. - [Mock instance](/api/runtime-api/rstest/mock-instance.md): MockInstance is the type of all mock/spy instances, providing a rich set of APIs for controlling and inspecting mocks. - [Mock modules](/api/runtime-api/rstest/mock-modules.md): Rstest supports mocking modules, which allows you to replace the implementation of modules in tests. Rstest provides utility functions in rs (rstest) for mocking modules. You can directly use the following methods to mock modules: - [Utilities](/api/runtime-api/rstest/utilities.md): A set of useful utility functions. - [Describe](/api/runtime-api/test-api/describe.md): describe defines a test suite. It supports chainable modifiers and parameterized methods for flexible and organized test grouping. - [Expect](/api/runtime-api/test-api/expect.md): 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. - [Hooks](/api/runtime-api/test-api/hooks.md): Hooks allow you to run setup and teardown logic before or after your tests or test suites. - [Test](/api/runtime-api/test-api/test.md): test defines a test case. It supports chainable modifiers and fixture extension for flexible and powerful test definitions. Alias: it. ## Others - [Reporter](/api/javascript-api/reporter.md): The Reporter API allows you to create custom test result processors and output formatters. This interface is experimental and may change in future versions. Note: For usage examples and configuration guidance, see the Reporters guide. - [Rstest core](/api/javascript-api/rstest-core.md): Rstest offers these core methods.