For AI agents: the complete documentation index is available at https://rstest.rs/zh/llms.txt, the full documentation bundle is available at https://rstest.rs/zh/llms-full.txt, and this page is available as Markdown at https://rstest.rs/zh/api/javascript-api/instance.md.
close
  • 简体中文
  • Rstest 实例

    本页介绍的 API 均由 @rstest/core 的 @rstest/core/api 入口导出,用于创建 Rstest 实例、运行或列出测试、启动 watch 会话、合并 blob 报告以及以编程方式调用 CLI。

    import { createRstest } from '@rstest/core/api';
    Warning

    @rstest/core/api 的所有导出目前均为实验性 API,在 Rstest 1.0.0 之前可能调整。依赖该入口时建议锁定 @rstest/core 的精确版本。

    createRstest

    创建并返回一个 RstestInstance。config 会在创建实例时解析一次,并作为实例的基础配置持续复用;传给实例方法的选项只作用于当前操作,不会修改基础配置。

    cwd 默认为 process.cwd(),用于解析相对路径的 config.root;省略 config 时使用空的内联配置,不会在 cwd 中自动查找配置文件。

    createRstest 会设置 RSTEST=true,仅在 NODE_ENV 未设置时设置 NODE_ENV=test,且之后不会还原这两个环境变量。

    示例

    import { createRstest } from '@rstest/core/api';
    
    const rstest = await createRstest({
      cwd: './packages/app',
      config: {
        include: ['src/**/*.test.ts'],
        reporters: [],
      },
    });
    
    const result = await rstest.run();
    console.log(result.status);

    加载配置文件

    使用 @rstest/core 的 loadConfig 加载配置文件,再将返回值({ content, filePath, dependencies })直接传给 config。

    import { loadConfig } from '@rstest/core';
    import { createRstest } from '@rstest/core/api';
    
    const loaded = await loadConfig();
    const rstest = await createRstest({ config: loaded });

    CreateRstestOptions

    • 类型:
    interface LoadedRstestConfig {
      content: RstestConfig; // 已加载的配置内容。
      filePath: string | null; // `loadConfig` 返回的配置文件路径,无文件时为 `null`。
      dependencies?: string[];
    }
    
    interface CreateRstestOptions {
      cwd?: string;
      config?: RstestConfig | LoadedRstestConfig;
      configLoader?: 'auto' | 'jiti' | 'native'; // 解析通过 `projects` 发现的配置文件时使用的 loader;默认为 `auto`。
    }
    
    function createRstest(options?: CreateRstestOptions): Promise<RstestInstance>;

    rstest.context

    rstest.context 是在创建实例时解析一次的只读对象,可在不运行测试的前提下查看解析结果:通过 rootPath 将结果中的 testPath 映射回工作区,通过 projects 获取多项目列表,通过 config 查看生效配置,通过 version 检查版本兼容性。

    示例

    import { createRstest } from '@rstest/core/api';
    
    const rstest = await createRstest({
      config: {
        projects: [
          {
            name: 'unit',
            include: ['tests/**/*.test.ts'],
          },
        ],
      },
    });
    
    console.log(rstest.context.version);
    console.log(rstest.context.rootPath);
    
    for (const project of rstest.context.projects) {
      console.log(project.name, project.rootPath);
    }

    RstestContext

    • 类型:
    interface ProjectContext {
      name: string; // 项目名称。
      rootPath: string; // 项目的绝对根路径。
      configFilePath?: string; // 与项目关联的配置文件路径(如果有)。
      configFileDependencies?: string[]; // 项目配置依赖,包含父级项目的配置文件。
    }
    
    interface RstestContext {
      readonly version: string;
      readonly rootPath: string;
      readonly config: Readonly<NormalizedConfig>;
      readonly projects: readonly ProjectContext[];
    }

    context.version

    当前使用的 @rstest/core 版本。

    • 类型: string

    context.rootPath

    Rstest 实例的绝对根路径,基于 cwd 解析 config.root 得到。

    • 类型: string

    context.config

    Rstest 实例规范化后的配置。

    • 类型: Readonly<NormalizedConfig>

    context.projects

    解析后的项目 Context 列表。未显式配置 projects 时,数组中包含以 config.name 命名的默认项目(默认为 'rstest')。

    • 类型: readonly ProjectContext[]

    rstest.run

    rstest.run() 运行一轮测试并返回 TestRunResult。仅当运行无法启动时(无效的选项或配置,或 Node 项目的 dev server 无法启动),返回的 Promise 才会拒绝;启动后的失败(Browser Mode dev server 或浏览器无法启动、globalSetup 抛错、编译错误、测试失败)都通过 status 报告,不会拒绝 Promise,见 TestRunResult。

    示例

    import { createRstest } from '@rstest/core/api';
    
    const rstest = await createRstest({
      config: {
        include: ['src/**/*.test.ts'],
      },
    });
    
    const result = await rstest.run({
      filters: ['"src/foo.test.ts"'],
    });
    
    console.log(result.status);
    console.log(result.summary.tests);

    RunOptions

    RunOptions 支持运行周期选项以及可通过 CLI 覆盖的配置子集(并非完整的 RstestConfig;例如 reporters 仅接受 string | string[])。不接受创建阶段的选项(config、configLoader、root)和仅用于 CLI 的 teardownTimeout。对应的 CLI 参数见 CLI 选项。

    对于覆盖配置项的字段,优先级为:本次 run() 显式传入的值 > 实例配置值 > 配置项默认值。未传入或值为 undefined 的字段保留实例配置;嵌套对象和数组遵循对应配置项的合并规则。

    覆盖仅作用于当前 run() 调用,不会修改实例的基础配置:

    const rstest = await createRstest({ config: { repeats: 2 } });
    
    await rstest.run({ repeats: 5 }); // 本次调用使用 5。
    await rstest.run(); // 恢复使用实例配置中的 2。

    filters 仅用于 API(CLI 通过位置参数传入 filter)。默认按不区分大小写的子串匹配;用成对的单引号或双引号包裹路径可精确匹配绝对路径或相对于 root 的路径,例如 filters: ['"src/foo.test.ts"', 'utils'],两者可混用。省略 filters 会选择全部文件;显式传入空数组则不选择任何文件。

    trace v0.12.4 为本次运行采集性能 trace。传入 true 会将 trace 文件写入 <rootPath>/.rstest/。与 CLI 参数不同,它不会打印输出,也不会启动 Perfetto helper server,文件路径需从 TestRunResult.trace 读取。在 rstest.watch() 中对整个会话生效。

    repeats v0.13.0 设置单个测试的额外执行次数,测试和套件自身的选项优先。详见 repeats。

    browser 覆盖本次运行中 browser 项目的浏览器选项:RunOptions.browser.instances v0.13.0 按与 CLI 过滤相同的规则筛选已配置的浏览器实例——仅运行 browserName 在列表中的实例,无匹配实例的 browser 项目会被跳过,若指定的名称未在任何选中项目中配置则报错;传 undefined 保留所有已配置实例。已废弃的 browser.name 用于选择单个浏览器。选项语义详见 instances。

    • 类型:
    interface RunOptions {
      filters?: string[];
      trace?: boolean;
      repeats?: number;
      // `true` 为 `{ enabled: true }` 的简写。
      browser?:
        | boolean
        | {
            enabled?: boolean;
            /** @deprecated 请改用 `instances`,将在 1.0 移除。 */
            name?: BrowserName;
            instances?: BrowserName | BrowserName[];
            headless?: boolean;
            screenshotFailures?: boolean | { clean?: boolean };
            viewport?: BrowserViewport;
            port?: number;
            strictPort?: boolean;
            providerOptions?: Record<string, unknown>;
          };
      // ……以及其余与 CLI 选项对应的运行期与配置覆盖字段
    }
    
    interface RstestInstance {
      run(options?: RunOptions): Promise<TestRunResult>;
    }

    TestRunResult

    • 类型:
    type TestRunStatus = 'passed' | 'failed' | 'error';
    
    interface TestRunResult {
      status: TestRunStatus; // 本次运行的整体状态。
      trace?: { tracePath: string; summaryPath: string }; // 仅在传入 `trace` 时存在。
      // 其余字段与 `onTestRunEnd` 的 payload 相同,去掉 `getSourcemap`。
    }

    其余字段(results、testResults、summary、duration、snapshotSummary、unhandledErrors、coverage、rerunTestPaths)对应 Reporter API 中 onTestRunEnd 的 payload。

    当 unhandledErrors 非空时,status 为 'error'。存在失败的测试或测试文件、覆盖率未达标,或未开启 passWithNoTests 且未找到测试时,status 为 'failed'。在 watch 模式下,只要会话中仍保留失败的测试文件,即使当前轮次全部通过,status 仍为 'failed'。其余情况为 'passed'。后续 global teardown 阶段发生的错误不会改变 onTestRunEnd 收到的 payload,但 run() 仍会返回 'failed'。

    unhandledErrors 中的每一项都是可 JSON 序列化的普通对象,而非 Error 实例。

    trace v0.12.4 在启用 trace 时包含 Perfetto trace JSON 与 markdown 摘要的绝对路径。在 watch 模式下指向最近一轮生成的文件。

    rstest.watch

    rstest.watch() 启动监听会话,并返回用于关闭会话的控制器。

    示例

    import { createRstest } from '@rstest/core/api';
    
    const rstest = await createRstest({
      config: {
        include: ['src/**/*.test.ts'],
      },
    });
    
    const watcher = await rstest.watch({
      onResult(result) {
        console.log(
          result.status,
          result.results.map((file) => file.testPath),
          result.rerunTestPaths,
        );
      },
    });
    
    await watcher.close();

    每轮结束后都会调用 onResult(包括第一轮)。results、summary 和 status 反映整个 watch 会话的累计状态,rerunTestPaths 列出当前轮次执行的文件。

    失败分为三类:

    • 启动失败:配置阶段抛错,或 Node 项目的 dev server 无法启动。run() 和 watch() 均会拒绝 Promise。
    • 启动后的致命失败:Browser Mode 的 dev server 或浏览器无法启动、首轮 globalSetup 抛错或编译失败,或打包器结束编译后未能重新挂载文件监听器。run() 返回 status: 'error';在 watch 模式下,失败轮次仍会送达 onResult,随后会话关闭;若 watch() 尚未 resolve,则以该错误拒绝(多个错误时合并为 AggregateError)。
    • 可恢复的周期失败:测试失败、测试文件编译失败,或后续轮次的 globalSetup 失败。该轮会上报失败,watch 会话保持开启。

    onResult 抛出的错误会被隔离,不会中断监听会话。调用 watcher.close() 会释放编译器、worker、文件监听器及待执行的 globalSetup 清理回调。该方法幂等,若清理阶段失败则返回的 Promise 会被拒绝。

    rstest.watch() 不接受 related 和 changed,因为它们会固定文件集合,而监听会话需要动态发现新的关联测试;需要这两个选项时请改用 rstest.run()(传入 related: false 和 changed: false 会被忽略)。

    WatchOptions

    • 类型:
    interface WatchOptions {
      onResult?: (result: TestRunResult & { rerunTestPaths: string[] }) => void;
    }
    
    interface RstestWatcher {
      close(): Promise<void>;
    }
    
    interface RstestInstance {
      watch(options?: WatchOptions & RunOptions): Promise<RstestWatcher>;
    }

    rstest.listTests

    rstest.listTests() 收集测试文件和测试声明,不执行测试主体代码。

    示例

    import { createRstest } from '@rstest/core/api';
    
    const rstest = await createRstest({
      config: {
        include: ['src/**/*.test.ts'],
      },
    });
    
    const tests = await rstest.listTests({
      includeSuites: true,
      includeTaskLocation: true,
    });
    
    console.log(tests);

    设置 filesOnly 可跳过声明收集;includeSuites 会将具名测试套件作为独立条目返回;RunOptions 中的 includeTaskLocation 用于附加源码位置。

    每个条目都包含 testPath 和 project。隐式默认项目的基础名称为 config.name(默认为 'rstest')。声明条目包含自身的 name、带套件前缀的 fullName 以及表示层级的 parentNames;文件条目省略 name 和 fullName。标记为 skip 或 todo 的声明也会包含在内,其 runMode 为 'skip' 或 'todo';可运行声明省略 runMode。

    在 Browser Mode 下,声明会在每个选中的浏览器实例中收集;开启 filesOnly 时按文件与实例组合返回条目,且不启动浏览器。两种模式返回的 project 名称均与 run() 一致,例如同时选中两个实例时为 web (chromium) 和 web (firefox)。

    条目按深度优先的声明顺序返回:套件紧邻其后代之前,同一文件和项目的条目保持连续。

    收集失败时,rstest.listTests() 会抛出 ListTestsError,而不是返回部分列表或空列表。

    仅当向 rstest.listTests() 显式传入 shard 时才按分片过滤;省略时列出全部文件,不受实例配置影响。

    ListOptions

    • 类型:
    interface ListOptions {
      filesOnly?: boolean;
      includeSuites?: boolean;
    }
    
    interface ListedTest {
      testPath: string; // 测试文件路径。
      name?: string; // 声明自身名称;文件条目省略此字段。
      fullName?: string; // 带套件前缀的显示名称;文件条目省略此字段。
      parentNames?: string[]; // 外层测试套件名称。
      project: string; // 项目名称。
      location?: TestLocation; // 请求后附带的源码位置。
      runMode?: 'skip' | 'todo'; // 不可运行声明的 skip 或 todo 模式。
      type: 'file' | 'suite' | 'case'; // 条目类型。
    }
    
    interface RstestInstance {
      listTests(options?: ListOptions & RunOptions): Promise<ListedTest[]>;
    }

    ListTestsError

    当测试收集阶段出现文件级错误或未捕获异常时,rstest.listTests() 抛出的错误类。

    • 类型:
    class ListTestsError extends Error {
      readonly name: 'ListTestsError';
      files: { testPath: string; errors: SerializedError[] }[];
      unhandledErrors: SerializedError[];
      constructor(
        files: { testPath: string; errors: SerializedError[] }[],
        unhandledErrors: SerializedError[],
      );
    }

    SerializedError 由 @rstest/core 导出,字段定义见 TestResult。

    rstest.mergeReports

    rstest.mergeReports() 合并 blob 报告,并返回与 rstest.run() 相同的结果模型。

    仅当无法生成运行结果时拒绝 Promise;合并报告中存在失败测试时,通过 status 反映,不会拒绝 Promise。

    示例

    import { createRstest } from '@rstest/core/api';
    
    const rstest = await createRstest();
    
    const result = await rstest.mergeReports({
      path: './.rstest-reports',
      cleanup: true,
    });
    
    console.log(result.status);

    path 指定 blob 报告目录,cleanup 在合并成功后删除已消费的报告。

    MergeReportsOptions

    • 类型:
    interface MergeReportsOptions {
      path?: string;
      cleanup?: boolean;
    }
    
    interface RstestInstance {
      mergeReports(options?: MergeReportsOptions): Promise<TestRunResult>;
    }

    runCLI

    runCLI 在当前进程中运行 Rstest CLI,负责解析 argv、设置 process.exitCode 并注册 CLI 的信号处理。需要完整 CLI 进程行为时使用此函数;实例方法不会设置 process.exitCode 或注册信号处理。

    示例

    import { runCLI } from '@rstest/core/api';
    
    runCLI({
      argv: [...process.argv.slice(0, 2), 'run', 'src/foo.test.ts', '--update'],
    });

    argv 格式与 Node.js process.argv 一致(默认即为 process.argv):前两项为可执行文件与脚本路径并会被忽略,子命令、filter 和选项从索引 2 开始。

    所有可用的命令和选项见 CLI 文档。

    RunCLIOptions

    • 类型:
    interface RunCLIOptions {
      argv?: string[];
    }
    
    function runCLI(options?: RunCLIOptions): void;