### Database Setup and Teardown Example Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/config/test/global-setup.mdx An example demonstrating how to set up a MongoDB connection, seed data, and tear down the database using global setup functions. Ensure the MongoDB URI is set in your environment variables. ```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: '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'); } } ``` ```typescript import { defineConfig } from '@rstest/core'; export default defineConfig({ globalSetup: ['./db-setup.ts'], include: ['**/*.test.ts'], }); ``` -------------------------------- ### Run Example Tests Source: https://github.com/web-infra-dev/rstest/blob/main/CLAUDE.md Executes tests specifically for the examples within the project. ```bash pnpm test:examples ``` -------------------------------- ### Global Setup with Named Functions Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/config/test/global-setup.mdx Implement global setup and teardown using exported async functions named 'setup' and 'teardown'. This is the recommended approach for managing test environment initialization and cleanup. ```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(); } ``` -------------------------------- ### Set up Rstest Prompt for AI Agents Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/guide/start/ai.mdx Use this prompt to guide an AI agent in setting up Rstest for a new project. It directs the agent to follow specific instructions for installation. ```markdown Set up Rstest in this project by following the instructions here: https://rstest.rs/guide/start/agent-install.md ``` -------------------------------- ### Install Rstest Rslib Adapter Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/guide/integration/rslib.mdx Install the official adapter to enable Rstest to inherit configurations from your Rslib setup. This command should be run in your project's root directory. ```bash npm install @rstest/adapter-rslib -D ``` -------------------------------- ### GitHub Actions Workflow for Browser Mode Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/guide/advanced/ci.mdx A sample GitHub Actions workflow demonstrating the setup for running Rstest in browser mode. It includes steps for checking out code, setting up Node.js, installing dependencies, installing browser binaries, and running tests. ```yaml jobs: browser-test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: pnpm/action-setup@v4 with: version: 11 - uses: actions/setup-node@v4 with: node-version: 22.12.0 cache: pnpm - run: pnpm install --frozen-lockfile - run: pnpm exec playwright install --with-deps chromium - run: pnpm rstest --browser ``` -------------------------------- ### CI Configuration for Playwright Browsers Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/config/test/browser.mdx Example of a GitHub Actions workflow step to install Playwright browsers. This ensures the necessary browser binaries are available in the CI environment. ```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 ``` -------------------------------- ### Fixture with Setup and Teardown Logic Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/api/runtime-api/test-api/test.mdx Illustrates creating a fixture with asynchronous setup (database connection) and teardown (closing connection) logic. ```typescript import { test } from '@rstest/core'; const testWithDb = test.extend({ db: async ({}, use) => { // setup: create connection const db = await connectTestDb(); await use(db); // teardown: close connection await db.close(); }, }); ``` -------------------------------- ### Install @rstest/adapter-rslib Source: https://github.com/web-infra-dev/rstest/blob/main/packages/adapter-rslib/README.md Install the adapter as a dev dependency. ```bash npm install @rstest/adapter-rslib -D ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/web-infra-dev/rstest/blob/main/examples/react-rspack/README.md Run this command in your project directory to install all necessary npm packages. ```bash npm install ``` -------------------------------- ### Install @rstest/adapter-rsbuild Source: https://github.com/web-infra-dev/rstest/blob/main/packages/adapter-rsbuild/README.md Install the adapter as a development dependency. ```bash npm install @rstest/adapter-rsbuild -D ``` -------------------------------- ### Simple Custom Reporter Example Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/api/javascript-api/reporter.mdx A basic example of a custom reporter that logs test file start, case results, and a summary of the test run. ```APIDOC ## Simple Custom Reporter Example ```ts 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(` 📊 ${passed} passed, ${failed} failed`); }, }; ``` ``` -------------------------------- ### Example Prompt for Agent Skill Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/guide/start/ai.mdx After installing a skill, you can use natural language prompts to trigger its functionality. This example shows how to prompt an agent to migrate a Jest project to Rstest. ```plaintext Help me migrate this Jest project to Rstest ``` -------------------------------- ### Enable and Install PNPM Source: https://github.com/web-infra-dev/rstest/blob/main/CONTRIBUTING.md Enable pnpm with corepack and then install project dependencies. ```bash corepack enable pnpm install ``` -------------------------------- ### Install @rstest/adapter-rspack Source: https://github.com/web-infra-dev/rstest/blob/main/packages/adapter-rspack/README.md Install the adapter as a development dependency. ```bash npm install @rstest/adapter-rspack -D ``` -------------------------------- ### Install Node.js LTS with nvm Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/guide/start/quick-start.mdx Use nvm to install and switch to the Node.js Long Term Support (LTS) version if your current version is too low or not installed. ```bash # Install Node.js LTS nvm install --lts # Switch to Node.js LTS nvm use --lts ``` -------------------------------- ### Global Setup with Default Function Returning Teardown Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/config/test/global-setup.mdx Define a default async function in your setup file that performs initialization and returns another async function for teardown. This pattern is useful for encapsulating setup and cleanup logic. ```typescript // 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(); }; } ``` -------------------------------- ### Install Workspace Dependencies with pnpm Source: https://github.com/web-infra-dev/rstest/blob/main/CLAUDE.md Installs all dependencies for the entire workspace using pnpm. Ensure pnpm is installed and the correct version is used. ```bash pnpm install ``` -------------------------------- ### Example Initialization Output Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/guide/browser-testing/getting-started.mdx This output shows the files created and next steps after running the initialization command for a React project. ```bash 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! ``` -------------------------------- ### Install @rstest/coverage-v8 Source: https://github.com/web-infra-dev/rstest/blob/main/packages/coverage-v8/README.md Install the coverage provider as a development dependency. ```bash npm add @rstest/coverage-v8 -D ``` -------------------------------- ### Start Development Server Source: https://github.com/web-infra-dev/rstest/blob/main/examples/react-rspack/README.md Launches the development server, making your application accessible at http://localhost:8080. ```bash npm run dev ``` -------------------------------- ### Run Setup Before Each Test Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/api/runtime-api/test-api/hooks.mdx Use `beforeEach` to execute setup logic before each individual test within the current suite. The context provided is specific to the test. ```typescript import { beforeEach } from '@rstest/core'; beforeEach(async () => { // Setup logic before each test }); ``` -------------------------------- ### Run Setup Before All Tests Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/api/runtime-api/test-api/hooks.mdx Use `beforeAll` to execute setup logic once before any tests in the current suite begin. It accepts an asynchronous function that receives the suite context. ```typescript import { beforeAll } from '@rstest/core'; beforeAll(async (ctx) => { // Setup logic before all tests // ctx.filepath gives the current test file path }); ``` -------------------------------- ### Browser Mode Configuration Example Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/config/test/browser.mdx Enables Browser Mode and specifies Playwright as the provider. Ensure you have installed the necessary packages and Playwright browsers. ```typescript import { defineConfig } from '@rstest/core'; export default defineConfig({ browser: { enabled: true, provider: 'playwright', }, }); ``` -------------------------------- ### Run Development Server Source: https://github.com/web-infra-dev/rstest/blob/main/packages/browser-ui/AGENTS.md Starts the development server for the @rstest/browser-ui package. ```bash pnpm --filter @rstest/browser-ui dev ``` -------------------------------- ### Install Rstest Adapter for Rsbuild Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/guide/framework/react.mdx Install the Rstest adapter for Rsbuild to enable reusing existing Rsbuild configurations. ```bash npm install @rstest/adapter-rsbuild -D # or yarn add @rstest/adapter-rsbuild -D # or pnpm add @rstest/adapter-rsbuild -D ``` -------------------------------- ### Implement a Custom Reporter Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/api/javascript-api/reporter.mdx Create a custom reporter by implementing the `Reporter` interface. This example shows basic hooks for starting and finishing test files, and the end of the test run. ```typescript import type { Reporter, TestFileResult } from '@rstest/core'; const customReporter: Reporter = { onTestFileStart(test) { console.log(`Starting: ${test.testPath}`); }, onTestFileResult(result) { console.log(`Finished: ${result.testPath}`); }, onTestRunEnd({ results, duration }) { console.log(`All tests completed in ${duration.totalTime}ms`); }, }; ``` -------------------------------- ### Install Browser React Package Source: https://github.com/web-infra-dev/rstest/blob/main/packages/browser-react/README.md Install the @rstest/browser-react package for browser mode testing. Also install testing-library utilities for DOM queries and user events. ```bash npm install @rstest/browser-react # or pnpm add @rstest/browser-react ``` ```bash npm install @testing-library/dom @testing-library/user-event # or pnpm install @testing-library/dom @testing-library/user-event ``` -------------------------------- ### Install Node.js Version Source: https://github.com/web-infra-dev/rstest/blob/main/CONTRIBUTING.md Use fnm or nvm to switch to the Node.js version specified in the project's .nvmrc file. ```bash # with fnm fnm use # with nvm nvm use ``` -------------------------------- ### Locator Usage Example Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/api/runtime-api/browser-mode/locator.mdx This example demonstrates the typical workflow: query elements using page.getBy*, perform interactions like fill and click, and combine with expect.element for assertions. ```APIDOC ## page - **Type:** `BrowserPage` `page` is the starting point in tests: first use `page` to locate elements, then execute interactions and assertions on the returned `Locator`. `page` is a query-only object: it only creates `Locator` instances and does not directly execute interaction actions. ```ts const submitButton = page.getByRole('button', { name: 'Submit' }); ``` The `submitButton` above is a `Locator`. You can continue chaining calls on it (e.g., `.click()`) or pass it to `expect.element(...)` for assertions. ``` ```APIDOC ## Query API All the following APIs return a new `Locator` and support further chaining. ### locator - **Type:** `(selector: string) => Locator` Query elements by CSS selector. ```ts const item = page.locator('.todo-item'); ``` ``` ```APIDOC ### getByRole - **Type:** `(role: string, options?: LocatorGetByRoleOptions) => Locator` Query elements by semantic role. Recommended as the first choice. `LocatorGetByRoleOptions` supports: `name`, `exact`, `checked`, `disabled`, `expanded`, `selected`, `pressed`, `includeHidden`, `level`. ```ts const saveBtn = page.getByRole('button', { name: 'Save' }); ``` ``` ```APIDOC ### getByText - **Type:** `(text: string | RegExp, options?: { exact?: boolean }) => Locator` Query by visible text. ```ts const successMessage = page.getByText('Saved successfully'); ``` ``` ```APIDOC ### getByLabel - **Type:** `(text: string | RegExp, options?: { exact?: boolean }) => Locator` Query by form label. ```ts const emailInput = page.getByLabel('Email'); ``` ``` ```APIDOC ### getByPlaceholder - **Type:** `(text: string | RegExp, options?: { exact?: boolean }) => Locator` Query by placeholder. ```ts const searchInput = page.getByPlaceholder('Search'); ``` ``` ```APIDOC ### getByAltText - **Type:** `(text: string | RegExp, options?: { exact?: boolean }) => Locator` Query by `alt` text. ```ts const avatarImage = page.getByAltText('User avatar'); ``` ``` ```APIDOC ### getByTitle - **Type:** `(text: string | RegExp, options?: { exact?: boolean }) => Locator` Query by `title`. ```ts const helpIcon = page.getByTitle('Help'); ``` ``` ```APIDOC ### getByTestId - **Type:** `(text: string | RegExp) => Locator` Query by test id. ```ts const settingsPanel = page.getByTestId('settings-panel'); ``` ``` -------------------------------- ### Install @rstest/coverage-istanbul Source: https://github.com/web-infra-dev/rstest/blob/main/packages/coverage-istanbul/README.md Install the package as a development dependency using npm. ```bash npm add @rstest/coverage-istanbul -D ``` -------------------------------- ### Install Coverage Provider and Enable Coverage Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/guide/advanced/ci.mdx Install the desired coverage provider and run Rstest with the --coverage flag to collect coverage data. The generated coverage directory can be uploaded for reporting. ```bash pnpm add @rstest/coverage-istanbul -D pnpm rstest --coverage ``` -------------------------------- ### Rstest Development and Build Commands Source: https://github.com/web-infra-dev/rstest/blob/main/website/CLAUDE.md Commands to start the development server, build for production, and preview the production build of Rstest. ```bash pnpm dev # Start dev server pnpm build # Build for production pnpm preview # Preview production build ``` -------------------------------- ### Adapt Testing Library Setup for Rstest Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/guide/migration/vitest.mdx Replace Vitest-specific setup adapters like '@testing-library/jest-dom/vitest' with Rstest's `expect.extend` for global matchers. ```diff - import '@testing-library/jest-dom/vitest'; + import * as jestDomMatchers from '@testing-library/jest-dom/matchers'; + import { expect } from '@rstest/core'; + + expect.extend(jestDomMatchers); ``` -------------------------------- ### Setup Mock Module Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/api/runtime-api/rstest/mock-modules.mdx Sets up a mock implementation for a module using `rs.mock` within a setup file. This mock will be active for subsequent tests unless explicitly unmocked. ```typescript import { rs } from '@rstest/core' ; rs.mock('./src/sum', () => { return { sum: (a: number, b: number) => a + b + 100, }; }); ``` -------------------------------- ### Example AGENTS.md Content for Rstest Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/guide/start/ai.mdx An example of content that can be added to an AGENTS.md file to provide Rstest-specific information to AI agents. ```markdown # AGENTS.md You are an expert in JavaScript, Rspack, Rsbuild, and Rstest. You write maintainable, performant, and accessible tests. ## Tools ### Rstest - Run `npm run test` to run tests (`npx rstest`) - Run `npm run test:watch` to run tests in watch mode (`npx rstest --watch`) ## Docs - Rstest: https://rstest.rs/llms.txt ``` -------------------------------- ### Configure Rstest with Setup Files Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/guide/advanced/troubleshooting.mdx Specify the test setup file in your Rstest configuration. This ensures the registered runtime loader is active during test execution. ```typescript import { defineConfig } from '@rstest/core'; export default defineConfig({ setupFiles: ['./test/rstest.setup.ts'], }); ``` -------------------------------- ### Install migrate-to-rstest Skill Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/guide/migration/jest.mdx Use this command to install the Rstest migration skill for your Coding Agent. This skill can assist with the upgrade process. ```bash npx skills add rstackjs/agent-skills --skill migrate-to-rstest ``` -------------------------------- ### Install Rstest Rspack Adapter Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/guide/integration/rspack.mdx Install the official Rstest adapter for Rspack using your preferred package manager. ```bash npm install @rstest/adapter-rspack -D # or yarn add @rstest/adapter-rspack -D # or pnpm add @rstest/adapter-rspack -D ``` -------------------------------- ### Build All Packages Source: https://github.com/web-infra-dev/rstest/blob/main/CONTRIBUTING.md Build all packages in the monorepo after installing dependencies. ```bash pnpm run build ``` -------------------------------- ### Configure Rstest with Setup Files Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/guide/framework/react.mdx Update the Rstest configuration to include the setup file for Jest-DOM matchers and cleanup. ```typescript import { pluginReact } from '@rsbuild/plugin-react'; import { defineConfig } from '@rstest/core'; export default defineConfig({ plugins: [pluginReact()], testEnvironment: 'happy-dom', setupFiles: ['./rstest.setup.ts'], }); ``` -------------------------------- ### Install Rstest Dependencies for React Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/guide/framework/react.mdx Install core Rstest packages, React plugin, testing utilities, and a DOM simulator for Node-based testing. ```bash npm install @rstest/core @rsbuild/plugin-react @testing-library/react @testing-library/jest-dom happy-dom -D # or yarn add @rstest/core @rsbuild/plugin-react @testing-library/react @testing-library/jest-dom happy-dom -D # or pnpm add @rstest/core @rsbuild/plugin-react @testing-library/react @testing-library/jest-dom happy-dom -D ``` -------------------------------- ### Install Additional Playwright Browsers Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/guide/browser-testing/getting-started.mdx Optional commands to install Firefox, WebKit (Safari), or all available browsers for Playwright testing. ```bash # Install Firefox npx playwright install firefox # Install WebKit (Safari) npx playwright install webkit # Install all browsers npx playwright install ``` -------------------------------- ### Install Rsdoctor Plugin Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/guide/advanced/profiling.mdx Install the Rsdoctor plugin using your package manager. This is a prerequisite for enabling Rsdoctor analysis. ```bash npm install @rsdoctor/rspack-plugin -D # or yarn add @rsdoctor/rspack-plugin -D # or pnpm add @rsdoctor/rspack-plugin -D ``` -------------------------------- ### GitHub Actions Reporter Example Output Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/guide/basic/reporters.mdx Example of the output format used by the GitHub Actions reporter for failed tests, enabling rich error annotations. ```bash ::error file=src/index.ts,line=4,col=17,title=test/index.test.ts > should add two numbers correctly::expected 2 to be 4 ``` -------------------------------- ### Install Runtime Loader for TypeScript Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/guide/advanced/troubleshooting.mdx Install a package that provides a runtime loader hook for TypeScript files. This is necessary before registering it in your test setup. ```bash npm add -D @swc-node/register # or: npm add -D ts-node ``` -------------------------------- ### Configure setupFiles in rstest.config.ts Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/config/test/setup-files.mdx Specify the path to your setup script in the setupFiles array within your rstest.config.ts file. This script will run before each test. ```typescript import { defineConfig } from '@rstest/core'; export default defineConfig({ setupFiles: ['./scripts/rstest.setup.ts'], }); ``` -------------------------------- ### Build for Production Source: https://github.com/web-infra-dev/rstest/blob/main/examples/react-rspack/README.md Compiles and bundles your project for deployment. ```bash npm run build ``` -------------------------------- ### Browser Mode Example: Query, Interaction, and Assertion Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/api/runtime-api/browser-mode/index.mdx This example demonstrates a typical test cycle in Browser Mode: querying an element using `page`, performing an interaction like `fill` or `click` on a `Locator`, and finally asserting its state using `expect.element`. ```typescript import { page } from '@rstest/browser'; import { expect, test } from '@rstest/core'; test('submits form', async () => { await page.getByLabel('Email').fill('dev@rstest.rs'); await page.getByRole('button', { name: 'Submit' }).click(); await expect.element(page.getByText('Done')).toBeVisible(); }); ``` -------------------------------- ### Preview Production Build Source: https://github.com/web-infra-dev/rstest/blob/main/examples/react-rspack/README.md Locally serves the production build to test its behavior before deployment. ```bash npm run preview ``` -------------------------------- ### Example Function to Test Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/guide/start/quick-start.mdx A simple function that returns a string, used for demonstrating test writing. ```typescript export const sayHi = () => 'hi'; ``` -------------------------------- ### Basic Reporter Configuration via CLI Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/config/test/reporters.mdx Demonstrates how to specify a single reporter using the CLI command. ```bash npx rstest --reporters=default ``` -------------------------------- ### Run CPU Benchmarks Source: https://github.com/web-infra-dev/rstest/blob/main/CLAUDE.md Initiates CPU performance benchmarks for the project. ```bash pnpm bench:cpu ``` -------------------------------- ### Rstest Init CLI Options Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/guide/basic/cli.mdx Details the flags for the `rstest init` command, primarily focusing on skipping interactive setup with the `--yes` flag. ```bash rstest init --yes ``` -------------------------------- ### Initialize rstest Configuration Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/guide/basic/cli.mdx Create starter configuration files for supported project types using the rstest init command. This command helps set up rstest for your project. ```bash npx rstest init ``` -------------------------------- ### Initialize Browser Project Configuration with Defaults Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/guide/basic/cli.mdx Initialize rstest configuration for a browser project, skipping the interactive prompt by using the --yes flag. This applies the default setup automatically. ```bash npx rstest init browser --yes ``` -------------------------------- ### Install Rstest Browser Mode and Playwright Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/guide/browser-testing/getting-started.mdx Install the necessary Rstest packages and the Playwright browser driver. This command installs the core package, browser support, and the Chromium browser. ```bash npx playwright install chromium ``` -------------------------------- ### Install Browser Mode Dependencies Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/config/test/browser.mdx To use Browser Mode, install the `@rstest/browser` package and Playwright browsers. This snippet shows the necessary npm command and Playwright installation command. ```bash npm add @rstest/browser -D npx playwright install chromium ``` -------------------------------- ### Initialize Browser Mode Tests Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/guide/browser-testing/getting-started.mdx Use this command for automatic configuration and setup of Browser Mode tests. It detects project specifics and generates necessary files and scripts. ```bash pnpm dlx @rstest/core init browser ``` ```bash npx @rstest/core init browser --yes ``` -------------------------------- ### Install Rstest Core Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/guide/start/quick-start.mdx Install the Rstest core package as a development dependency using your preferred package manager. ```bash npm install @rstest/core -D ``` -------------------------------- ### Configure Global Setup in rstest.config.ts Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/config/test/global-setup.mdx Specify one or more files for global setup in your Rstest configuration. These files will be executed before all tests. ```typescript import { defineConfig } from '@rstest/core'; export default defineConfig({ globalSetup: ['./global-setup.ts'], // or multiple files globalSetup: ['./setup-db.ts', './setup-server.ts'], // your other config... }); ``` -------------------------------- ### Markdown Reporter Output Example (All Pass) Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/guide/basic/reporters.mdx An example of the Markdown reporter's output when all tests pass, including a summary section. ```markdown ## Summary ```json { "status": "pass", "counts": { "testFiles": 2, "failedFiles": 0, "tests": 14, "failedTests": 0, "passedTests": 13, "skippedTests": 1, "todoTests": 0 } } ``` ## Failures No test failures reported. Note: all tests passed. Lists omitted for brevity. ``` -------------------------------- ### Create New Rslib Project with Rstest Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/guide/integration/rslib.mdx Use this command to scaffold a new Rslib project with Rstest pre-configured. The `--tools rstest` flag ensures Rstest is included from the start. ```bash npx create-rslib --template react-ts --tools rstest --dir my-project ``` -------------------------------- ### Install Playwright Browsers Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/config/test/browser.mdx Commands to install specific Playwright browsers or all available browsers. This is required before running tests with a chosen browser type. ```bash # Install chromium npx playwright install chromium # Install Firefox npx playwright install firefox # Install WebKit npx playwright install webkit # Install all browsers npx playwright install ``` -------------------------------- ### Typical Locator Workflow Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/api/runtime-api/browser-mode/locator.mdx Demonstrates querying elements, performing interactions, and asserting their state using the Locator API and expect.element. ```typescript import { page } from '@rstest/browser'; import { expect, test } from '@rstest/core'; test('interacts with a form using locator', async () => { await page.getByLabel('Username').fill('alice'); await page.getByLabel('Password').fill('secret123'); await page.getByRole('button', { name: 'Login' }).click(); await expect.element(page.getByLabel('Username')).toHaveValue('alice'); }); ``` -------------------------------- ### Markdown Reporter Output Example (With Failures) Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/guide/basic/reporters.mdx An example of the Markdown reporter's output when tests fail, showing summary and failure details. ```markdown ## Summary ```json { "status": "fail", "counts": { "testFiles": 1, "failedFiles": 1, "tests": 1, "failedTests": 1, "passedTests": 0, "skippedTests": 0, "todoTests": 0 } } ``` ## Failures ### [F01] fixtures/agent-md/index.test.ts :: agent-md > fails with diff details: ```json { "testPath": "fixtures/agent-md/index.test.ts", "fullName": "agent-md > fails with diff", "status": "fail" } ``` diff: ```diff - Expected + Received - 3 + 2 ``` ``` -------------------------------- ### File Output Reporter Example Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/api/javascript-api/reporter.mdx An example of a custom reporter that writes test results to a JSON file upon completion of the test run. ```APIDOC ## File Output Reporter Example ```ts import { writeFileSync } from 'node:fs'; import type { Reporter } from '@rstest/core'; const jsonReporter: Reporter = { onTestRunEnd({ results }) { const report = { timestamp: new Date().toISOString(), results: results.map((r) => ({ path: r.testPath, status: r.status, duration: r.duration, errors: r.errors, })), }; writeFileSync('test-report.json', JSON.stringify(report, null, 2)); }, }; ``` ``` -------------------------------- ### Build for Production Source: https://github.com/web-infra-dev/rstest/blob/main/packages/browser-ui/AGENTS.md Builds the @rstest/browser-ui package for production deployment. ```bash pnpm --filter @rstest/browser-ui build ``` -------------------------------- ### Run Memory Benchmarks Source: https://github.com/web-infra-dev/rstest/blob/main/CLAUDE.md Initiates memory usage benchmarks for the project. ```bash pnpm bench:memory ``` -------------------------------- ### Build and Development Commands Source: https://github.com/web-infra-dev/rstest/blob/main/packages/browser/CLAUDE.md Commands for building the package in production mode or running it in watch mode for development. Also includes a command for type checking. ```bash pnpm --filter @rstest/browser build pnpm --filter @rstest/browser dev # Watch mode pnpm --filter @rstest/browser typecheck ``` -------------------------------- ### CommonJS Module Example Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/config/build/output.mdx Example of a CommonJS module that exports properties and a default function. This code is intended to be imported using ES module syntax. ```typescript Object.defineProperty(exports, '__esModule', { value: true }); const a = require('./a'); exports.a = a.a; exports.default = () => { return `hello ${a.a}`; }; ``` -------------------------------- ### Configure Multi-Framework Projects Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/guide/browser-testing/framework-guides.mdx Define independent test environments for different frameworks within a single project. This example sets up separate configurations for React and Node.js testing. ```typescript import { defineConfig } from '@rstest/core'; export default defineConfig({ projects: [ { name: 'react', include: ['src/react/**/*.test.{ts,tsx}'], browser: { enabled: true, provider: 'playwright', }, }, { name: 'node', include: ['src/utils/**/*.test.ts'], testEnvironment: 'node', }, ], }); ``` -------------------------------- ### Specify Browser Type (Firefox) Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/config/test/browser.mdx Configures Browser Mode to use Firefox. Remember to install the Firefox browser using `npx playwright install firefox`. ```typescript import { defineConfig } from '@rstest/core'; export default defineConfig({ browser: { enabled: true, provider: 'playwright', browser: 'firefox', }, }); ``` -------------------------------- ### Build and Watch Commands Source: https://github.com/web-infra-dev/rstest/blob/main/packages/vscode/CLAUDE.md Commands for building the project with or without sourcemaps, and for enabling watch mode during development. ```bash npm run build # Build with rslib npm run build:local # Build with sourcemaps npm run watch # Watch mode ``` -------------------------------- ### CommonJS TypeScript File Example Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/guide/advanced/troubleshooting.mdx An example of a TypeScript file exporting using CommonJS syntax (`module.exports`). This will cause issues when loaded in a `type: module` context. ```typescript module.exports = { name: 'plugin', }; ``` -------------------------------- ### Using Plain Value Fixtures Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/api/runtime-api/test-api/test.mdx Shows how to define a fixture with a simple, plain value like a base URL, which does not require setup or teardown. ```typescript import { test } from '@rstest/core'; const myTest = test.extend({ baseURL: 'https://api.example.com', }); myTest('uses baseURL', ({ baseURL, expect }) => { expect(baseURL).toBe('https://api.example.com'); }); ``` -------------------------------- ### Rebuild Affected Packages for E2E/Examples Source: https://github.com/web-infra-dev/rstest/blob/main/CLAUDE.md Rebuilds packages that are affected by changes, which is necessary before running E2E tests or examples. This example shows rebuilding the '@rstest/browser' package. ```bash pnpm --filter @rstest/browser build ``` -------------------------------- ### Build and Development Commands for @rstest/adapter-rsbuild Source: https://github.com/web-infra-dev/rstest/blob/main/packages/adapter-rsbuild/AGENTS.md Commands to build the adapter or run it in watch mode for development. ```bash pnpm --filter @rstest/adapter-rsbuild build ``` ```bash pnpm --filter @rstest/adapter-rsbuild dev # Watch mode ``` -------------------------------- ### CLI Examples for Coverage Changed Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/config/test/coverage.mdx Demonstrates various command-line options for controlling test coverage scope, including running changed tests with coverage, and limiting coverage to files changed since specific Git references. ```bash npx rstest run --changed --coverage npx rstest run --coverage.changed npx rstest run --coverage.changed=HEAD~1 npx rstest run --coverage.changed=origin/main ``` -------------------------------- ### Setup Jest-DOM Matchers for React Testing Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/guide/framework/react.mdx Set up custom Jest-DOM matchers and a cleanup function for enhanced DOM assertions in React tests. This setup file should be referenced in your rstest.config.ts. ```typescript import { afterEach, expect } from '@rstest/core'; import { cleanup } from '@testing-library/react'; import * as jestDomMatchers from '@testing-library/jest-dom/matchers'; expect.extend(jestDomMatchers); // Cleanup after each test to prevent test pollution afterEach(() => { cleanup(); }); ``` -------------------------------- ### Build and Development Commands for @rstest/adapter-rspack Source: https://github.com/web-infra-dev/rstest/blob/main/packages/adapter-rspack/AGENTS.md Commands to build the adapter or run it in watch mode for development. ```bash pnpm --filter @rstest/adapter-rspack build ``` ```bash pnpm --filter @rstest/adapter-rspack dev # Watch mode ``` -------------------------------- ### Install Browser Dependencies for CI Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/guide/advanced/ci.mdx In a CI environment, install the Rstest browser package and Playwright with its dependencies to enable browser mode testing. This ensures the necessary browser binaries are available. ```bash pnpm add @rstest/browser playwright -D pnpm exec playwright install --with-deps chromium ``` -------------------------------- ### Build and Development Commands for @rstest/adapter-rslib Source: https://github.com/web-infra-dev/rstest/blob/main/packages/adapter-rslib/CLAUDE.md These commands are used to build, develop (watch mode), typecheck, and test the @rstest/adapter-rslib package using pnpm. ```bash pnpm --filter @rstest/adapter-rslib build ``` ```bash pnpm --filter @rstest/adapter-rslib dev # Watch mode ``` ```bash pnpm --filter @rstest/adapter-rslib typecheck ``` ```bash pnpm --filter @rstest/adapter-rslib test ``` -------------------------------- ### Example Test File with Silent Console Output Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/blog/announcing-0-10.mdx This example demonstrates how 'silent: passed-only' affects console logs. Only 'fail log' will be printed because the 'passes' test will have its 'pass log' discarded. ```typescript import { describe, expect, it } from '@rstest/core'; describe('math', () => { it('passes', () => { console.log('pass log'); expect(1 + 1).toBe(2); }); it('fails', () => { console.log('fail log'); expect(1 + 1).toBe(3); }); }); ``` -------------------------------- ### Build and Watch Commands for @rstest/adapter-rspack Source: https://github.com/web-infra-dev/rstest/blob/main/packages/adapter-rspack/CLAUDE.md Commands to build the adapter package or run it in watch mode for development. ```bash # Build pnpm --filter @rstest/adapter-rspack build pnpm --filter @rstest/adapter-rspack dev # Watch mode ``` -------------------------------- ### Install rstest-debugging Agent Skill Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/guide/advanced/profiling.mdx Install the rstest-debugging skill to systematically debug Rstest performance issues with a Coding Agent. Use this when Rstest is slower than expected or to pinpoint bottlenecks in build startup versus test execution. ```bash npx skills add rstackjs/agent-skills --skill rstest-debugging ``` -------------------------------- ### Initialize Browser Project Configuration Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/guide/basic/cli.mdx Initialize rstest configuration specifically for a browser project. This command sets up the necessary files and settings for browser testing. ```bash npx rstest init browser ``` -------------------------------- ### Install Vue Testing Dependencies Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/guide/framework/vue.mdx Install core Rstest, Vue plugin, Vue test utils, and a DOM simulator like happy-dom for Node-based testing. For Vue JSX, additional Babel and Vue JSX plugins are required. ```bash npm install @rstest/core @rsbuild/plugin-vue @vue/test-utils happy-dom -D ``` ```bash npm install @rsbuild/plugin-babel @rsbuild/plugin-vue-jsx -D ``` -------------------------------- ### Configure SWC Loader Options Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/guide/basic/configure-rstest.mdx Use the `tools.swc` option to configure the `builtin:swc-loader`. This example shows how to set up automatic React runtime and an Emotion plugin. ```typescript import { defineConfig } from '@rsbuild/core'; export default defineConfig({ tools: { swc: { jsc: { transform: { react: { runtime: 'automatic', }, }, experimental: { plugins: [['@swc/plugin-emotion', {}]], }, }, }, }, }); ``` -------------------------------- ### Register Runtime Loader in Test Setup Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/guide/advanced/troubleshooting.mdx Configure your test setup file to import and register a runtime loader for TypeScript. This ensures TypeScript files can be processed before Node.js's native loader applies module system rules. ```typescript import '@swc-node/register'; // or: import 'ts-node/register'; ``` -------------------------------- ### Run Development Server for Specific Package Source: https://github.com/web-infra-dev/rstest/blob/main/CLAUDE.md Starts the development server for a specific package (e.g., '@rstest/core') using pnpm --filter. ```bash pnpm --filter @rstest/core dev ``` -------------------------------- ### Enable Coverage Collection via CLI Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/config/test/coverage.mdx Demonstrates how to enable code coverage collection using the CLI flag. ```bash npx rstest --coverage ``` -------------------------------- ### Configure Provider Options from CLI Source: https://github.com/web-infra-dev/rstest/blob/main/website/docs/en/config/test/browser.mdx Passes nested provider options to the browser provider via the command line interface. This example sets the Playwright launch channel to Chrome. ```bash npx rstest --browser.providerOptions.launch.channel=chrome ```