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/config/test/global-setup.md.
close
  • 简体中文
  • globalSetup

    • 类型: string | string[]
    • 默认值: undefined

    Rstest 中的 globalSetup 选项允许你运行 setup 和 teardown 代码,这些代码会在所有测试之前和完成后执行。这对于以下场景很有用:

    • 启动和停止数据库
    • 初始化测试服务
    • 测试运行后清理资源
    rstest.config.ts
    import { defineConfig } from '@rstest/core';
    
    export default defineConfig({
      globalSetup: ['./global-setup.ts'],
    });

    与 setupFiles 的区别

    根据资源需要的作用范围选择:

    方式执行时机执行环境清理方式典型用途
    globalSetup项目的测试开始前执行一次独立的 setup worker导出 teardown 或返回清理函数启动数据库或测试服务
    setupFiles每个测试文件执行前该文件的测试环境注册 afterAll 或 afterEach hook扩展 matcher、注册共用 hook
    beforeAll所属 suite 的测试开始前执行一次;在 describe 外注册时作用于整个文件与测试相同的环境afterAll 或返回的清理函数准备 suite 共用的数据
    beforeEach作用范围内的每个测试执行前与测试相同的环境afterEach 或返回的清理函数为每个测试重置状态

    setupFiles 不会识别导出的 setup 或 teardown 函数。文件顶层代码会在每个测试文件执行前运行,可以在其中注册 hook 来清理资源。

    全局设置文件格式

    你可以用两种格式编写全局设置文件:

    命名函数(推荐)

    // global-setup.ts
    
    export async function setup() {
      console.log('正在设置测试环境...');
    
      // 初始化数据库、启动服务等
      // await startDatabase();
    }
    
    export async function teardown() {
      console.log('正在清理测试环境...');
    
      // 清理资源
      // await stopDatabase();
    }

    两个导出可以省略其一;两个都没有、也没有默认导出函数的文件会让运行失败。

    返回 teardown 函数的默认函数

    // global-setup.ts
    export default async function globalSetup() {
      console.log('正在设置测试环境...');
    
      // 初始化资源
      const database = await connectDatabase();
      const server = await startTestServer();
    
      // 返回 teardown 函数
      return async () => {
        console.log('正在清理资源...');
        await server.stop();
        await database.disconnect();
      };
    }

    向测试传递值

    globalSetup 在独立的 setup worker 中运行。测试无法访问其中的模块作用域变量,例如数据库连接。可以通过环境变量传递连接信息,再在测试环境中创建连接。

    globalSetup 中的环境变量变更会传递给 Node.js 测试 worker,不会修改宿主进程的 process.env。

    Browser 项目

    Browser Mode 的环境变量共享遵循以下规则:

    • Browser 项目自身的 globalSetup 所产生的变更,可以通过 process.env 和 import.meta.env 读取,与内置的 NODE_ENV、RSTEST 一起生效。
    • 显式的 env 配置优先于 globalSetup 中设置的值。
    • 其他宿主环境变量不会自动传递给 Browser 测试。在混合 Node.js 和 Browser 项目中,Node.js 项目 globalSetup 中的变更不会合并到 Browser 测试中。

    Browser provider hook(modifyRstestConfig)在测试发现阶段执行,早于 setup 阶段,因此其中新增或修改的 globalSetup 条目也会生效。

    Watch 模式

    项目的 globalSetup 成功执行后,watch 模式下的重新运行会复用这次初始化结果,直到 watch 会话关闭时才执行 teardown。需要在每个测试文件执行前重复运行的初始化逻辑,应放在 setupFiles 中。

    多个全局设置文件

    当使用多个全局设置文件时:

    • 设置函数按提供的顺序顺序执行
    • teardown 函数按相反顺序执行(LIFO - 后进先出)
    • 如果任何设置失败,整个测试运行都会失败

    示例:数据库设置

    // db-setup.ts
    let dbConnection: any;
    
    export async function setup() {
      const { MongoClient } = await import('mongodb');
      const client = new MongoClient(process.env.TEST_MONGODB_URI!);
      await client.connect();
    
      dbConnection = client.db('test');
    
      // 播种测试数据
      await dbConnection.collection('users').insertMany([
        { name: 'John', email: 'john@example.com' },
        { name: 'Jane', email: 'jane@example.com' },
      ]);
    
      console.log('✓ 数据库已连接并播种数据');
    }
    
    export async function teardown() {
      if (dbConnection) {
        await dbConnection.dropDatabase();
        await dbConnection.client.close();
        console.log('✓ 数据库已清理');
      }
    }
    rstest.config.ts
    import { defineConfig } from '@rstest/core';
    
    export default defineConfig({
      globalSetup: ['./db-setup.ts'],
      include: ['**/*.test.ts'],
    });