### Example TWD Project Configuration File Source: https://context7.com/brikev/twd-ai/llms.txt An example of the `.claude/twd-patterns.md` file generated by the `/twd:setup` command. It outlines project configuration details and standard test file imports and templates. ```typescript // Example generated .claude/twd-patterns.md content // Project Configuration // - Framework: React // - Vite base path: / // - Dev server port: 5173 // - Entry point: src/main.tsx // Standard imports for all test files: import { twd, userEvent, screenDom, expect } from "twd-js"; import { describe, it, beforeEach, afterEach } from "twd-js/runner"; // Standard beforeEach template: beforeEach(() => { twd.clearRequestMockRules(); twd.clearComponentMocks(); // Store reset if using state management // Auth setup if using auth middleware }); ``` -------------------------------- ### Install twd-cli for CI Source: https://github.com/brikev/twd-ai/blob/main/skills/ci-setup/SKILL.md Installs the `twd-cli` package as a development dependency. This is essential for running TWD tests in a headless CI environment. ```bash npm install --save-dev twd-cli ``` -------------------------------- ### Install Code Coverage Packages for Vite Source: https://github.com/brikev/twd-ai/blob/main/skills/ci-setup/SKILL.md Installs `vite-plugin-istanbul` for code instrumentation and `nyc` for coverage reporting. These are required when code coverage is enabled for Vite projects. ```bash npm install --save-dev vite-plugin-istanbul nyc ``` -------------------------------- ### Install TWD Packages Source: https://github.com/brikev/twd-ai/blob/main/skills/twd/references/setup.md Installs the necessary TWD packages using npm. `twd-js` is for core functionality, and `twd-relay` is for development-time communication, installed as a dev dependency. ```bash npm install twd-js npm install --save-dev twd-relay ``` -------------------------------- ### Configure Entry Point for TWD (Bundled Setup) Source: https://github.com/brikev/twd-ai/blob/main/skills/twd/references/setup.md Configures the application's entry point to load TWD only in development mode. It dynamically imports TWD and sets up tests, and also connects the twd-relay browser client for communication. ```typescript // src/main.ts (or main.tsx) if (import.meta.env.DEV) { const { initTWD } = await import('twd-js/bundled'); const tests = import.meta.glob("./**/*.twd.test.ts"); initTWD(tests, { open: true, position: 'left', serviceWorker: true, serviceWorkerUrl: '/mock-sw.js', }); // Connect twd-relay browser client const { createBrowserClient } = await import('twd-relay/browser'); const client = createBrowserClient({ url: `${window.location.origin}/__twd/ws` }); client.connect(); } ``` -------------------------------- ### Configure CI/CD with GitHub Actions Source: https://context7.com/brikev/twd-ai/llms.txt Provides the setup command and an example YAML configuration for running TWD tests within a GitHub Actions workflow. ```bash /twd:ci-setup ``` ```yaml name: CI - twd tests on: [push] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v5 - run: npm ci - run: npx twd-cli run ``` -------------------------------- ### Generate TWD Configuration Patterns Source: https://github.com/brikev/twd-ai/blob/main/skills/setup/SKILL.md Template for the .claude/twd-patterns.md file. It includes sections for project configuration, relay commands, standard imports, visit paths, and lifecycle hooks for test setup and teardown. ```markdown # TWD Project Patterns ## Project Configuration - **Framework**: FRAMEWORK - **Vite base path**: BASE_PATH - **Dev server port**: PORT - **Entry point**: ENTRY_FILE - **Public folder**: PUBLIC_DIR ### Relay Commands ```bash # Run all tests (default — use this if base path is / and port is 5173) npx twd-relay run # Run all tests (custom config) npx twd-relay run --port PORT --path "BASE_PATH__twd/ws" ``` ## Standard Imports ```typescript import { twd, userEvent, screenDom, expect } from "twd-js"; import { describe, it, beforeEach, afterEach } from "twd-js/runner"; // Project-specific imports go here (added by user) ``` ## Visit Paths All `twd.visit()` calls must include the base path prefix: ```typescript await twd.visit("BASE_PATH"); await twd.visit("BASE_PATHsome-page"); ``` ## Standard beforeEach / afterEach ```typescript beforeEach(() => { twd.clearRequestMockRules(); twd.clearComponentMocks(); Sinon.restore(); // STORE_RESET (if applicable — e.g., useStore.setState(initialState), store.$reset()) // AUTH_SETUP (if applicable) // THIRD_PARTY_STUBS (if applicable — e.g., Sinon.stub(authModule, 'useAuth').returns(...)) }); afterEach(() => { twd.clearRequestMockRules(); }); ``` ``` -------------------------------- ### String URL Matching for GET Requests Source: https://github.com/brikev/twd-ai/blob/main/skills/twd/references/test-writing.md Demonstrates mocking GET requests using string URL matching. This method is preferred and automatically handles path boundaries. It shows examples for specific user retrieval, dynamic IDs, and external API calls. ```typescript // Mock GET — string match handles path boundaries automatically await twd.mockRequest("getUser", { method: "GET", url: "/api/user/123", response: { id: 123, name: "John Doe" }, status: 200, }); // For dynamic IDs, hardcode the mock value await twd.mockRequest("getUser", { method: "GET", url: "/api/users/456", response: { id: 456, name: "Test User" }, }); // For external APIs with full domain await twd.mockRequest("searchShows", { method: "GET", url: "https://api.tvmaze.com/search/shows?q=", response: [{ show: { name: "Friends" } }], }); ``` -------------------------------- ### Setup TWD Configuration Source: https://github.com/brikev/twd-ai/blob/main/README.md Initializes the TWD environment by detecting project configuration and generating the .claude/twd-patterns.md file. ```bash /twd:setup ``` -------------------------------- ### Configure Vite for Code Coverage Source: https://github.com/brikev/twd-ai/blob/main/skills/twd/references/ci.md Setup instructions for vite-plugin-istanbul to instrument source code for coverage collection. Includes installation commands and the Vite configuration snippet. ```bash npm install --save-dev vite-plugin-istanbul nyc ``` ```typescript import istanbul from "vite-plugin-istanbul"; export default defineConfig({ plugins: [ istanbul({ include: "src/*", exclude: ["node_modules", "**/*.twd.test.ts"], extension: ['.ts', '.tsx'], requireEnv: !process.env.CI, }), ], }); ``` -------------------------------- ### TWD CI Configuration File Source: https://github.com/brikev/twd-ai/blob/main/skills/ci-setup/SKILL.md Example `twd.config.json` file for configuring TWD CLI. It includes settings for URL, timeout, coverage options, and Puppeteer arguments. The 'url' field should reflect the detected development server port. ```json { "url": "http://localhost:5173", "timeout": 10000, "coverage": true, "coverageDir": "./coverage", "nycOutputDir": "./.nyc_output", "headless": true, "puppeteerArgs": ["--no-sandbox", "--disable-setuid-sandbox"] } ``` -------------------------------- ### Write a First TWD Test Source: https://github.com/brikev/twd-ai/blob/main/skills/twd/references/setup.md Demonstrates how to write a basic TWD test case using `twd-js` and its runner. It includes visiting a route, selecting a DOM element by its role, and asserting its visibility. ```typescript // src/twd-tests/app.twd.test.ts import { twd, screenDom } from "twd-js"; import { describe, it } from "twd-js/runner"; describe("App", () => { it("should render the main heading", async () => { await twd.visit("/"); const heading = screenDom.getByRole("heading", { level: 1 }); twd.should(heading, "be.visible"); }); }); ``` -------------------------------- ### Configure CI/CD for TWD Source: https://github.com/brikev/twd-ai/blob/main/README.md Automates the setup of CI/CD pipelines, including installing the CLI and generating GitHub Actions workflows for headless testing. ```bash /twd:ci-setup ``` -------------------------------- ### Basic CI Workflow (YAML) Source: https://github.com/brikev/twd-ai/blob/main/skills/twd/references/ci.md This GitHub Actions workflow automates the CI process for the TWD AI project without code coverage. It checks out the repository, sets up Node.js, installs dependencies, initializes a mock service worker, starts the Vite development server, caches Puppeteer browsers, installs Chrome for Puppeteer, and runs TWD tests. ```yaml name: CI - twd tests on: push: branches: [ main ] pull_request: branches: [ main ] jobs: test: runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v5 - name: Setup Node.js uses: actions/setup-node@v5 with: node-version: 24 cache: 'npm' - name: Install dependencies run: npm ci - name: Install mock service worker run: npx twd-js init public --save - name: Start Vite dev server run: | nohup npm run dev > vite.log 2>&1 & npx wait-on http://localhost:5173 - name: Cache Puppeteer browsers uses: actions/cache@v4 with: path: ~/.cache/puppeteer key: ${{ runner.os }}-puppeteer-${{ hashFiles('package-lock.json') }} restore-keys: | ${{ runner.os }}-puppeteer- - name: Install Chrome for Puppeteer run: npx puppeteer browsers install chrome - name: Run TWD tests run: npx twd-cli run ``` -------------------------------- ### Configure Entry Point for TWD (Solid.js) Source: https://github.com/brikev/twd-ai/blob/main/skills/twd/references/setup.md Integrates TWD into a Solid.js application's entry point for development. It initializes TWD with dynamically imported tests and establishes a connection with the twd-relay browser client. ```tsx // src/main.tsx if (import.meta.env.DEV) { const { initTWD } = await import('twd-js/bundled'); const tests = import.meta.glob("./**/*.twd.test.ts"); initTWD(tests, { open: true, position: 'left' }); const { createBrowserClient } = await import('twd-relay/browser'); const client = createBrowserClient({ url: `${window.location.origin}/__twd/ws` }); client.connect(); } ``` -------------------------------- ### Add Coverage Scripts to package.json Source: https://github.com/brikev/twd-ai/blob/main/skills/ci-setup/SKILL.md Adds development and code coverage reporting scripts to `package.json`. `dev:ci` starts the Vite dev server in CI mode, while `collect:coverage:*` scripts generate coverage reports in different formats. ```json { "scripts": { "dev:ci": "CI=true vite", "collect:coverage:text": "npx nyc report --reporter=text --temp-dir .nyc_output", "collect:coverage:html": "npx nyc report --reporter=html --temp-dir .nyc_output", "collect:coverage:lcov": "npx nyc report --reporter=lcov --temp-dir .nyc_output" } } ``` -------------------------------- ### Initializing TWD in Development Environment Source: https://github.com/brikev/twd-ai/blob/main/skills/setup/SKILL.md Configures the TWD environment within the application entry point. This includes initializing the test runner and connecting the TWD-relay browser client for real-time communication. ```typescript if (import.meta.env.DEV) { const { initTWD } = await import('twd-js/bundled'); const tests = import.meta.glob("./**/*.twd.test.ts"); initTWD(tests, { open: true, position: 'left', serviceWorker: true, serviceWorkerUrl: '/mock-sw.js', }); const { createBrowserClient } = await import('twd-relay/browser'); const client = createBrowserClient({ url: `${window.location.origin}/__twd/ws` }); client.connect(); } ``` -------------------------------- ### Configuring Vite Plugins for TWD Source: https://github.com/brikev/twd-ai/blob/main/skills/setup/SKILL.md Integrates TWD HMR and remote relay plugins into the Vite configuration file to enable development testing features. ```typescript import { twdHmr } from 'twd-js/vite-plugin'; import { twdRemote } from 'twd-relay/vite'; import type { PluginOption } from 'vite'; plugins: [ twdHmr(), twdRemote() as PluginOption, ] ``` -------------------------------- ### Querying Portal Elements with TWD Source: https://github.com/brikev/twd-ai/blob/main/skills/setup/SKILL.md Demonstrates how to use the screenDomGlobal utility to select elements rendered outside the main DOM hierarchy, such as modals or tooltips. ```typescript import { screenDomGlobal } from "twd-js"; const modal = screenDomGlobal.getByRole("dialog"); ``` -------------------------------- ### Configure Entry Point for TWD (Vue) Source: https://github.com/brikev/twd-ai/blob/main/skills/twd/references/setup.md Configures the entry point for a Vue application to include TWD in development. It dynamically imports TWD and its tests, and establishes a connection with the twd-relay browser client. ```typescript // src/main.ts import { createApp } from 'vue'; import App from './App.vue'; if (import.meta.env.DEV) { const { initTWD } = await import('twd-js/bundled'); const tests = import.meta.glob("./**/*.twd.test.ts"); initTWD(tests, { open: true, position: 'left' }); const { createBrowserClient } = await import('twd-relay/browser'); const client = createBrowserClient({ url: `${window.location.origin}/__twd/ws` }); client.connect(); } createApp(App).mount('#app'); ``` -------------------------------- ### Install and Run twd-cli Source: https://github.com/brikev/twd-ai/blob/main/skills/twd/references/ci.md Commands to install the headless test runner and execute the test suite. The run command returns an exit code of 0 for success and 1 for failures. ```bash npm install --save-dev twd-cli npx twd-cli run ``` -------------------------------- ### Configure Entry Point for TWD (Angular) Source: https://github.com/brikev/twd-ai/blob/main/skills/twd/references/setup.md Sets up TWD within an Angular application's entry point for development. It initializes TWD with manually defined tests and connects the twd-relay browser client. Note that Angular might not support `import.meta.glob`. ```typescript // src/main.ts import { isDevMode } from '@angular/core'; if (isDevMode()) { const { initTWD } = await import('twd-js/bundled'); // Angular may not support import.meta.glob — define tests manually: const tests = { './twd-tests/feature.twd.test.ts': () => import('./twd-tests/feature.twd.test'), }; initTWD(tests, { open: true, position: 'left' }); const { createBrowserClient } = await import('twd-relay/browser'); const client = createBrowserClient({ url: `${window.location.origin}/__twd/ws` }); client.connect(); } ``` -------------------------------- ### Install TWD Plugin Source: https://github.com/brikev/twd-ai/blob/main/README.md Commands to add the marketplace and install the TWD plugin into the Claude Code environment. ```bash claude plugin marketplace add BRIKEV/twd-ai claude plugin install twd@twd-ai ``` -------------------------------- ### Flow-based Test Structure in TypeScript Source: https://github.com/brikev/twd-ai/blob/main/skills/twd/SKILL.md Examples demonstrating the preferred flow-based testing approach versus the discouraged granular element testing approach. Each test should represent a complete user interaction flow. ```typescript // GOOD — flow-based it() names it("should load the payment list and display all columns", async () => { /* ... */ }); it("should open the create form, fill fields, and submit successfully", async () => { /* ... */ }); it("should show validation errors when submitting an empty form", async () => { /* ... */ }); it("should cancel creation and return to the list", async () => { /* ... */ }); it("should display empty state when no payments exist", async () => { /* ... */ }); ``` ```typescript // BAD — granular per-element tests (NEVER do this) it("should display Pre payment label", async () => { /* ... */ }); it("should display the payment amount", async () => { /* ... */ }); it("should display the payment date", async () => { /* ... */ }); it("should display the submit button", async () => { /* ... */ }); it("should display the cancel button", async () => { /* ... */ }); ``` -------------------------------- ### Regex URL Matching for Dynamic Requests Source: https://github.com/brikev/twd-ai/blob/main/skills/twd/references/test-writing.md Illustrates mocking requests using regular expressions when URL segments are unpredictable. It shows examples using both RegExp literals and string regex patterns, emphasizing the use of `urlRegex: true`. ```typescript // RegExp literal await twd.mockRequest("getUserById", { method: "GET", url: /\/api\/users\/\d+/, response: { id: 999, name: "Dynamic User" }, urlRegex: true, }); // String regex (starts with ^) await twd.mockRequest("getUserById", { method: "GET", url: "^.*\/api\/users\/\d+", response: { id: 999, name: "Dynamic User" }, urlRegex: true, }); ``` -------------------------------- ### Flow-Based Testing Example (TypeScript) Source: https://github.com/brikev/twd-ai/blob/main/skills/twd/references/test-writing.md Demonstrates a 'good' example of flow-based testing using `it()` blocks that describe a complete user flow. This approach improves test readability and maintainability by focusing on user journeys rather than individual element states. It uses `describe` blocks to group related tests. ```typescript describe("Payments Page", () => { beforeEach(() => { /* ... */ }); describe("listing", () => { it("should load the payment list and display all columns", async () => { // Mock GET → visit → wait → assert heading, table rows, column headers }); it("should display empty state when no payments exist", async () => { // Mock GET with [] → visit → wait → assert empty message }); }); describe("create flow", () => { it("should open the create form, fill fields, and submit successfully", async () => { // Mock GET + POST → visit → click Add → fill form → submit → assert POST body + success }); it("should show validation errors when submitting an empty form", async () => { // Mock GET → visit → click Add → submit empty → assert error messages }); it("should cancel creation and return to the list", async () => { // Mock GET → visit → click Add → click Cancel → assert list is visible }); }); }); ``` -------------------------------- ### Configure Vite for Code Coverage Source: https://github.com/brikev/twd-ai/blob/main/skills/ci-setup/SKILL.md Adds the `vite-plugin-istanbul` to the Vite configuration. This plugin instruments the code for coverage analysis. It should be added after other existing plugins and configured with appropriate include/exclude paths. ```typescript import istanbul from "vite-plugin-istanbul"; // ... inside vite config plugins: [ // ... other plugins istanbul({ include: "src/*", exclude: ["node_modules", "**/*.twd.test.ts"], requireEnv: !process.env.CI, extension: ['.ts', '.tsx'], }), ] ``` -------------------------------- ### Add CI Test Script to package.json Source: https://github.com/brikev/twd-ai/blob/main/skills/ci-setup/SKILL.md Adds a `test:ci` script to the `package.json` file, which uses `npx twd-cli run` to execute tests in a CI environment. ```json { "scripts": { "test:ci": "npx twd-cli run" } } ``` -------------------------------- ### Initialize Mock Service Worker with twd-js Source: https://github.com/brikev/twd-ai/blob/main/skills/twd/references/setup.md Initializes the mock service worker for TWD by copying the `mock-sw.js` file to the specified public directory. This enables API mocking during development. ```bash npx twd-js init public --save ``` -------------------------------- ### Standard Test Setup and Teardown Source: https://github.com/brikev/twd-ai/blob/main/skills/twd/references/test-writing.md The standard beforeEach hook used to clear request mocks and component states before each test execution to ensure isolation. ```typescript beforeEach(() => { twd.clearRequestMockRules(); twd.clearComponentMocks(); }); ``` -------------------------------- ### Full mockRequest Options Configuration Source: https://github.com/brikev/twd-ai/blob/main/skills/twd/references/test-writing.md Details all available options for the `twd.mockRequest` function, including method, URL (string or RegExp), response body, status code, headers, response headers, simulated delay, and a flag to enable regex matching for the URL. This provides a comprehensive guide for configuring mocked requests. ```typescript await twd.mockRequest("alias", { method: string, // HTTP method (GET, POST, PUT, DELETE, etc.) url: string | RegExp, // URL to match response: unknown, // Response body (any JSON-serializable value) status?: number, // HTTP status code (default: 200) headers?: Record, // Response headers responseHeaders?: Record, // Alternative name for headers delay?: number, // Simulated network delay in ms urlRegex?: boolean, // Enable regex matching for url (default: false) }); ``` -------------------------------- ### Run TWD Relay Command Source: https://github.com/brikev/twd-ai/blob/main/skills/twd/references/setup.md Executes the TWD relay command to run tests. It supports custom ports and base paths for the WebSocket connection, allowing flexibility in different project configurations. ```bash # Default (works with Vite default port 5173 and base path /) npx twd-relay run # Custom port/base path npx twd-relay run --port PORT --path "BASE/__twd/ws" ``` -------------------------------- ### Correct Usage of twd.mockRequest Source: https://github.com/brikev/twd-ai/blob/main/skills/twd/references/test-writing.md Illustrates the correct syntax and usage patterns for the `twd.mockRequest` function, emphasizing the use of an alias, a configuration object, the `await` keyword, and the `response` field instead of `body`. It also shows examples with optional fields like `delay` and `responseHeaders`. ```typescript // RIGHT — alias + config object, await, response await twd.mockRequest("getUsers", { method: "GET", url: "/api/users", response: { data: [] }, status: 200, }); // RIGHT — with optional fields await twd.mockRequest("slowRequest", { method: "GET", url: "/api/data", response: { items: [] }, status: 200, delay: 1000, responseHeaders: { "X-Request-Id": "abc-123" }, }); // RIGHT — string match handles this automatically await twd.mockRequest("getUser", { method: "GET", url: "/api/users", response: { id: 1, name: "User" }, }); ``` -------------------------------- ### Module Stubbing with Sinon Source: https://github.com/brikev/twd-ai/blob/main/skills/twd/references/test-writing.md Details how to stub modules using the Sinon library. It emphasizes installing Sinon separately, importing it correctly, and wrapping immutable ESM named exports in objects with default exports for stubbing. ```typescript // hooks/useAuth.ts — CORRECT: stubbable const useAuth = () => useAuth0(); export default { useAuth }; // In test: import Sinon from "sinon"; // npm package "sinon", NOT "twd-js/sinon" import authModule from "../hooks/useAuth"; Sinon.stub(authModule, "useAuth").returns({ isAuthenticated: true, user: { name: "John" }, }); // Always Sinon.restore() in beforeEach ``` -------------------------------- ### Other Mock Request Patterns (POST, Error, Wait) Source: https://github.com/brikev/twd-ai/blob/main/skills/twd/references/test-writing.md Provides examples for various `mockRequest` scenarios including POST requests, simulating server errors with specific status codes, and waiting for requests to complete. It also shows how to clear all mock rules. ```typescript // Mock POST await twd.mockRequest("createUser", { method: "POST", url: "/api/users", response: { id: 456, created: true }, status: 201, }); // Error responses await twd.mockRequest("serverError", { method: "GET", url: "/api/data", response: { error: "Server error" }, status: 500, }); // Wait for request and inspect body const rule = await twd.waitForRequest("submitForm"); expect(rule.request).to.deep.equal({ email: "test@example.com" }); // Wait for multiple requests await twd.waitForRequests(["getUser", "getPosts"]); // Clear all mocks (always in beforeEach) twd.clearRequestMockRules(); ``` -------------------------------- ### Select elements and perform assertions with TWD Source: https://context7.com/brikev/twd-ai/llms.txt Demonstrates element selection using Testing Library queries and TWD-specific selectors. Includes examples of Chai-style assertions for DOM elements and URL states. ```typescript screenDom.getByRole("button", { name: "Submit" }); screenDom.getByLabelText("Email Address"); const button = await twd.get("button.primary"); await screenDom.findByRole("button", { name: "Submit" }); twd.should(screenDom.getByRole("button"), "be.visible"); expect(value).to.equal("expected"); ``` -------------------------------- ### Manual State Reset Example (TypeScript) Source: https://github.com/brikev/twd-ai/blob/main/skills/twd/references/test-writing.md Illustrates a comprehensive `beforeEach` block in TypeScript that resets TWD AI's mocks, clears local storage, and calls a custom store reset function to ensure complete test isolation. ```typescript import { resetMyStore } from "../../store"; describe("My feature", () => { beforeEach(() => { twd.clearRequestMockRules(); twd.clearComponentMocks(); resetMyStore(); localStorage.clear(); }); it("should start with clean state", async () => { await twd.visit("/my-page"); // State is fresh for every test }); }); ``` -------------------------------- ### Markdown Report Template for Test Gap Analysis Source: https://github.com/brikev/twd-ai/blob/main/skills/test-gaps/SKILL.md This template defines the structure for generating a Test Gap Analysis Report in markdown format. It includes sections for summary, UNTESTED pages (categorized by risk), PARTIALLY TESTED pages, and a 'Start Here' priority ranking. It also includes a note for monorepo projects. ```markdown # Test Gap Analysis Report Generated: {date} ## Summary - **Pages/routes discovered:** {N} - **Pages with tests:** {N} - **Pages partially tested:** {N} - **Pages untested:** {N} - **Route discovery method:** {framework route config / page component glob / TWD tests only} ## UNTESTED Pages ### HIGH Risk | Page | Path | Why High Risk | |------|------|---------------| | ... | ... | ... | ### MEDIUM Risk | Page | Path | Why Medium Risk | |------|------|-----------------| | ... | ... | ... | ### LOW Risk | Page | Path | Why Low Risk | |------|------|--------------| | ... | ... | ... | ## PARTIALLY TESTED Pages | Page | Path | What's Covered | What's Missing | |------|------|----------------|----------------| | ... | ... | ... | ... | ## Start Here (Top 5 Priorities) 1. **{Page}** — {reason this is #1} 2. ... --- > **Tip:** For large codebases, the Serena MCP server can reduce token usage > during gap analysis by enabling symbol-level navigation instead of full file reads. ``` -------------------------------- ### Complete Feature Test Template Source: https://github.com/brikev/twd-ai/blob/main/skills/twd/references/test-writing.md A full example of a test file structure, including imports, mock data setup, and flow-based test cases using the TWD testing library. ```typescript import { twd, userEvent, screenDom, expect } from "twd-js"; import { describe, it, beforeEach } from "twd-js/runner"; const mockData = [ { id: 1, name: "Item One" }, { id: 2, name: "Item Two" }, ]; describe("Feature Page", () => { beforeEach(() => { twd.clearRequestMockRules(); twd.clearComponentMocks(); }); it("should load and display items", async () => { await twd.mockRequest("getItems", { method: "GET", url: "/api/items", response: mockData, status: 200, }); await twd.visit("/items"); await twd.waitForRequest("getItems"); twd.should(screenDom.getByRole("heading", { name: "Items" }), "be.visible"); expect(screenDom.getAllByRole("listitem")).to.have.length(2); }); }); ``` -------------------------------- ### Initializing TWD in Application Entry Point Source: https://context7.com/brikev/twd-ai/llms.txt Initializes the TWD framework and relay client within the application entry point. Uses an environment guard to ensure TWD is only loaded during development mode. ```typescript if (import.meta.env.DEV) { const { initTWD } = await import('twd-js/bundled'); const tests = import.meta.glob("./**/*.twd.test.ts"); initTWD(tests, { open: true, position: 'left', serviceWorker: true, serviceWorkerUrl: '/mock-sw.js', }); const { createBrowserClient } = await import('twd-relay/browser'); const client = createBrowserClient({ url: `${window.location.origin}/__twd/ws` }); client.connect(); } ``` -------------------------------- ### Add Vite Plugins for TWD Source: https://github.com/brikev/twd-ai/blob/main/skills/twd/references/setup.md Configures Vite to use TWD-specific plugins for Hot Module Replacement (`twdHmr`) and remote functionality (`twdRemote`). These plugins enhance the development experience with TWD. ```typescript // vite.config.ts import { twdHmr } from 'twd-js/vite-plugin'; import { twdRemote } from 'twd-relay/vite'; import type { PluginOption } from 'vite'; export default defineConfig({ plugins: [ // ... other plugins twdHmr(), twdRemote() as PluginOption, ], }); ``` -------------------------------- ### Standard Mocking API Requests Before Navigation Source: https://github.com/brikev/twd-ai/blob/main/skills/twd/references/test-writing.md Demonstrates the standard pattern for mocking network requests before navigating to a page using `twd.visit()`. It shows how to define a request label, specify the HTTP method, URL, response data, and status code. It also includes waiting for the mocked request to be processed. ```typescript // Always mock BEFORE twd.visit() await twd.mockRequest("labelName", { method: "GET", url: "/api/endpoint", response: { data: "value" }, status: 200, }); await twd.visit("/page"); await twd.waitForRequest("labelName"); ``` -------------------------------- ### TWD AI Navigation and Waiting (TypeScript) Source: https://github.com/brikev/twd-ai/blob/main/skills/twd/references/test-writing.md Demonstrates TWD AI commands for navigating to different URLs (`twd.visit()`), waiting for a specified duration (`twd.wait()`), waiting for an element to appear (`screenDom.findByText()`), and waiting for an element to disappear (`twd.notExists()`). ```typescript await twd.visit("/"); await twd.visit("/login"); await twd.wait(1000); // Wait for time (ms) await screenDom.findByText("Success!"); // Wait for element await twd.notExists(".loading-spinner"); // Wait for element to NOT exist ``` -------------------------------- ### Element Selection with Testing Library (TypeScript) Source: https://github.com/brikev/twd-ai/blob/main/skills/twd/references/test-writing.md Demonstrates preferred methods for selecting DOM elements using the Testing Library, primarily through `screenDom`. It covers selection by role (recommended), label text, visible text, and test ID, along with variations like `getBy`, `queryBy`, `findBy`, and `getAllBy` for different assertion needs. It also shows how to use `screenDomGlobal` for modals. ```typescript // By role (RECOMMENDED) screenDom.getByRole("button", { name: "Submit" }); screenDom.getByRole("heading", { name: "Welcome", level: 1 }); // By label (form inputs) screenDom.getByLabelText("Email Address"); // By text screenDom.getByText("Success!"); screenDom.getByText(/welcome/i); // By test ID screenDom.getByTestId("user-card"); // Query variants screenDom.getByRole("button"); // Throws if not found screenDom.queryByRole("button"); // Returns null if not found await screenDom.findByRole("button"); // Waits for element (async) screenDom.getAllByRole("button"); // Returns array // For modals/portals use screenDomGlobal: import { screenDomGlobal } from "twd-js"; const modal = screenDomGlobal.getByRole("dialog"); ``` -------------------------------- ### Extract twd.visit() and twd.mockRequest() calls Source: https://github.com/brikev/twd-ai/blob/main/skills/test-gaps/SKILL.md This snippet demonstrates how to extract `twd.visit()` and `twd.mockRequest()` calls from TWD test files. It covers literal strings, template literals, and same-file constant references for URLs. It also notes how to handle `beforeEach` blocks and identifies interaction depth based on `userEvent.*` calls. ```javascript function extractTwdCalls(filePath) { // Read file content const code = fs.readFileSync(filePath, 'utf-8'); const calls = { visits: [], mocks: [], hasInteractions: false }; // Regex to find twd.visit() calls const visitRegex = /twd\.visit\(['"](.*?)['"]\)|twd\.visit\(``(.*?)``\)/g; let match; while ((match = visitRegex.exec(code)) !== null) { const url = match[1] || match[2]; // Handle both single/double quotes and template literals // Further processing for template literals like `/orders/${id}` -> `/orders/:param` calls.visits.push(url); } // Regex to find twd.mockRequest() calls const mockRegex = /twd\.mockRequest\(['"](.*?)['"], ['"](.*?)['"]\)/g; while ((match = mockRegex.exec(code)) !== null) { calls.mocks.push({ method: match[1], url: match[2] }); } // Regex to find userEvent.* calls if (/userEvent\.\w+\(/.test(code)) { calls.hasInteractions = true; } return calls; } ``` -------------------------------- ### Chai Expect Assertions (JavaScript/TypeScript) Source: https://github.com/brikev/twd-ai/blob/main/skills/twd/references/test-writing.md Provides examples of using Chai's `expect` for general assertions that do not involve DOM elements. This includes checking array lengths, string equality, and deep object equality. ```javascript expect(array).to.have.length(3); expect(value).to.equal("expected"); expect(obj).to.deep.equal({ key: "value" }); ```