rstest-best-practices

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Rstest Best Practices

Rstest 最佳实践

Apply these rules when writing or reviewing Rstest test projects.
编写或评审 Rstest 测试项目时,请遵循以下规则。

Configuration

配置

  • Use
    rstest.config.ts
    and
    defineConfig
    from
    @rstest/core
  • Prefer explicit imports
    import { test, expect, describe } from '@rstest/core'
    over
    globals: true
  • For Rsbuild projects, use
    @rstest/adapter-rsbuild
    with
    extends: withRsbuildConfig()
    to reuse build config
  • For Rslib projects, use
    @rstest/adapter-rslib
    with
    extends: withRslibConfig()
    to reuse build config
  • Use
    setupFiles
    for shared test setup (e.g., custom matchers, cleanup hooks)
  • When using Rsbuild plugins (e.g.,
    @rsbuild/plugin-react
    ), add them via the
    plugins
    field
  • For deep-level or advanced build configuration needs, use
    tools.rspack
    or
    tools.bundlerChain
  • 使用
    rstest.config.ts
    @rstest/core
    中的
    defineConfig
  • 优先使用显式导入
    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.rspack
    tools.bundlerChain

CLI

CLI

  • Use
    rstest
    or
    rstest run
    to run tests (
    run
    disables watch mode, suitable for CI)
  • Use
    rstest --watch
    or
    rstest watch
    for local development with file watching
  • Use
    rstest list
    to list all test files and test names
  • Use
    rstest -u
    to update snapshots
  • Use
    --reporter=verbose
    when debugging test failures for detailed output
  • Use
    --config
    (
    -c
    ) to specify a custom config file path
  • 使用
    rstest
    rstest run
    运行测试(
    run
    会禁用监听模式,适合 CI 环境)
  • 使用
    rstest --watch
    rstest watch
    进行本地开发,开启文件监听
  • 使用
    rstest list
    列出所有测试文件和测试名称
  • 使用
    rstest -u
    更新快照
  • 调试测试失败时,使用
    --reporter=verbose
    获取详细输出
  • 使用
    --config
    (缩写
    -c
    )指定自定义配置文件路径

Test writing

测试编写

  • Import test APIs from
    @rstest/core
    :
    test
    ,
    describe
    ,
    expect
    ,
    beforeEach
    ,
    afterEach
    , etc.
  • Use
    test
    or
    it
    for test cases; use
    describe
    for grouping related tests
  • Use
    .only
    to focus on specific tests during development, but never commit
    .only
    to the codebase
  • Use
    .skip
    or
    .todo
    to mark incomplete or temporarily skipped tests
  • Prefer small, focused test cases that test a single behavior
  • Use
    includeSource
    for in-source testing of small utility functions (Rust-style
    import.meta.rstest
    )
  • For in-source tests, wrap test code in
    if (import.meta.rstest) { ... }
    and define
    import.meta.rstest
    as
    false
    in production build config
  • @rstest/core
    导入测试 API:
    test
    describe
    expect
    beforeEach
    afterEach
  • 使用
    test
    it
    定义测试用例;使用
    describe
    对相关测试进行分组
  • 开发期间可使用
    .only
    聚焦特定测试,但切勿将
    .only
    提交到代码库
  • 使用
    .skip
    .todo
    标记未完成或暂时跳过的测试
  • 优先编写小型、聚焦的测试用例,每个用例仅测试单一行为
  • 对小型工具函数使用
    includeSource
    进行源码内测试(类似 Rust 的
    import.meta.rstest
  • 源码内测试需将测试代码包裹在
    if (import.meta.rstest) { ... }
    中,并在生产构建配置中将
    import.meta.rstest
    定义为
    false

Test environment

测试环境

  • Use
    testEnvironment: 'node'
    (default) for Node.js / server-side code
  • Use
    testEnvironment: 'jsdom'
    or
    testEnvironment: 'happy-dom'
    for DOM / browser API testing
  • Install
    jsdom
    or
    happy-dom
    as a dev dependency when using DOM environments
  • Prefer
    happy-dom
    for faster DOM testing; use
    jsdom
    when better browser API compatibility is needed
  • For real browser testing, use
    @rstest/browser
    with Playwright
  • Use inline project configs to run different test environments within one project (e.g.,
    node
    and
    jsdom
    projects)
  • 针对 Node.js/服务端代码,使用默认的
    testEnvironment: 'node'
  • 针对 DOM/浏览器 API 测试,使用
    testEnvironment: 'jsdom'
    testEnvironment: 'happy-dom'
  • 使用 DOM 环境时,需安装
    jsdom
    happy-dom
    作为开发依赖
  • 优先使用
    happy-dom
    以提升 DOM 测试速度;若需更好的浏览器 API 兼容性,则使用
    jsdom
  • 若需真实浏览器测试,使用
    @rstest/browser
    搭配 Playwright
  • 使用内联项目配置,可在一个项目中运行不同的测试环境(例如
    node
    jsdom
    项目)

React / Vue testing

React / Vue 测试

  • For React: use
    @rsbuild/plugin-react
    plugin and
    @testing-library/react
    for component testing
  • For Vue: use
    @rsbuild/plugin-vue
    plugin and
    @testing-library/vue
    for component testing
  • Create a
    rstest.setup.ts
    with
    expect.extend(jestDomMatchers)
    and
    afterEach(() => cleanup())
    for Testing Library
  • Add the setup file to
    setupFiles
    in config
  • For SSR testing, use
    testEnvironment: 'node'
    and test with
    react-dom/server
    or framework-specific SSR APIs
  • React 项目:使用
    @rsbuild/plugin-react
    插件和
    @testing-library/react
    进行组件测试
  • Vue 项目:使用
    @rsbuild/plugin-vue
    插件和
    @testing-library/vue
    进行组件测试
  • 创建
    rstest.setup.ts
    ,配置
    expect.extend(jestDomMatchers)
    afterEach(() => cleanup())
    以适配 Testing Library
  • 将该初始化文件添加到配置的
    setupFiles
  • SSR 测试:使用
    testEnvironment: 'node'
    ,并通过
    react-dom/server
    或框架专属的 SSR API 进行测试

Mocking

Mocking

  • Use
    rs.mock('./module')
    to mock modules
  • Use
    rs.fn()
    to create mock functions
  • Use
    rs.spyOn(object, 'method')
    to spy on methods
  • Prefer
    clearMocks
    ,
    resetMocks
    , or
    restoreMocks
    config options to automatically clean up mocks between tests
  • Use factory functions in
    rs.mock('./module', () => ({ ... }))
    to provide mock implementations
  • 使用
    rs.mock('./module')
    模拟模块
  • 使用
    rs.fn()
    创建模拟函数
  • 使用
    rs.spyOn(object, 'method')
    监听方法
  • 优先使用
    clearMocks
    resetMocks
    restoreMocks
    配置选项,自动在测试间清理模拟
  • rs.mock('./module', () => ({ ... }))
    中使用工厂函数提供模拟实现

Snapshot testing

快照测试

  • Use
    toMatchSnapshot()
    for general snapshot testing
  • Use
    toMatchInlineSnapshot()
    for small, readable inline snapshots
  • Use
    toMatchFileSnapshot()
    for large or structured outputs (e.g., HTML, generated code)
  • Keep snapshots concise — only include relevant data, avoid timestamps and session IDs
  • Use
    expect.addSnapshotSerializer()
    to mask paths or sensitive data in snapshots
  • Use
    path-serializer
    to normalize file paths across platforms
  • Review snapshot changes carefully in code review
  • 使用
    toMatchSnapshot()
    进行通用快照测试
  • 使用
    toMatchInlineSnapshot()
    生成小型、易读的内联快照
  • 使用
    toMatchFileSnapshot()
    处理大型或结构化输出(例如 HTML、生成的代码)
  • 保持快照简洁——仅包含相关数据,避免时间戳和会话 ID
  • 使用
    expect.addSnapshotSerializer()
    屏蔽快照中的路径或敏感数据
  • 使用
    path-serializer
    跨平台标准化文件路径
  • 代码评审时需仔细检查快照变更

Coverage

覆盖率

  • Enable coverage with
    --coverage
    CLI flag or
    coverage.enabled: true
    in config
  • Install
    @rstest/coverage-istanbul
    for the Istanbul coverage provider
  • Use
    coverage.include
    to specify source files for coverage (e.g.,
    ['src/**/*.{js,ts,tsx}']
    )
  • Use
    coverage.thresholds
    to enforce minimum coverage requirements
  • Use
    coverage.reporters
    to generate reports in different formats (e.g.,
    text
    ,
    lcov
    ,
    html
    )
  • 通过
    --coverage
    CLI 标志或配置中
    coverage.enabled: true
    启用覆盖率统计
  • 安装
    @rstest/coverage-istanbul
    以使用 Istanbul 覆盖率统计工具
  • 使用
    coverage.include
    指定需要统计覆盖率的源文件(例如
    ['src/**/*.{js,ts,tsx}']
  • 使用
    coverage.thresholds
    设置最低覆盖率要求
  • 使用
    coverage.reporters
    生成不同格式的报告(例如
    text
    lcov
    html

Multi-project testing

多项目测试

  • Use
    projects
    field in root config to define multiple test projects
  • For monorepos, use glob patterns like
    'packages/*'
    to auto-discover sub-projects
  • Use
    defineProject
    helper in sub-project configs
  • Extract shared config and use
    mergeRstestConfig
    to compose project configs
  • Global options (
    reporters
    ,
    pool
    ,
    isolate
    ,
    coverage
    ,
    bail
    ) must be set at the root level, not in projects
  • 在根配置中使用
    projects
    字段定义多个测试项目
  • 对于单体仓库,使用通配符模式如
    'packages/*'
    自动发现子项目
  • 在子项目配置中使用
    defineProject
    辅助函数
  • 提取共享配置,使用
    mergeRstestConfig
    组合项目配置
  • 全局选项(
    reporters
    pool
    isolate
    coverage
    bail
    )必须在根级别设置,不可在项目内设置

CI integration

CI 集成

  • Use
    rstest run
    (not
    rstest watch
    ) in CI
  • Use
    --shard
    for parallel test execution across CI machines (e.g.,
    --shard 1/3
    )
  • Use
    --reporter=blob
    with
    rstest merge-reports
    to combine sharded results
  • Use
    --reporter=junit
    with
    outputPath
    for CI report integration
  • The
    github-actions
    reporter is auto-enabled in GitHub Actions for inline error annotations
  • Use
    --bail
    to stop early on first failure when appropriate
  • CI 环境中使用
    rstest run
    (而非
    rstest watch
  • 使用
    --shard
    在多台 CI 机器上并行执行测试(例如
    --shard 1/3
  • 使用
    --reporter=blob
    搭配
    rstest merge-reports
    合并分片测试结果
  • 使用
    --reporter=junit
    并配置
    outputPath
    以集成 CI 报告
  • 在 GitHub Actions 中会自动启用
    github-actions
    报告器,实现内联错误标注
  • 必要时使用
    --bail
    在首次失败后提前终止测试

Performance

性能优化

  • Disable
    isolate
    (
    --no-isolate
    ) when tests have no side effects for faster execution via module cache reuse
  • Use
    pool.maxWorkers
    to control parallelism based on available resources
  • Keep test build fast by avoiding unnecessary Rspack plugins in test config
  • Use test filtering (
    rstest <pattern>
    or
    -t <name>
    ) to run only relevant tests during development
  • Leverage watch mode's incremental re-runs for fast local feedback
  • 若测试无副作用,禁用
    isolate
    --no-isolate
    ),通过复用模块缓存提升执行速度
  • 使用
    pool.maxWorkers
    根据可用资源控制并行度
  • 测试构建中避免不必要的 Rspack 插件,以加快构建速度
  • 使用测试过滤(
    rstest <pattern>
    -t <name>
    ),开发期间仅运行相关测试
  • 利用监听模式的增量重跑,获取快速的本地反馈

Debugging

调试

  • Run with
    DEBUG=rstest
    to enable debug mode, which writes final configs and build outputs to disk
  • Read generated files in
    dist/.rstest-temp/.rsbuild/
    to confirm final Rstest/Rsbuild/Rspack config
  • Use VS Code's JavaScript Debug Terminal to run
    rstest
    with breakpoints
  • Use
    --reporter=verbose
    for detailed per-test output
  • Use
    --printConsoleTrace
    to trace console calls to their source
  • Add VS Code launch config for debugging specific test files with
    @rstest/core/bin/rstest.js
  • 运行时添加
    DEBUG=rstest
    启用调试模式,会将最终配置和构建输出写入磁盘
  • 查看
    dist/.rstest-temp/.rsbuild/
    中的生成文件,确认最终的 Rstest/Rsbuild/Rspack 配置
  • 使用 VS Code 的 JavaScript Debug Terminal 运行
    rstest
    并设置断点
  • 使用
    --reporter=verbose
    获取每个测试的详细输出
  • 使用
    --printConsoleTrace
    追踪控制台调用的来源
  • 添加 VS Code 启动配置,通过
    @rstest/core/bin/rstest.js
    调试特定测试文件

Profiling

性能分析

  • Use Rsdoctor with
    RSDOCTOR=true rstest run
    to analyze test build performance
  • Use
    samply
    for native profiling of both main and worker processes
  • Use Node.js
    --heap-prof
    for memory profiling
  • 使用 Rsdoctor,运行
    RSDOCTOR=true rstest run
    分析测试构建性能
  • 使用
    samply
    对主进程和工作进程进行原生性能分析
  • 使用 Node.js 的
    --heap-prof
    进行内存分析

Toolchain integration

工具链集成

  • Use the official VS Code extension (
    rstack.rstest
    ) for in-editor test running and debugging
  • For Rslib libraries, use
    @rstest/adapter-rslib
    for config reuse
  • For Rsbuild apps, use
    @rstest/adapter-rsbuild
    for config reuse
  • Use
    process.env.RSTEST
    to detect test environment and apply test-specific config
  • 使用官方 VS Code 扩展(
    rstack.rstest
    )在编辑器内运行和调试测试
  • 对于 Rslib 库,使用
    @rstest/adapter-rslib
    复用配置
  • 对于 Rsbuild 应用,使用
    @rstest/adapter-rsbuild
    复用配置
  • 使用
    process.env.RSTEST
    检测测试环境,应用测试专属配置

Documentation

文档