rstest-best-practices
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseRstest Best Practices
Rstest 最佳实践
Apply these rules when writing or reviewing Rstest test projects.
编写或评审 Rstest 测试项目时,请遵循以下规则。
Configuration
配置
- Use and
rstest.config.tsfromdefineConfig@rstest/core - Prefer explicit imports over
import { test, expect, describe } from '@rstest/core'globals: true - For Rsbuild projects, use with
@rstest/adapter-rsbuildto reuse build configextends: withRsbuildConfig() - For Rslib projects, use with
@rstest/adapter-rslibto reuse build configextends: withRslibConfig() - Use for shared test setup (e.g., custom matchers, cleanup hooks)
setupFiles - When using Rsbuild plugins (e.g., ), add them via the
@rsbuild/plugin-reactfieldplugins - For deep-level or advanced build configuration needs, use or
tools.rspacktools.bundlerChain
- 使用 和
rstest.config.ts中的@rstest/coredefineConfig - 优先使用显式导入 ,而非
import { test, expect, describe } from '@rstest/core'globals: true - 对于 Rsbuild 项目,使用 并配置
@rstest/adapter-rsbuild以复用构建配置extends: withRsbuildConfig() - 对于 Rslib 项目,使用 并配置
@rstest/adapter-rslib以复用构建配置extends: withRslibConfig() - 使用 进行共享测试初始化(例如自定义匹配器、清理钩子)
setupFiles - 使用 Rsbuild 插件(如 )时,通过
@rsbuild/plugin-react字段添加plugins - 若需深层或高级构建配置,使用 或
tools.rspacktools.bundlerChain
CLI
CLI
- Use or
rstestto run tests (rstest rundisables watch mode, suitable for CI)run - Use or
rstest --watchfor local development with file watchingrstest watch - Use to list all test files and test names
rstest list - Use to update snapshots
rstest -u - Use when debugging test failures for detailed output
--reporter=verbose - Use (
--config) to specify a custom config file path-c
- 使用 或
rstest运行测试(rstest run会禁用监听模式,适合 CI 环境)run - 使用 或
rstest --watch进行本地开发,开启文件监听rstest watch - 使用 列出所有测试文件和测试名称
rstest list - 使用 更新快照
rstest -u - 调试测试失败时,使用 获取详细输出
--reporter=verbose - 使用 (缩写
--config)指定自定义配置文件路径-c
Test writing
测试编写
- Import test APIs from :
@rstest/core,test,describe,expect,beforeEach, etc.afterEach - Use or
testfor test cases; useitfor grouping related testsdescribe - Use to focus on specific tests during development, but never commit
.onlyto the codebase.only - Use or
.skipto mark incomplete or temporarily skipped tests.todo - Prefer small, focused test cases that test a single behavior
- Use for in-source testing of small utility functions (Rust-style
includeSource)import.meta.rstest - For in-source tests, wrap test code in and define
if (import.meta.rstest) { ... }asimport.meta.rstestin production build configfalse
- 从 导入测试 API:
@rstest/core、test、describe、expect、beforeEach等afterEach - 使用 或
test定义测试用例;使用it对相关测试进行分组describe - 开发期间可使用 聚焦特定测试,但切勿将
.only提交到代码库.only - 使用 或
.skip标记未完成或暂时跳过的测试.todo - 优先编写小型、聚焦的测试用例,每个用例仅测试单一行为
- 对小型工具函数使用 进行源码内测试(类似 Rust 的
includeSource)import.meta.rstest - 源码内测试需将测试代码包裹在 中,并在生产构建配置中将
if (import.meta.rstest) { ... }定义为import.meta.rstestfalse
Test environment
测试环境
- Use (default) for Node.js / server-side code
testEnvironment: 'node' - Use or
testEnvironment: 'jsdom'for DOM / browser API testingtestEnvironment: 'happy-dom' - Install or
jsdomas a dev dependency when using DOM environmentshappy-dom - Prefer for faster DOM testing; use
happy-domwhen better browser API compatibility is neededjsdom - For real browser testing, use with Playwright
@rstest/browser - Use inline project configs to run different test environments within one project (e.g., and
nodeprojects)jsdom
- 针对 Node.js/服务端代码,使用默认的
testEnvironment: 'node' - 针对 DOM/浏览器 API 测试,使用 或
testEnvironment: 'jsdom'testEnvironment: 'happy-dom' - 使用 DOM 环境时,需安装 或
jsdom作为开发依赖happy-dom - 优先使用 以提升 DOM 测试速度;若需更好的浏览器 API 兼容性,则使用
happy-domjsdom - 若需真实浏览器测试,使用 搭配 Playwright
@rstest/browser - 使用内联项目配置,可在一个项目中运行不同的测试环境(例如 和
node项目)jsdom
React / Vue testing
React / Vue 测试
- For React: use plugin and
@rsbuild/plugin-reactfor component testing@testing-library/react - For Vue: use plugin and
@rsbuild/plugin-vuefor component testing@testing-library/vue - Create a with
rstest.setup.tsandexpect.extend(jestDomMatchers)for Testing LibraryafterEach(() => cleanup()) - Add the setup file to in config
setupFiles - For SSR testing, use and test with
testEnvironment: 'node'or framework-specific SSR APIsreact-dom/server
- React 项目:使用 插件和
@rsbuild/plugin-react进行组件测试@testing-library/react - Vue 项目:使用 插件和
@rsbuild/plugin-vue进行组件测试@testing-library/vue - 创建 ,配置
rstest.setup.ts和expect.extend(jestDomMatchers)以适配 Testing LibraryafterEach(() => cleanup()) - 将该初始化文件添加到配置的 中
setupFiles - SSR 测试:使用 ,并通过
testEnvironment: 'node'或框架专属的 SSR API 进行测试react-dom/server
Mocking
Mocking
- Use to mock modules
rs.mock('./module') - Use to create mock functions
rs.fn() - Use to spy on methods
rs.spyOn(object, 'method') - Prefer ,
clearMocks, orresetMocksconfig options to automatically clean up mocks between testsrestoreMocks - Use factory functions in to provide mock implementations
rs.mock('./module', () => ({ ... }))
- 使用 模拟模块
rs.mock('./module') - 使用 创建模拟函数
rs.fn() - 使用 监听方法
rs.spyOn(object, 'method') - 优先使用 、
clearMocks或resetMocks配置选项,自动在测试间清理模拟restoreMocks - 在 中使用工厂函数提供模拟实现
rs.mock('./module', () => ({ ... }))
Snapshot testing
快照测试
- Use for general snapshot testing
toMatchSnapshot() - Use for small, readable inline snapshots
toMatchInlineSnapshot() - Use for large or structured outputs (e.g., HTML, generated code)
toMatchFileSnapshot() - Keep snapshots concise — only include relevant data, avoid timestamps and session IDs
- Use to mask paths or sensitive data in snapshots
expect.addSnapshotSerializer() - Use to normalize file paths across platforms
path-serializer - Review snapshot changes carefully in code review
- 使用 进行通用快照测试
toMatchSnapshot() - 使用 生成小型、易读的内联快照
toMatchInlineSnapshot() - 使用 处理大型或结构化输出(例如 HTML、生成的代码)
toMatchFileSnapshot() - 保持快照简洁——仅包含相关数据,避免时间戳和会话 ID
- 使用 屏蔽快照中的路径或敏感数据
expect.addSnapshotSerializer() - 使用 跨平台标准化文件路径
path-serializer - 代码评审时需仔细检查快照变更
Coverage
覆盖率
- Enable coverage with CLI flag or
--coveragein configcoverage.enabled: true - Install for the Istanbul coverage provider
@rstest/coverage-istanbul - Use to specify source files for coverage (e.g.,
coverage.include)['src/**/*.{js,ts,tsx}'] - Use to enforce minimum coverage requirements
coverage.thresholds - Use to generate reports in different formats (e.g.,
coverage.reporters,text,lcov)html
- 通过 CLI 标志或配置中
--coverage启用覆盖率统计coverage.enabled: true - 安装 以使用 Istanbul 覆盖率统计工具
@rstest/coverage-istanbul - 使用 指定需要统计覆盖率的源文件(例如
coverage.include)['src/**/*.{js,ts,tsx}'] - 使用 设置最低覆盖率要求
coverage.thresholds - 使用 生成不同格式的报告(例如
coverage.reporters、text、lcov)html
Multi-project testing
多项目测试
- Use field in root config to define multiple test projects
projects - For monorepos, use glob patterns like to auto-discover sub-projects
'packages/*' - Use helper in sub-project configs
defineProject - Extract shared config and use to compose project configs
mergeRstestConfig - Global options (,
reporters,pool,isolate,coverage) must be set at the root level, not in projectsbail
- 在根配置中使用 字段定义多个测试项目
projects - 对于单体仓库,使用通配符模式如 自动发现子项目
'packages/*' - 在子项目配置中使用 辅助函数
defineProject - 提取共享配置,使用 组合项目配置
mergeRstestConfig - 全局选项(、
reporters、pool、isolate、coverage)必须在根级别设置,不可在项目内设置bail
CI integration
CI 集成
- Use (not
rstest run) in CIrstest watch - Use for parallel test execution across CI machines (e.g.,
--shard)--shard 1/3 - Use with
--reporter=blobto combine sharded resultsrstest merge-reports - Use with
--reporter=junitfor CI report integrationoutputPath - The reporter is auto-enabled in GitHub Actions for inline error annotations
github-actions - Use to stop early on first failure when appropriate
--bail
- CI 环境中使用 (而非
rstest run)rstest watch - 使用 在多台 CI 机器上并行执行测试(例如
--shard)--shard 1/3 - 使用 搭配
--reporter=blob合并分片测试结果rstest merge-reports - 使用 并配置
--reporter=junit以集成 CI 报告outputPath - 在 GitHub Actions 中会自动启用 报告器,实现内联错误标注
github-actions - 必要时使用 在首次失败后提前终止测试
--bail
Performance
性能优化
- Disable (
isolate) when tests have no side effects for faster execution via module cache reuse--no-isolate - Use to control parallelism based on available resources
pool.maxWorkers - Keep test build fast by avoiding unnecessary Rspack plugins in test config
- Use test filtering (or
rstest <pattern>) to run only relevant tests during development-t <name> - Leverage watch mode's incremental re-runs for fast local feedback
- 若测试无副作用,禁用 (
isolate),通过复用模块缓存提升执行速度--no-isolate - 使用 根据可用资源控制并行度
pool.maxWorkers - 测试构建中避免不必要的 Rspack 插件,以加快构建速度
- 使用测试过滤(或
rstest <pattern>),开发期间仅运行相关测试-t <name> - 利用监听模式的增量重跑,获取快速的本地反馈
Debugging
调试
- Run with to enable debug mode, which writes final configs and build outputs to disk
DEBUG=rstest - Read generated files in to confirm final Rstest/Rsbuild/Rspack config
dist/.rstest-temp/.rsbuild/ - Use VS Code's JavaScript Debug Terminal to run with breakpoints
rstest - Use for detailed per-test output
--reporter=verbose - Use to trace console calls to their source
--printConsoleTrace - Add VS Code launch config for debugging specific test files with
@rstest/core/bin/rstest.js
- 运行时添加 启用调试模式,会将最终配置和构建输出写入磁盘
DEBUG=rstest - 查看 中的生成文件,确认最终的 Rstest/Rsbuild/Rspack 配置
dist/.rstest-temp/.rsbuild/ - 使用 VS Code 的 JavaScript Debug Terminal 运行 并设置断点
rstest - 使用 获取每个测试的详细输出
--reporter=verbose - 使用 追踪控制台调用的来源
--printConsoleTrace - 添加 VS Code 启动配置,通过 调试特定测试文件
@rstest/core/bin/rstest.js
Profiling
性能分析
- Use Rsdoctor with to analyze test build performance
RSDOCTOR=true rstest run - Use for native profiling of both main and worker processes
samply - Use Node.js for memory profiling
--heap-prof
- 使用 Rsdoctor,运行 分析测试构建性能
RSDOCTOR=true rstest run - 使用 对主进程和工作进程进行原生性能分析
samply - 使用 Node.js 的 进行内存分析
--heap-prof
Toolchain integration
工具链集成
- Use the official VS Code extension () for in-editor test running and debugging
rstack.rstest - For Rslib libraries, use for config reuse
@rstest/adapter-rslib - For Rsbuild apps, use for config reuse
@rstest/adapter-rsbuild - Use to detect test environment and apply test-specific config
process.env.RSTEST
- 使用官方 VS Code 扩展()在编辑器内运行和调试测试
rstack.rstest - 对于 Rslib 库,使用 复用配置
@rstest/adapter-rslib - 对于 Rsbuild 应用,使用 复用配置
@rstest/adapter-rsbuild - 使用 检测测试环境,应用测试专属配置
process.env.RSTEST
Documentation
文档
- For the latest Rstest docs, read https://rstest.rs/llms.txt
- 如需获取 Rstest 最新文档,请访问 https://rstest.rs/llms.txt