For AI agents: the complete documentation index is available at https://rstest.rs/llms.txt, the full documentation bundle is available at https://rstest.rs/llms-full.txt, and this page is available as Markdown at https://rstest.rs/config/test/global-setup.md.
close
  • English
  • globalSetup

    • Type: string | string[]
    • Default: undefined

    The globalSetup option in Rstest allows you to run setup and teardown code that executes once before all tests and after all tests complete. This is useful for:

    • Starting and stopping databases
    • Initializing test services
    • Cleaning up resources after test runs
    rstest.config.ts
    import { defineConfig } from '@rstest/core';
    
    export default defineConfig({
      globalSetup: ['./global-setup.ts'],
    });

    Differences from setupFiles

    Choose the scope that matches the resource you need:

    MechanismWhen it runsWhere it runsCleanupTypical use
    globalSetupOnce before a project's testsSeparate setup workerExport teardown or return a cleanup functionStart a database or test server
    setupFilesBefore each test fileThat file's test environmentRegister afterAll or afterEach hooksInstall matchers and register shared hooks
    beforeAllOnce before tests in its suite, or file when outside describeSame environment as the testsafterAll or a returned cleanup functionPrepare data shared by a suite
    beforeEachBefore each test in its scopeSame environment as the testafterEach or a returned cleanup functionReset state for each test

    setupFiles does not recognize exported setup or teardown functions. Its top-level code runs before each file and can register hooks for later cleanup.

    Global setup file formats

    You can write global setup files in two formats:

    // global-setup.ts
    
    export async function setup() {
      console.log('Setting up test environment...');
    
      // Initialize database, start services, etc.
      // await startDatabase();
    }
    
    export async function teardown() {
      console.log('Tearing down test environment...');
    
      // Cleanup resources
      // await stopDatabase();
    }

    Either export can be omitted; a file that exports neither and has no default function fails the run.

    Default function returning teardown

    // global-setup.ts
    export default async function globalSetup() {
      console.log('Setting up test environment...');
    
      // Initialize resources
      const database = await connectDatabase();
      const server = await startTestServer();
    
      // Return teardown function
      return async () => {
        console.log('Cleaning up resources...');
        await server.stop();
        await database.disconnect();
      };
    }

    Sharing values with tests

    Global setup runs in a separate setup worker. Tests cannot access its module-scope variables, such as a database connection. Share connection details through environment variables, then create the connection in the test environment.

    Environment variable changes made in global setup are passed to Node.js test workers without changing the host process's process.env.

    Browser projects

    For Browser Mode, environment sharing follows these rules:

    • Changes from the browser project's own globalSetup are available through process.env and import.meta.env, alongside the built-in NODE_ENV and RSTEST values.
    • Explicit env configuration takes precedence over values from global setup.
    • Other host environment variables are not forwarded automatically. In mixed Node.js and browser projects, Node.js projects' global setup changes are not merged into browser tests.

    Browser provider hooks (modifyRstestConfig) run during test discovery, before the setup stage. Any globalSetup entries they add or change are therefore included.

    Watch mode

    Once a project's global setup succeeds, watch reruns reuse it. The teardown runs when the watch session closes. Put initialization that must repeat for each test file in setupFiles.

    Multiple global setup files

    When using multiple global setup files:

    • Setup functions execute sequentially in the order provided
    • Teardown functions execute in reverse order (LIFO - Last In, First Out)
    • If any setup fails, the entire test run fails

    Example: database setup

    // 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');
    
      // Seed test data
      await dbConnection.collection('users').insertMany([
        { name: 'John', email: 'john@example.com' },
        { name: 'Jane', email: 'jane@example.com' },
      ]);
    
      console.log('✓ Database connected and seeded');
    }
    
    export async function teardown() {
      if (dbConnection) {
        await dbConnection.dropDatabase();
        await dbConnection.client.close();
        console.log('✓ Database cleaned up');
      }
    }
    rstest.config.ts
    import { defineConfig } from '@rstest/core';
    
    export default defineConfig({
      globalSetup: ['./db-setup.ts'],
      include: ['**/*.test.ts'],
    });