close

Reporters

Rstest 中的报告器控制测试结果的显示和处理方式。

你可以使用内置报告器获得不同的输出格式,或创建自定义报告器来集成到你的工作流程中。

配置方式

你可以通过以下方式配置报告器:

  1. CLI: --reporter=<name> (可多次使用)
  2. 配置文件: 在 rstest.config.ts 中添加 reporters
import { defineConfig } from '@rstest/core';
import { customReporter } from './path/to/custom-reporter';

export default defineConfig({
  reporters: [
    'default', // 简单字符串报告器
    ['junit', { outputPath: './test-results.xml' }], // 带选项的报告器
    customReporter, // 自定义报告器实例
  ],
});

更多配置方式请参考 报告器配置

内置报告器

Rstest 提供了多种内置报告器:

报告器用途使用场景
default带颜色的控制台输出本地开发
verbose详细的测试用例输出调试测试失败
github-actionsCI 错误注释GitHub Actions 工作流
junitJUnit XML 格式CI/CD 集成

默认报告器

默认报告器在终端中显示测试运行状态、结果和汇总信息,带有彩色输出。

输出示例:

 test/index.test.ts (2)

 Test Files 1 passed
      Tests 2 passed
   Duration 112ms (build 19ms, tests 93ms)

配置选项:

  • summary: 是否显示汇总信息 (默认: true)
  • logger: 用于输出的自定义日志函数 (默认: process.stdout/process.stderr)

详细报告器

详细报告器为所有测试用例输出详细信息,包括成功的测试用例。当你需要对测试执行有完整可见性时使用此报告器。

CLI
rstest.config.ts
npx rstest --reporter=verbose

输出示例:

 test/index.test.ts (2) 2ms
 Index > should add two numbers correctly (1ms)
 Index > should test source code correctly (1ms)

 Test Files 1 passed
      Tests 2 passed
   Duration 112ms (build 19ms, tests 93ms)

GitHub Actions 报告器

GitHub Actions 报告器将在测试失败时以 GitHub Actions 工作流命令 的形式输出错误信息。

CLI
rstest.config.ts
npx rstest --reporter=github-actions

当测试失败时,GitHub Actions 报告器会输出类似以下格式的信息:

::error file=src/index.ts,line=4,col=17,title=test/index.test.ts > should add two numbers correctly::expected 2 to be 4

这些输出会被 GitHub Actions 解析并在对应位置生成注释。

rstest-github-actions-example

自动启用

当没有手动设置报告器时,Rstest 在检测到 GitHub Actions 环境(process.env.GITHUB_ACTIONS'true')时会自动启用此报告器。

手动启用

你也可以手动启用此报告器:

CLI
rstest.config.ts
npx rstest --reporter=github-actions

JUnit 报告器

生成 JUnit XML 格式的测试报告,非常适合 CI/CD 集成和测试结果聚合。

CLI
rstest.config.ts
npx rstest --reporter=junit

配置选项:

  • outputPath: 输出文件路径 (默认为控制台输出)

JUnit 报告器生成如下 XML 格式:

<?xml version="1.0" encoding="UTF-8"?>
<testsuites name="rstest tests" tests="3" failures="1" errors="1" skipped="1" time="0.3" timestamp="2024-01-01T00:00:00.000Z">
  <testsuite name="test1.test.ts" tests="3" failures="1" errors="1" skipped="1" time="0.3" timestamp="2024-01-01T00:00:00.000Z">
    <testcase name="should pass" classname="test1.test.ts" time="0.1">
    </testcase>
    <testcase name="should fail" classname="test1.test.ts" time="0.2">
      <failure message="Test failed" type="AssertionError">expected 'hi' to be 'hii' // Object.is equality - Expected + Received - hii + hi at test1.test.ts:10:21</failure>
    </testcase>
    <testcase name="should skip" classname="test1.test.ts" time="0.0">
      <skipped/>
    </testcase>
  </testsuite>
</testsuites>

JUnit 报告器将测试用例执行状态映射到 JUnit 测试状态:

  • pass: 测试通过
  • fail: 测试失败,生成 <failure> 标签
  • skip: 测试跳过,生成 <skipped> 标签
  • todo: 测试待办,生成 <skipped> 标签

自定义报告器

对于高级集成需求,你可以通过实现 Reporter 接口来创建自定义报告器。

更多详细信息可以在 Reporter API 参考 中找到。