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/guide/migration/jest.md.
close
  • English
  • Migrating from Jest

    Rstest provides Jest-compatible test, assertion, and mock APIs. Follow this guide to migrate a Jest project to Rstest:

    Using Agent Skills

    If you are using a Coding Agent that supports Skills, install the migrate-to-rstest skill to assist with migrating from Jest to Rstest:

    npx skills add rstackjs/agent-skills --skill migrate-to-rstest

    Installation and setup

    Install @rstest/core as a development dependency:

    npm
    yarn
    pnpm
    bun
    deno
    npm add @rstest/core -D

    Update the test script in package.json to run rstest instead of jest:

    "scripts": {
    -  "test": "jest"
    +  "test": "rstest"
    }

    CLI option mappings

    Some Jest CLI flags map directly to Rstest, while others move into config. Use this table for the common option differences you are likely to hit during migration:

    Jest CLI optionRstest equivalentNotes
    jestrstest
    jest --watchrstest --watch or rstest watch
    jest --watchAllrstest --watch or rstest watchRstest does not distinguish between --watch and --watchAll.
    jest --runInBandrstest --pool.maxWorkers 1
    jest --maxWorkers=50% or jest -w 50%rstest --pool.maxWorkers 50%Rstest's -w means --watch, not --maxWorkers.
    jest --selectProjects apprstest --project app
    jest --env=jsdomrstest --testEnvironment jsdom
    jest --forceExitrstest --teardownTimeout 0Rstest exits immediately after teardown functions and reporters finish.
    jest --openHandlesTimeout=5000rstest --teardownTimeout 5000Rstest force exits after the timeout; Jest only prints a warning.
    jest --coveragerstest --coverageAlso install the provider package that matches your config: @rstest/coverage-istanbul or @rstest/coverage-v8.
    jest --coverageDirectory=coveragerstest --coverage.reportsDirectory coverageOr set coverage.reportsDirectory in rstest.config.ts.
    jest --coverageProvider=v8rstest --coverage.provider v8Install @rstest/coverage-v8, or set coverage.provider: 'v8' in rstest.config.ts.

    Configuration migration

    Update your Jest config file (e.g., jest.config.js or jest.config.ts) to a rstest.config.ts file:

    rstest.config.ts
    import { defineConfig } from '@rstest/core';
    
    export default defineConfig({
      // Fill in by mapping fields from your jest.config.js — see the table below.
    });

    Jest configuration mappings

    When migrating, walk through every field in your jest.config.js and match it against the table below — map it, restructure it, or drop it. Fields not listed here may not map 1:1; verify against the Rstest config reference before dropping them silently.

    Jest configurationRstest equivalentNotes
    preset (e.g. 'ts-jest')RemoveRstest uses swc by default; ts-jest is not needed.
    transformRemoveswc transforms .ts / .tsx / .js / .jsx out of the box. For custom Babel, see Code transformation.
    testEnvironmenttestEnvironment
    testEnvironmentOptionstestEnvironment.optionsFold into the object form: testEnvironment: { name: 'jsdom', options: { ... } }.
    testRegexinclude
    testMatchincludeStrip the <rootDir>/ prefix from each pattern.
    testPathIgnorePatternsexcludeWrap bare /name/ with **, e.g. '/node_modules/' → '**/node_modules/**'.
    transformIgnorePatternsoutput.bundleDependenciesDefault differs by testEnvironment. For 'node': Rstest externalizes node_modules — drop most entries; for ESM packages where Jest needed an exception (e.g. 'node_modules/(?!(lodash-es)/)'), use output.bundleDependencies: ['lodash-es'] to bundle them through swc. For 'jsdom' / 'happy-dom': node_modules is bundled by default — transformIgnorePatterns usually has no equivalent and can be dropped entirely.
    displayNamename
    rootDirroot
    setupFilesAfterEnvsetupFilesRstest's setupFiles runs after the test framework is registered — equivalent to Jest's setupFilesAfterEnv (not Jest's plain setupFiles). Strip the <rootDir>/ prefix. Merge any Jest setupFiles entries here too; there is no separate "before framework" hook.
    globalSetupglobalSetupRstest calls setup with no arguments — if your Jest setup reads (globalConfig, projectConfig), rewrite without them. As in Jest, process.env mutations made here propagate to every test worker.
    globalTeardownglobalSetupNo separate field. Rewrite the file to globalSetup's format (see above) — a bare export default async function teardown() from Jest would run at setup, not after tests.
    verbosereporters: 'verbose'No verbose boolean — use the verbose reporter.
    reportersreportersString values must be built-in names. For third-party reporters (e.g. jest-junit), import the reporter class and pass the instance.
    injectGlobalsglobalsJest defaults to true; Rstest's globals defaults to false. If your tests rely on bare describe / test / expect without imports, set globals: true and add @rstest/core/globals to compilerOptions.types in tsconfig.json.
    moduleNameMapperresolve.aliasresolve.alias is string-prefix only. Rewrite prefix mappings: '^@/(.*)$': '<rootDir>/src/$1' → resolve: { alias: { '@': './src' } }. For TypeScript projects, prefer compilerOptions.paths in tsconfig.json — Rstest reads it automatically. Regex/asset stubs (e.g. '\\.(css|svg)$': 'identity-obj-proxy') have no direct equivalent; most are unnecessary because Rstest handles CSS/assets natively.
    maxWorkerspool.maxWorkers
    testTimeouttestTimeoutFor per-test overrides, replace jest.setTimeout(n) with rs.setConfig({ testTimeout: n }).
    slowTestThresholdslowTestThresholdJest measures in seconds (default 5); Rstest measures in milliseconds (default 300). Multiply Jest values by 1000.
    openHandlesTimeoutteardownTimeoutRstest force exits after the timeout; Jest only prints a warning.
    forceExitteardownTimeout: 0Exit immediately after tests, global teardown, and reporters finish.
    detectOpenHandlesNo exact equivalent; consider detectAsyncLeaks for test-file async leak debuggingNot a 1:1 mapping. detectAsyncLeaks fails test files with active async resources, but these leaks do not block process exit. Use teardownTimeout to stop a run from hanging because of handles left open by reporters, plugins, or config.
    fakeTimersrs.useFakeTimersNo config field. Call rs.useFakeTimers(opts) inside a setupFiles module or per-test; pair with rs.useRealTimers() to restore.
    bailbail
    clearMocksclearMocks
    resetMocksresetMocks
    restoreMocksrestoreMocks
    snapshotFormatsnapshotFormat
    snapshotResolverresolveSnapshotPathRstest takes a function, not a module path.
    snapshotSerializersexpect.addSnapshotSerializerNo config field. In a setupFiles module, import each serializer and call expect.addSnapshotSerializer(serializer).
    cacheDirectoryRemoveNot supported. Rstest manages build caching internally via Rsbuild.
    collectCoveragecoverage.enabled
    collectCoverageFromcoverage.include
    coverageDirectorycoverage.reportsDirectory
    coverageProvidercoverage.providerRstest supports 'istanbul' (default) and 'v8'. Use coverage.provider: 'v8' for tests that need V8 coverage. 'babel' should be replaced with 'istanbul'.
    coveragePathIgnorePatternscoverage.exclude
    coverageThresholdcoverage.thresholds
    projectsprojectsJest's inline project shape differs — review before porting.

    For more details, please refer to the Configuration section.

    Inject globals

    Rstest does not mount the test APIs (e.g., describe, expect, it, test) to the global object by default, which is different from Jest.

    If you want to continue using the global test APIs, you can enable the globals option in your rstest.config.ts file:

    rstest.config.ts
    import { defineConfig } from '@rstest/core';
    
    export default defineConfig({
      globals: true,
    });

    To enable TypeScript to properly recognize the global APIs, add the @rstest/core/globals type declaration in your tsconfig.json:

    tsconfig.json
    {
      "compilerOptions": {
        "types": ["@rstest/core/globals"]
      }
    }

    File-level environment comments

    If your Jest tests use file-level environment comments, Rstest recognizes Jest environment comments during migration:

    /**
     * @jest-environment jsdom
     * @jest-environment-options { "url": "https://example.com/" }
     */

    You can keep these comments as-is or rename them to @rstest-environment / @rstest-environment-options. The options value must be a single-line JSON object. Supported environments are node, jsdom, and happy-dom.

    Dependency export conditions

    By default, Rstest enables the development export condition when bundling dependencies, while Jest does not. After migrating, a dependency may therefore load a different entry from its package.json exports, even though both runners default NODE_ENV to 'test'.

    For example, Emotion disables its speedy style insertion in development builds to support style debugging and source maps. This creates more <style> elements and can slow down style-heavy jsdom tests.

    If this difference causes a regression in your jsdom tests, use resolve.byDependency through tools.rspack to omit development for ESM and CommonJS dependencies:

    rstest.config.ts
    import { defineConfig } from '@rstest/core';
    
    export default defineConfig({
      testEnvironment: 'jsdom',
      tools: {
        rspack: {
          resolve: {
            byDependency: {
              esm: {
                conditionNames: ['browser', 'import', 'module', 'webpack', 'node'],
              },
              commonjs: {
                conditionNames: ['browser', 'require', 'module', 'webpack', 'node'],
              },
            },
          },
        },
      },
    });

    The browser condition is needed for DOM environments such as jsdom and happy-dom. For the same issue in the node environment, use testEnvironment: 'node' and remove browser from both lists.

    These lists preserve the distinction between import and require and leave other dependency types, such as CSS imports, unchanged. Do not add '...': it would restore the default conditions, including development. If your project uses custom export conditions, add them to the corresponding lists.

    This configuration addresses the development export difference; it does not reproduce all of Jest's resolution behavior. It keeps Rspack's module and webpack conditions, does not enable the production condition, and leaves NODE_ENV unchanged. Dependencies may lose checks or warnings provided only by their development exports, so apply it when needed rather than to every migrated project.

    Code transformation

    Unlike Jest's babel-jest, Rstest transforms code with SWC by default. Most projects need no extra transform config; customize SWC options through tools.swc when needed.

    Jest itself gets module resolution and transformation from moduleNameMapper and transform, rather than from tsconfig.json. If you use ts-jest, do not assume that its TypeScript transform settings carry over: Rstest automatically applies compilerOptions.paths for resolution, while transformation settings, such as decorator syntax or output-target requirements, should be reviewed and configured through Rstest when needed. An adapter can inherit or infer additional settings, so refer to the documentation for the adapter you use. See source.tsconfigPath.

    Rstest transforms files that are part of its bundle graph. If your project previously relied on ts-jest runtime transforms, see Code outside the bundle graph uses native Node.js behavior.

    export default {
    -  transform: {
    -    '^.+\\.(t|j)sx?$': ['@swc/jest', {}],
    -  },
    +  tools: {
    +    swc: {}
    +  }
    }

    If you use custom Babel plugins or presets, add Rsbuild's Babel plugin:

    rstest.config.ts
    import { pluginBabel } from '@rsbuild/plugin-babel';
    import { defineConfig } from '@rstest/core';
    
    export default defineConfig({
      plugins: [pluginBabel()],
    });

    Environment variables

    Rstest mirrors Jest's two main injected variables under different names:

    JestRstestNotes
    JEST_WORKER_IDRSTEST_WORKER_IDSame semantics — a stringified integer, unique among workers active at the same time. Use it to isolate per-worker DBs / ports / temp dirs. See RSTEST_WORKER_ID.
    NODE_ENVNODE_ENVBoth default to 'test' when not set.

    Replace any references in tests, fixtures, or setupFiles:

    - const dbName = `myapp_test_${process.env.JEST_WORKER_ID}`;
    + const dbName = `myapp_test_${process.env.RSTEST_WORKER_ID}`;

    See Environment variables for the full list.

    Update test API

    Test API

    Update your test API imports from @jest/globals to @rstest/core:

    - import { describe, expect, it, test } from '@jest/globals';
    + import { describe, expect, it, test, rs } from '@rstest/core';

    Replace jest.<api> calls with rs.<api> (or its longer alias rstest). See Rstest APIs for the full list.

    - const fn = jest.fn();
    + const fn = rs.fn();
    
    fn.mockResolvedValue('foo');

    Manual mocks for npm packages

    Jest automatically uses a manual mock such as __mocks__/zustand.ts in the project root when a test imports zustand. To use the same file in Rstest, call rs.mock('zustand') in the test file. To apply the mock to every test file, register it once in a file listed in setupFiles.

    rstest.setup.ts
    import { rs } from '@rstest/core';
    
    rs.mock('zustand');

    Loading actual modules (requireActual)

    In Jest, jest.requireActual() synchronously loads the unmocked implementation in factories and tests; in Rstest, hoisted rs.mock() factories must be synchronous, so use a static import with with { rstest: 'importActual' } (use rs.importActual in async tests, rs.requireActual for CommonJS modules, and see Mocking):

    + import * as actualUtils from './utils' with { rstest: 'importActual' };
    +
    - jest.mock('./utils', () => ({
    -   ...jest.requireActual('./utils'),
    -   formatDate: jest.fn(() => '2024-01-01'),
    - }));
    + rs.mock('./utils', () => ({
    +   ...actualUtils,
    +   formatDate: rs.fn(() => '2024-01-01'),
    + }));

    Virtual module mocks

    When migrating a Jest virtual mock, declare the module and configure resolve.alias (see Mocking), then remove Jest's third argument:

    - jest.mock('native-runtime', () => ({ platform: 'test' }), {
    -   virtual: true,
    - });
    + rs.mock('native-runtime', () => ({ platform: 'test' }));

    Done callback

    The done callback is not supported in Rstest. Instead, you can return a Promise or use async/await for asynchronous tests.

    - test('async test with done', (done) => {
    + test('async test with done', () => new Promise(done => {
      // ...
      done();
    - });
    + }));

    If you need to handle errors, you can modify it as follows:

    - test('async test with done', (done) => {
    + test('async test with done', () => new Promise((resolve, reject) => {
    +   const done = err => (err ? reject(err) : resolve());
      // ...
      done(error);
    - });
    + }));

    Hooks

    Rstest runs afterEach and afterAll hooks in reverse declaration order by default. Set sequence.hooks: 'list' to run hooks within each suite in declaration order, matching Jest. This matters when one library's cleanup must run before another, such as unmounting components before resetting stores.

    When beforeEach or beforeAll returns a function, Rstest registers it as a cleanup callback to run after the test or suite. Unlike Jest, which ignores hook return values, an arrow function with an implicit return such as beforeEach(() => doSomething()) runs the returned value during teardown if doSomething() returns a function. Wrap the body in braces so nothing is returned:

    - beforeEach(() => doSomething());
    + beforeEach(() => { doSomething(); });

    Snapshot format

    Rstest snapshots use a different key format than Jest. Existing Jest snapshot files will not match Rstest's generated keys on the first run — the snapshot bodies are unchanged, only the key formatting differs.

    Key separator change

    Jest separates the suite name and test name with a space and appends the snapshot label after : . Rstest joins all three with >:

    - overlay should not show a warning when "client.overlay.warnings" is "false": page html 1
    + overlay > should not show a warning when "client.overlay.warnings" is "false" > page html 1

    For the example above, the parts are:

    1. overlay — suite name (describe(...)).
    2. should not show a warning when "client.overlay.warnings" is "false" — test name (it(...) / test(...)).
    3. page html — snapshot label from .toMatchSnapshot('page html').
    4. 1 — snapshot index for that label in the test.

    Updating snapshots

    rstest -u re-records snapshots in Rstest's key format:

    rstest -u                # update everything
    rstest overlay -u        # update a filtered scope

    Reviewing the diff

    Separator-only key renames and key-order changes with no body diff are formatting-only; only body changes under the same key indicate real behavior changes.

    ESM and CJS

    Rstest supports ESM natively (no NODE_OPTIONS=--experimental-vm-modules needed) as well as CommonJS projects.

    ESM vs CJS mocking

    In Rstest, rs.mock() targets the import entry, whereas modules loaded through require() with a separate CommonJS entry need rs.mockRequire() (see Mock CommonJS modules):

    - jest.mock('./math.cjs', () => ({
    + rs.mockRequire('./math.cjs', () => ({
      sum: (a, b) => a + b + 100,
    }));