### Database setup example with globalSetup Source: https://rstest.rs/config/test/global-setup Example of a global setup file that connects to MongoDB, seeds test data, and cleans up in teardown, along with the corresponding rstest.config.ts that references it. ```TypeScript // 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: '[email protected]' }, { name: 'Jane', email: '[email protected]' }, ]); console.log('✓ Database connected and seeded'); } export async function teardown() { if (dbConnection) { await dbConnection.dropDatabase(); await dbConnection.client.close(); console.log('✓ Database cleaned up'); } } ``` ```TypeScript import { defineConfig } from '@rstest/core'; export default defineConfig({ globalSetup: ['./db-setup.ts'], include: ['**/*.test.ts'], }); ``` -------------------------------- ### Configure setupFiles in rstest.config.ts Source: https://rstest.rs/config/test/setup-files Use this configuration to specify setup modules that run before each test file. The example sets setupFiles to ['./scripts/rstest.setup.ts']. ```TypeScript import { defineConfig } from '@rstest/core'; export default defineConfig({ setupFiles: ['./scripts/rstest.setup.ts'], }); ``` -------------------------------- ### rs.mock: Setup file for unmock example Source: https://rstest.rs/api/runtime-api/rstest/mock-modules This setup file (rstest.setup.ts) registers a mock for './src/sum' using rs.mock, which returns a sum function that adds 100 to the result. This mock is executed in setupFiles and is later cancelled by rs.unmock in the test file. ```typescript import { rs } from '@rstest/core' ; rs.mock('./src/sum', () => { return { sum: (a: number, b: number) => a + b + 100, }; }); ``` -------------------------------- ### Install dependencies with bun Source: https://rstest.rs/guide/framework/react Installs the same dependencies using bun. ```bash bun add @rstest/core @rsbuild/plugin-react @testing-library/react @testing-library/jest-dom happy-dom -D ``` -------------------------------- ### Install @rstest/adapter-rslib with deno Source: https://rstest.rs/integration/rslib/ Install the adapter as a dev dependency using deno. ```bash deno add npm:@rstest/adapter-rslib -D ``` -------------------------------- ### global-setup.ts: Start and stop HTTP server for remote Source: https://rstest.rs/guide/advanced/module-federation Defines setup and teardown functions to start an HTTP server on port 3001 before tests and close it after. Used with globalSetup in Rstest config to ensure the remote is reachable before test workers import the host. ```typescript import { createServer, type Server } from 'node:http'; let server: Server; export async function setup() { server = createServer(/* serve the remote's build output */); await new Promise((resolve) => server.listen(3001, resolve)); } export async function teardown() { await new Promise((resolve) => server.close(() => resolve())); } ``` -------------------------------- ### Install identity-obj-proxy with deno Source: https://rstest.rs/guide/basic/css Install identity-obj-proxy as a dev dependency using deno. ```bash deno add npm:identity-obj-proxy -D ``` -------------------------------- ### Install @rstest/adapter-rspack with deno Source: https://rstest.rs/integration/rspack/ Install the adapter as a dev dependency using deno. ```bash deno add npm:@rstest/adapter-rspack -D ``` -------------------------------- ### Install identity-obj-proxy with bun Source: https://rstest.rs/guide/basic/css Install identity-obj-proxy as a dev dependency using bun. ```bash bun add identity-obj-proxy -D ``` -------------------------------- ### Install @rstest/adapter-rslib with bun Source: https://rstest.rs/integration/rslib/ Install the adapter as a dev dependency using bun. ```bash bun add @rstest/adapter-rslib -D ``` -------------------------------- ### Install @rstest/adapter-rspack with bun Source: https://rstest.rs/integration/rspack/ Install the adapter as a dev dependency using bun. ```bash bun add @rstest/adapter-rspack -D ``` -------------------------------- ### Install dependencies with pnpm Source: https://rstest.rs/guide/framework/react Installs the same dependencies using pnpm. ```bash pnpm add @rstest/core @rsbuild/plugin-react @testing-library/react @testing-library/jest-dom happy-dom -D ``` -------------------------------- ### Install @rstest/adapter-rsbuild with deno Source: https://rstest.rs/integration/rsbuild/ Install the Rsbuild adapter as a dev dependency using deno. ```bash deno add npm:@rstest/adapter-rsbuild -D ``` -------------------------------- ### Install @rslint/core with deno Source: https://rstest.rs/integration/rslint Install the @rslint/core package as a dev dependency using deno. ```bash deno add npm:@rslint/core -D ``` -------------------------------- ### Install dependencies with deno Source: https://rstest.rs/guide/framework/react Installs the same dependencies using deno with npm: prefixes. ```bash deno add npm:@rstest/core npm:@rsbuild/plugin-react npm:@testing-library/react npm:@testing-library/jest-dom npm:happy-dom -D ``` -------------------------------- ### Install dependencies with yarn Source: https://rstest.rs/guide/framework/react Installs the same dependencies using yarn. ```bash yarn add @rstest/core @rsbuild/plugin-react @testing-library/react @testing-library/jest-dom happy-dom -D ``` -------------------------------- ### Install @rstest/core with deno Source: https://rstest.rs/guide/migration/jest Install Rstest as a development dependency using deno. ```bash deno add npm:@rstest/core -D ``` -------------------------------- ### Install @rstest/adapter-rsbuild with bun Source: https://rstest.rs/integration/rsbuild/ Install the Rsbuild adapter as a dev dependency using bun. ```bash bun add @rstest/adapter-rsbuild -D ``` -------------------------------- ### Install @rstest/adapter-rslib with pnpm Source: https://rstest.rs/integration/rslib/ Install the adapter as a dev dependency using pnpm. ```bash pnpm add @rstest/adapter-rslib -D ``` -------------------------------- ### Install identity-obj-proxy with pnpm Source: https://rstest.rs/guide/basic/css Install identity-obj-proxy as a dev dependency using pnpm. ```bash pnpm add identity-obj-proxy -D ``` -------------------------------- ### Install @rstest/core with bun Source: https://rstest.rs/guide/migration/jest Install Rstest as a development dependency using bun. ```bash bun add @rstest/core -D ``` -------------------------------- ### Install @rslint/core with bun Source: https://rstest.rs/integration/rslint Install the @rslint/core package as a dev dependency using bun. ```bash bun add @rslint/core -D ``` -------------------------------- ### Install other Playwright browsers Source: https://rstest.rs/guide/browser-testing/getting-started Install Firefox, WebKit, or all browsers. Comments show each option. ```bash # Install Firefox npx playwright install firefox # Install WebKit (Safari) npx playwright install webkit # Install all browsers npx playwright install ``` -------------------------------- ### Install identity-obj-proxy with npm Source: https://rstest.rs/guide/basic/css Install identity-obj-proxy as a dev dependency using npm. ```bash npm add identity-obj-proxy -D ``` -------------------------------- ### Install @rstest/adapter-rslib with npm Source: https://rstest.rs/integration/rslib/ Install the adapter as a dev dependency using npm. ```bash npm add @rstest/adapter-rslib -D ``` -------------------------------- ### Install identity-obj-proxy with yarn Source: https://rstest.rs/guide/basic/css Install identity-obj-proxy as a dev dependency using yarn. ```bash yarn add identity-obj-proxy -D ``` -------------------------------- ### Install happy-dom with bun Source: https://rstest.rs/config/test/test-environment Install the happy-dom package as a dev dependency using bun. ```bash bun add happy-dom -D ``` -------------------------------- ### beforeEach basic setup Source: https://rstest.rs/api/runtime-api/test-api/hooks Runs setup logic before each test in the current suite. The callback can be async. ```typescript import { beforeEach } from '@rstest/core'; beforeEach(async () => { // Setup logic before each test }); ``` -------------------------------- ### runCLI() usage example Source: https://rstest.rs/api/javascript-api/instance Runs the Rstest CLI in the current process. It parses 'argv', sets 'process.exitCode', and installs signal handling. The 'argv' matches Node.js 'process.argv' shape; the first two entries are ignored, and command, filters, and flags start at index 2. ```javascript import { runCLI } from '@rstest/core/api'; runCLI({ argv: [...process.argv.slice(0, 2), 'run', 'src/foo.test.ts', '--update'], }); ``` -------------------------------- ### Example output for a React project Source: https://rstest.rs/guide/browser-testing/getting-started Shows the expected output when running the initialization command on a React project. It lists detected settings, created files, and next steps. ```text Set up Rstest browser mode Detecting project... ✓ Found React 19.0.0 ✓ Using playwright as browser provider ✓ Test directory: tests/ Created files: - rstest.browser.config.ts - tests/Counter.jsx - tests/Counter.test.jsx - Updated package.json Next steps: pnpm i pnpm dlx playwright install --with-deps pnpm run test:browser └ Done! ``` -------------------------------- ### Prompt to trigger migrate-to-rstest skill Source: https://rstest.rs/guide/start/ai Example natural language prompt to trigger the installed migrate-to-rstest skill after installation. ```text Help me migrate this Playwright Test project to @rstest/playwright ``` -------------------------------- ### Global setup file with named functions Source: https://rstest.rs/config/test/global-setup Recommended format for a global setup file, exporting async setup and teardown functions. Either export can be omitted, but a file exporting neither and no default function fails the run. ```TypeScript // 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(); } ``` -------------------------------- ### rs.mocked usage example Source: https://rstest.rs/api/runtime-api/rstest/mock-functions Example of using rs.mocked to get type hints for a mocked module. After mocking with rs.mock, rs.mocked returns the same object but with TypeScript types that include mock methods. ```typescript import { myModule } from './myModule'; rs.mock('./myModule', { spy: true }); // TypeScript now knows myModule.method is a MockInstance const mockedModule = rs.mocked(myModule); mockedModule.method.mockReturnValue('mocked'); ``` -------------------------------- ### Example projects configuration with defineConfig and defineInlineProject Source: https://rstest.rs/config/test/projects Shows how to define multiple test projects using directories, glob patterns, config files, and inline project configs. Inline projects require a name, and use defineInlineProject. ```typescript import { defineConfig, defineInlineProject } from '@rstest/core'; export default defineConfig({ projects: [ // A monorepo: each package directory is a project 'packages/*', // All projects under the apps directory that provide an rstest config file 'apps/**/rstest.config.ts', // A specific project directory '/services/auth', // A specific project's config file './projects/web/rstest.config.ts', // inline project configs defineInlineProject({ name: 'node', include: ['tests/node/**/*.{test,spec}.{js,cjs,mjs,ts,tsx}'], }), defineInlineProject({ name: 'react', include: ['tests/react/**/*.{test,spec}.{js,cjs,mjs,ts,tsx}'], testEnvironment: 'jsdom', }), ], }); ``` -------------------------------- ### Install coverage provider and run tests with coverage Source: https://rstest.rs/guide/advanced/ci Install the default Istanbul coverage provider and run tests with coverage enabled using the --coverage flag. ```bash pnpm add @rstest/coverage-istanbul -D pnpm rstest --coverage ``` -------------------------------- ### Run rstest init Source: https://rstest.rs/guide/basic/cli Creates starter configuration for supported project types. Run without arguments to use the default initializer. ```bash npx rstest init ``` -------------------------------- ### Assertion error with default truncateThreshold (40) Source: https://rstest.rs/config/test/chai-config Example output showing how long arrays or objects get truncated with the default threshold of 40 characters. ```text AssertionError: expected [ 1, 2, [ 3, [ 4 ], ... ] ] to strictly equal [ 1, 2, [ 3 ] ] ``` -------------------------------- ### rstest.run() example Source: https://rstest.rs/api/javascript-api/instance Shows how to create an Rstest instance and run a test cycle with filters, then log the status and summary. ```javascript 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); ``` -------------------------------- ### Simple custom reporter Source: https://rstest.rs/api/javascript-api/reporter An example of a simple custom reporter that logs test file starts, test case results, and a summary at the end of the test run. ```APIDOC ## Simple custom reporter ### Description An example of a simple custom reporter that logs test file starts, test case results, and a summary at the end of the test run. ### Code Example ```typescript import type { Reporter } from '@rstest/core'; const simpleReporter: Reporter = { onTestFileStart(test) { console.log(`📁 ${test.testPath}`); }, onTestCaseResult(result) { const status = result.status === 'pass' ? '✅' : '❌'; console.log(`${status} ${result.name}`); }, onTestRunEnd({ results }) { const passed = results.filter((r) => r.status === 'pass').length; const failed = results.filter((r) => r.status === 'fail').length; console.log(`\n📊 ${passed} passed, ${failed} failed`); }, }; ``` ``` -------------------------------- ### Run rstest init with browser initializer Source: https://rstest.rs/guide/basic/cli Creates starter configuration using the `browser` initializer, which is currently the only available initializer. ```bash npx rstest init browser ``` -------------------------------- ### Define Rstest config with defineConfig in rstest.config.ts Source: https://rstest.rs/guide/basic/configure-rstest Use defineConfig from @rstest/core in a TypeScript configuration file to get type hints and autocompletion. This example sets testEnvironment to 'node'. ```typescript import { defineConfig } from '@rstest/core'; export default defineConfig({ testEnvironment: 'node', }); ``` -------------------------------- ### rs.doMockRequire: mock applied only after execution Source: https://rstest.rs/api/runtime-api/rstest/mock-modules Use rs.doMockRequire to mock a CommonJS module only for subsequent require() calls. The mock is not hoisted, so earlier require() calls load the original module. The example shows that the first require() gets the original sum, and after calling rs.doMockRequire, the next require() gets the mocked sum. ```javascript test('doMockRequire only affects later require calls', () => { const { sum } = require('./math.cjs'); expect(sum(1, 2)).toBe(3); rs.doMockRequire('./math.cjs', () => ({ sum: (a, b) => a + b + 100, })); const { sum: mockedSum } = require('./math.cjs'); expect(mockedSum(1, 2)).toBe(103); }); ``` -------------------------------- ### Run rstest init browser with --yes flag Source: https://rstest.rs/guide/basic/cli Skips the interactive prompt and applies the default setup when initializing with the browser initializer. ```bash npx rstest init browser --yes ``` -------------------------------- ### onTestFinished hook usage Source: https://rstest.rs/api/runtime-api/test-api/hooks Registers a cleanup function that runs after the test finishes, regardless of the test result. This hook is called after afterEach. In the example, it closes a server started in the test. ```typescript import { onTestFinished, test } from '@rstest/core'; test('test server', () => { const server = startServer(); // Register a cleanup function to close the server after the test onTestFinished(() => server.close()); server.listen(3000, () => { console.log('Server is running on port 3000'); }); }); ``` -------------------------------- ### Example: initial run with failures Source: https://rstest.rs/config/test/only-failures Shows the output of a full test run where 2 of 14 test files failed. ```bash npx rstest Test Files 2 failed | 12 passed ``` -------------------------------- ### rstest-plugin.ts: modifyRstestConfig usage Source: https://rstest.rs/config/build/plugins Example of a Rsbuild plugin that uses modifyRstestConfig to set the include pattern for test discovery. The plugin must be registered during the setup phase; registering later is too late. ```typescript import type { RsbuildPlugin } from '@rsbuild/core'; import type { RstestExposeAPI } from '@rstest/core'; export const myPlugin = (): RsbuildPlugin => ({ name: 'modify-rstest-config', setup(api) { const rstestApi = api.useExposed('rstest'); rstestApi?.modifyRstestConfig((config) => { config.include = ['**/*.plugin.test.ts']; }); }, }); ``` -------------------------------- ### Example output with heap usage Source: https://rstest.rs/config/test/log-heap-usage Example output after setting `logHeapUsage` to `true`, showing heap usage for each test file. ```text ✓ test/index.test.ts (2) 11 MB heap used ✓ test/index1.test.ts (2) 11 MB heap used Test Files 2 passed Tests 2 passed | 2 skipped (4) Duration 233ms (build 175ms, tests 58ms) ``` -------------------------------- ### mock.invocationCallOrder - Global call order Source: https://rstest.rs/api/runtime-api/rstest/mock-instance An array of numbers representing the order in which the mock was called, shared across all mocks. The index starts from 1. The example shows the order for two mocks. ```javascript const fn1 = rs.fn(); const fn2 = rs.fn(); fn1(); fn2(); fn1(); console.log(fn1.mock.invocationCallOrder); // [1, 3] console.log(fn2.mock.invocationCallOrder); // [2] ``` -------------------------------- ### expect.getState / expect.setState - Access and modify matcher state Source: https://rstest.rs/api/runtime-api/test-api/expect Gets the current matcher state and sets partial state. The example shows reading currentTestName and updating it, with the console output confirming the change. ```javascript const state = expect.getState(); console.log(state.currentTestName); expect.setState({ currentTestName: 'custom name' }); console.log(expect.getState().currentTestName); // will output 'custom name' ``` -------------------------------- ### Install Node.js LTS via nvm Source: https://rstest.rs/guide/start/quick-start Commands to install and switch to Node.js LTS using nvm. ```bash # Install Node.js LTS nvm install --lts # Switch to Node.js LTS nvm use --lts ``` -------------------------------- ### Debug with pool.execArgv and maxWorkers: 1 Source: https://rstest.rs/config/test/pool Combine `pool.execArgv` with `maxWorkers: 1` to run files one at a time for easier debugging. This example passes `--inspect-brk` to workers, enabling the inspector to break on start. ```TypeScript import { defineConfig } from '@rstest/core'; export default defineConfig({ pool: { maxWorkers: 1, execArgv: ['--inspect-brk'], }, }); ``` -------------------------------- ### Using request fixture for API client Source: https://rstest.rs/guide/basic/e2e-testing Use the request fixture when you only need Playwright's API client and do not need to launch a browser. The example performs a GET request and asserts the response is ok. ```typescript import { expect, test } from '@rstest/playwright'; test('health check', async ({ request }) => { const response = await request.get('http://localhost:3000/health'); expect(response.ok()).toBe(true); }); ``` -------------------------------- ### Enable headless mode in CI Source: https://rstest.rs/config/test/browser Sets `browser.headless` to `true` in `rstest.config.ts` for CI environments. The default is `true` in CI and `false` locally. Includes a GitHub Actions workflow example that installs dependencies and runs tests. ```typescript import { defineConfig } from '@rstest/core'; export default defineConfig({ browser: { enabled: true, provider: 'playwright', headless: true, }, }); ``` ```yaml # .github/workflows/test.yml jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - run: npm install - run: npx playwright install chromium - run: npm test ``` -------------------------------- ### setTestIdAttribute in setup file Source: https://rstest.rs/api/runtime-api/browser-mode/locator Configures setTestIdAttribute in a setup file to apply consistently to all tests. The setup file is referenced in the config via setupFiles. ```typescript import { setTestIdAttribute } from '@rstest/browser'; await setTestIdAttribute('data-qa'); ``` ```typescript export default defineConfig({ setupFiles: ['./rstest.setup.ts'], }); ``` -------------------------------- ### Write first test with @testing-library/react Source: https://rstest.rs/guide/framework/react Creates src/App.test.tsx to render App and assert 'Hello World' is in the document. ```tsx import { expect, test } from '@rstest/core'; import { render, screen } from '@testing-library/react'; import App from './App'; test('renders greeting', () => { render(); expect(screen.getByText('Hello World')).toBeInTheDocument(); }); ``` -------------------------------- ### Install @rstest/coverage-istanbul with deno Source: https://rstest.rs/config/test/coverage Install the Istanbul coverage provider package using deno. ```bash deno add npm:@rstest/coverage-istanbul -D ``` -------------------------------- ### Example: query, interaction, and assertion Source: https://rstest.rs/api/runtime-api/browser-mode/ A complete example showing how to use page to create a Locator, perform actions like fill and click, and assert visibility with expect.element. ```APIDOC ## Example: query, interaction, and assertion ### Description Demonstrates the usage of `page` to create a Locator, perform actions, and assert element state. ### Code Example ```typescript import { page } from '@rstest/browser'; import { expect, test } from '@rstest/core'; test('submits form', async () => { await page.getByLabel('Email').fill('[email protected]'); await page.getByRole('button', { name: 'Submit' }).click(); await expect.element(page.getByText('Done')).toBeVisible(); }); ``` ### Explanation - `page` creates a Locator for the element with label 'Email' and fills it. - `page` creates a Locator for the button with role 'button' and name 'Submit' and clicks it. - `expect.element(locator)` performs a visibility assertion on the Locator for text 'Done'. ``` -------------------------------- ### Create a new Rslib + Rstest project with --tools rstest Source: https://rstest.rs/integration/rslib/ Use this command to scaffold a new project with Rstest and demo tests. Run `npm run test` to execute the tests. ```bash npx create-rslib --template react-ts --tools rstest --dir my-project ``` -------------------------------- ### Install runtime loader for TypeScript require hook Source: https://rstest.rs/guide/debug/troubleshooting Install a runtime loader like @swc-node/register or ts-node to handle CommonJS-style TypeScript files. Rstest does not install these loaders for you. ```bash npm add -D @swc-node/register # or: npm add -D ts-node ``` -------------------------------- ### Create Rstest instance and inspect context Source: https://rstest.rs/api/javascript-api/instance Shows how to create an Rstest instance with a project configuration and then log the context's version, rootPath, and project details. The context is read-only and resolved once at instance creation. ```javascript 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); } ``` -------------------------------- ### Install @rstest/core and @rstest/browser with deno Source: https://rstest.rs/guide/browser-testing/getting-started Install the Rstest core package and Browser Mode support package using deno. Add as dev dependencies. ```bash deno add npm:@rstest/core npm:@rstest/browser -D ``` -------------------------------- ### Install @rstest/adapter-rspack with pnpm Source: https://rstest.rs/integration/rspack/ Install the adapter as a dev dependency using pnpm. ```bash pnpm add @rstest/adapter-rspack -D ``` -------------------------------- ### Install @rstest/adapter-rspack with yarn Source: https://rstest.rs/integration/rspack/ Install the adapter as a dev dependency using yarn. ```bash yarn add @rstest/adapter-rspack -D ``` -------------------------------- ### Install @rstest/adapter-rspack with npm Source: https://rstest.rs/integration/rspack/ Install the adapter as a dev dependency using npm. ```bash npm add @rstest/adapter-rspack -D ``` -------------------------------- ### Boolean option negation examples Source: https://rstest.rs/guide/basic/cli Shows how to use the `--no-