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/api/javascript-api/instance.md.
close
  • English
  • Rstest instance

    All APIs on this page are exported from the @rstest/core/api entry of @rstest/core. Use them to create Rstest instances, run or list tests, start watch sessions, merge blob reports, and invoke the CLI programmatically.

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

    All exports from @rstest/core/api are experimental and may change before Rstest 1.0.0. Pin @rstest/core to an exact version if you depend on this surface.

    createRstest

    Creates and returns an RstestInstance. It resolves config once during creation and reuses it as the instance's base configuration. Options passed to instance methods apply only to that operation without mutating the base configuration.

    cwd defaults to process.cwd() and serves as the base for resolving a relative config.root; omitting config uses an empty inline config without discovering a config file in cwd.

    createRstest sets RSTEST=true, sets NODE_ENV=test only when NODE_ENV is unset, and does not restore either variable afterwards.

    Example

    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);

    Load a config file

    Use loadConfig from @rstest/core to load a config file, then pass its return value ({ content, filePath, dependencies }) directly as config.

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

    CreateRstestOptions

    • Type:
    interface LoadedRstestConfig {
      content: RstestConfig; // Loaded config content.
      filePath: string | null; // Source config file path returned by `loadConfig`, or `null`.
      dependencies?: string[];
    }
    
    interface CreateRstestOptions {
      cwd?: string;
      config?: RstestConfig | LoadedRstestConfig;
      configLoader?: 'auto' | 'jiti' | 'native'; // Loader for configs discovered through `projects`; defaults to `auto`.
    }
    
    function createRstest(options?: CreateRstestOptions): Promise<RstestInstance>;

    rstest.context

    rstest.context is a read-only object resolved once when the instance is created. Use it to inspect resolved state without running tests: rootPath maps result testPath values back to the workspace, projects lists multi-project targets, config exposes the effective configuration, and version returns the @rstest/core version.

    Example

    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

    • Type:
    interface ProjectContext {
      name: string; // Project name.
      rootPath: string; // Absolute project root path.
      configFilePath?: string; // Project config file path, when one is associated with the project.
      configFileDependencies?: string[]; // Project config dependencies, including parent project configuration files.
    }
    
    interface RstestContext {
      readonly version: string;
      readonly rootPath: string;
      readonly config: Readonly<NormalizedConfig>;
      readonly projects: readonly ProjectContext[];
    }

    context.version

    The version of @rstest/core currently in use.

    • Type: string

    context.rootPath

    The absolute root path of the Rstest instance, resolved from config.root relative to cwd.

    • Type: string

    context.config

    The normalized config of the Rstest instance.

    • Type: Readonly<NormalizedConfig>

    context.projects

    The resolved project contexts. Without an explicit projects config, this contains the default project named by config.name ('rstest' by default).

    • Type: readonly ProjectContext[]

    rstest.run

    rstest.run() runs one test cycle and resolves with a TestRunResult. It rejects only when the run cannot start (invalid options or configuration, or a Node project's dev server fails to start). Failures after startup — a Browser Mode dev server or browser failing to start, a globalSetup error, a compile error, or failing tests — are reported through status without rejecting; see TestRunResult.

    Example

    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 accepts run-cycle options and the CLI-overridable subset of config options (not full RstestConfig; for example, reporters takes string | string[]). Creation-time options (config, configLoader, and root) and the CLI-only teardownTimeout are not accepted. See CLI options for corresponding CLI flags.

    For fields that override configuration options, precedence is: value passed to run() > instance configuration > option default. Omitted or undefined fields retain the instance configuration value. Nested objects and arrays follow the merge rules of the corresponding configuration option.

    Overrides apply only to the current run() call and do not mutate the instance's base configuration:

    const rstest = await createRstest({ config: { repeats: 2 } });
    
    await rstest.run({ repeats: 5 }); // Uses 5 for this call.
    await rstest.run(); // Uses the configured 2 again.

    filters is API-only (the CLI passes filters as positional arguments). It uses case-insensitive substring matching by default. Wrap a filter in matching single or double quotes to match an exact absolute or root-relative path, for example filters: ['"src/foo.test.ts"', 'utils']; quoted and unquoted filters can be mixed. Omit filters to select all files; an explicit empty array selects none.

    trace v0.12.4 collects a performance trace for the run. Setting true writes the trace files under <rootPath>/.rstest/. Unlike the CLI flag, it prints nothing and never starts the Perfetto helper server; read file paths from TestRunResult.trace instead. In rstest.watch(), it applies to the whole session.

    repeats v0.13.0 sets the number of additional runs for each individual test. Test and suite options take precedence; see repeats.

    browser overrides browser options for browser projects on this run: RunOptions.browser.instances v0.13.0 filters configured browser instances like the CLI filter — only instances whose browserName is listed run, a browser project with no match is skipped, and a name no selected browser project configures is an error; undefined keeps all configured instances. The deprecated browser.name selects a single browser. See instances for option semantics.

    • Type:
    interface RunOptions {
      filters?: string[];
      trace?: boolean;
      repeats?: number;
      // `true` is shorthand for `{ enabled: true }`.
      browser?:
        | boolean
        | {
            enabled?: boolean;
            /** @deprecated Use `instances` instead. Will be removed in 1.0. */
            name?: BrowserName;
            instances?: BrowserName | BrowserName[];
            headless?: boolean;
            screenshotFailures?: boolean | { clean?: boolean };
            viewport?: BrowserViewport;
            port?: number;
            strictPort?: boolean;
            providerOptions?: Record<string, unknown>;
          };
      // ...plus other supported run and config override options matching CLI flags
    }
    
    interface RstestInstance {
      run(options?: RunOptions): Promise<TestRunResult>;
    }

    TestRunResult

    • Type:
    type TestRunStatus = 'passed' | 'failed' | 'error';
    
    interface TestRunResult {
      status: TestRunStatus; // Overall status of the run.
      trace?: { tracePath: string; summaryPath: string }; // Present only when the run was started with `trace`.
      // Every other field matches the `onTestRunEnd` payload, minus `getSourcemap`.
    }

    The remaining fields (results, testResults, summary, duration, snapshotSummary, unhandledErrors, coverage, rerunTestPaths) match the onTestRunEnd payload in the Reporter API.

    status is 'error' when unhandledErrors is non-empty. It is 'failed' when the run has failing tests or test files, a coverage threshold violation, or no tests found without passWithNoTests. In watch mode, it stays 'failed' while the session still holds a failing test file, even if the current cycle passed. Otherwise, it is 'passed'. A later global teardown error does not change the onTestRunEnd payload, but run() still resolves with 'failed'.

    Every entry in unhandledErrors is a plain JSON-serializable object, not an Error instance.

    trace v0.12.4 holds the absolute paths of the Perfetto trace JSON and its markdown summary when trace is enabled. In watch mode, it points to the latest cycle's files.

    rstest.watch

    rstest.watch() starts a watch session and returns a watcher handle to close it.

    Example

    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 runs after every completed cycle, including the first. results, summary, and status reflect the accumulated watch session; rerunTestPaths lists the files executed in the current cycle.

    Failures fall into three categories:

    • Startup failure — configuration failed, or a Node project's dev server could not start. Both run() and watch() reject.
    • Fatal failure after startup — a Browser Mode dev server or browser failed to start, a first-cycle globalSetup threw or failed to compile, or the bundler ended compilation without reattaching a file watcher. run() resolves with status: 'error'. In watch mode, the failed cycle still reaches onResult and then the session closes; if watch() has not resolved yet, it rejects with that error (or an AggregateError for multiple errors).
    • Recoverable cycle failure — a test failure, a test file compile error, or a later-cycle globalSetup failure. The cycle reports the failure and the watch session stays open.

    Errors thrown by onResult are isolated and do not stop the watch session. Calling watcher.close() releases the compiler, workers, file watchers, and pending globalSetup teardown hooks. It is idempotent and rejects if teardown fails.

    rstest.watch() rejects related and changed because they select a fixed file set, whereas a watch session must pick up newly related tests. Use rstest.run() for those options (related: false and changed: false are ignored).

    WatchOptions

    • Type:
    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() collects test files and test declarations without running test bodies.

    Example

    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);

    Set filesOnly to skip collecting declarations. includeSuites includes named suites as separate entries. includeTaskLocation from RunOptions adds source locations.

    Every entry includes testPath and project. The implicit default project's base name is config.name ('rstest' by default). Declaration entries include name, suite-prefixed fullName, and parentNames; file entries omit name and fullName. Skipped and todo declarations are included with runMode set to 'skip' or 'todo'; runnable declarations omit runMode.

    In Browser Mode, declarations are collected in each selected browser instance. filesOnly returns one entry per file and instance without launching browsers. Both modes use the same project names as run(), such as web (chromium) and web (firefox).

    Entries are returned in depth-first declaration order: a suite immediately precedes its descendants, and entries for the same file and project stay contiguous.

    rstest.listTests() rejects with ListTestsError when collection fails instead of returning a partial or empty list.

    shard applies only when passed explicitly to rstest.listTests(); omitted shard lists all files regardless of instance config.

    ListOptions

    • Type:
    interface ListOptions {
      filesOnly?: boolean;
      includeSuites?: boolean;
    }
    
    interface ListedTest {
      testPath: string; // Path of the test file.
      name?: string; // Declaration's own name; absent for file entries.
      fullName?: string; // Suite-prefixed display name; absent for file entries.
      parentNames?: string[]; // Names of the enclosing suites.
      project: string; // Project name.
      location?: TestLocation; // Source location when requested.
      runMode?: 'skip' | 'todo'; // Skip or todo mode for non-runnable declarations.
      type: 'file' | 'suite' | 'case'; // Entry kind.
    }
    
    interface RstestInstance {
      listTests(options?: ListOptions & RunOptions): Promise<ListedTest[]>;
    }

    ListTestsError

    Error class thrown by rstest.listTests() when one or more files fail during collection or unhandled errors occur.

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

    SerializedError is exported from @rstest/core; see TestResult for its fields.

    rstest.mergeReports

    rstest.mergeReports() merges blob reports and returns the same result model as rstest.run().

    It rejects when the operation cannot produce a run result; test failures in the merged reports are indicated through status without rejecting the promise.

    Example

    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 selects the blob-report directory. cleanup removes consumed reports after a successful merge.

    MergeReportsOptions

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

    runCLI

    runCLI runs the Rstest CLI in the current process. It parses argv, sets process.exitCode, and installs the CLI's signal handlers. Use it when you need the CLI's process behavior; instance methods do not set process.exitCode or install signal handlers.

    Example

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

    argv matches the shape of Node.js process.argv and defaults to process.argv: the first two entries are the executable and script paths and are ignored, while the command, filters, and flags start at index 2.

    See the CLI documentation for all available commands and flags.

    RunCLIOptions

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