### Install TWD using npm, yarn, or pnpm Source: https://github.com/brikev/twd/blob/main/docs/getting-started.md Install the TWD library using your preferred package manager. This is the first step to integrating TWD into your project. ```bash npm install twd-js ``` ```bash yarn add twd-js ``` ```bash pnpm add twd-js ``` -------------------------------- ### Run Development Server with npm Source: https://github.com/brikev/twd/blob/main/docs/getting-started.md Starts the development server for your React application. This command is typically used with build tools like Vite and allows you to see the TWD sidebar in action during development. ```bash npm run dev ``` -------------------------------- ### Clone TWD Docs Tutorial Repository Source: https://github.com/brikev/twd/blob/main/docs/tutorial/installation.md Clones the TWD documentation tutorial repository from GitHub. This command initializes the project setup for learning how to use TWD, allowing users to follow along with the tutorial. ```bash git clone git@github.com:BRIKEV/twd-docs-tutorial.git cd twd-docs-tutorial git checkout 01-setup npm i ``` -------------------------------- ### Write a Basic TWD Test for React Component (TypeScript) Source: https://github.com/brikev/twd/blob/main/docs/getting-started.md Demonstrates how to write a test for a React component using TWD. It covers visiting a route, getting elements, and making assertions about their visibility and text content. This example uses 'describe', 'it' from 'twd-js/runner' and 'twd', 'userEvent' from 'twd-js'. ```ts // src/App.twd.test.ts import { twd, userEvent } from "twd-js"; import { describe, it } from "twd-js/runner"; describe("App Component", () => { it("should render the main heading", async () => { await twd.visit("/"); const heading = await twd.get("h1"); heading.should("be.visible"); }); it("should handle button clicks", async () => { await twd.visit("/"); const user = userEvent.setup(); const button = await twd.get("button"); await user.click(button.el); // Add your assertions here const result = await twd.get("#result"); result.should("have.text", "Button clicked!"); }); }); ``` -------------------------------- ### Run Development Server Source: https://github.com/brikev/twd/blob/main/docs/tutorial/installation.md Starts the local development server for the project using npm. This command is used to run the application locally, enabling testing and development workflows. ```bash npm run serve:dev ``` -------------------------------- ### Repository Setup Commands Source: https://github.com/brikev/twd/blob/main/docs/tutorial/ci-integration.md A set of Git and npm commands to reset the repository to a clean state and check out a specific branch for the CI integration tutorial. These commands ensure a consistent starting point for the tutorial. ```bash # Repo git clone git@github.com:BRIKEV/twd-docs-tutorial.git git reset --hard git clean -d -f git checkout 04-ci-integration npm run serve:dev ``` -------------------------------- ### Initialize Mock Service Worker with TWD CLI Source: https://github.com/brikev/twd/blob/main/docs/getting-started.md Sets up the mock service worker by copying the necessary 'mock-sw.js' file to your public directory. This command-line utility is part of the TWD JS package. ```bash npx twd-js init public ``` -------------------------------- ### Create Basic TWD Test File Source: https://github.com/brikev/twd/blob/main/docs/tutorial/installation.md Defines a basic test suite for the 'Hello World Page' using TWD's `describe` and `it` functions. This file serves as a starting point for TWD tests, demonstrating how to structure test cases. It includes a placeholder for test logic. ```typescript import { describe, it } from "twd-js/runner"; describe("Hello World Page", () => { it("should display the welcome title and counter button", async () => { console.log('Executed console.log'); }); }); ``` -------------------------------- ### Repository Setup Commands for TWD Testing Source: https://github.com/brikev/twd/blob/main/docs/tutorial/first-test.md Git commands to clone, reset, and configure the TWD testing repository branch for this tutorial. These commands prepare the local development environment by resetting the repository to a clean state and checking out the assertions-specific branch. ```bash # Repo git clone git@github.com:BRIKEV/twd-docs-tutorial.git git reset --hard git clean -d -f git checkout 02-assertions npm run serve:dev ``` -------------------------------- ### Run the twd-test-app Source: https://github.com/brikev/twd/blob/main/CONTRIBUTING.md Commands to navigate to the example test application, install its dependencies, and run it in development mode. This app uses a local version of TWD for testing new features. ```bash cd examples/twd-test-app npm install npm run dev ``` -------------------------------- ### Initialize TWD Sidebar and Load Tests in React (TypeScript) Source: https://github.com/brikev/twd/blob/main/docs/getting-started.md Integrates the TWD sidebar and automatically loads tests in development mode by using Vite's glob import. It requires the 'twd-js' library and should be placed in your main entry file (e.g., src/main.tsx). It also includes optional request mocking initialization. ```tsx // src/main.tsx import { StrictMode } from 'react'; import { createRoot } from 'react-dom/client'; import './index.css'; import App from './App'; // Only load the test sidebar and tests in development mode if (import.meta.env.DEV) { // Use Vite's glob import to find all test files const testModules = import.meta.glob("./**/*.twd.test.ts"); const { initTests, twd, TWDSidebar } = await import('twd-js'); // You need to pass the test modules, the sidebar component, and createRoot function initTests(testModules, , createRoot); // Optionally initialize request mocking twd.initRequestMocking() .then(() => { console.log("Request mocking initialized"); }) .catch((err) => { console.error("Error initializing request mocking:", err); }); } createRoot(document.getElementById('root')!).render( , ); ``` -------------------------------- ### Install TWD Package Source: https://github.com/brikev/twd/blob/main/docs/tutorial/installation.md Installs the TWD (Test While Developing) JavaScript package as a development dependency using npm. This command is essential for integrating TWD into your project for testing purposes. ```bash npm i --save-dev twd-js ``` -------------------------------- ### API Mocking Setup Source: https://github.com/brikev/twd/blob/main/README.md CLI command and configuration for setting up mock service worker for API/request mocking. ```APIDOC ## API Mocking Setup ### Description CLI command and configuration for setting up mock service worker for API/request mocking. ### Code Examples ```bash npx twd-js init [--save] ``` ```ts // vite.config.ts import { defineConfig } from 'vite'; import { removeMockServiceWorker } from 'twd-js'; export default defineConfig({ plugins: [ // ... other plugins removeMockServiceWorker() ] }); ``` ``` -------------------------------- ### Using beforeEach for Common Setup in TWD Source: https://github.com/brikev/twd/blob/main/docs/api/test-functions.md Demonstrates how to use `beforeEach` in TWD to perform common setup tasks for multiple tests. This reduces code duplication and ensures consistency across related tests. ```typescript describe("Authentication Flow", () => { beforeEach(async () => { // Common setup for all auth tests await twd.initRequestMocking(); await twd.visit("/login"); }); it("should login successfully", async () => { // No need to repeat visit and mock setup }); it("should handle login errors", async () => { // No need to repeat visit and mock setup }); }); ``` -------------------------------- ### Mock GET request and verify UI with TWD-js (TypeScript) Source: https://context7.com/brikev/twd/llms.txt Shows how to mock an HTTP GET request using twd.mockRequest, wait for the request, and assert that the UI displays the mocked user data. Includes setup clearing mock rules and usage of selectors to verify text. ```TypeScript import { twd, userEvent, expect } from \"twd-js\";\import { describe, it, beforeEach } from \"twd-js/runner\";\n\ndescribe(\"User profile\", () => {\n beforeEach(() => {\n twd.clearRequestMockRules();\n });\n\n it(\"should fetch and display user data\", async () => {\n // Mock GET request with JSON response\n await twd.mockRequest(\"getUser\", {\n method: \"GET\",\n url: \"https://api.example.com/user/123\",\n response: {\n id: 123,\n name: \"John Doe\",\n email: \"john@example.com\",\n role: \"admin\"\n },\n status: 200,\n responseHeaders: {\n \"Content-Type\": \"application/json\",\n \"X-Custom-Header\": \"test-value\"\n }\n });\n\n await twd.visit(\"profile/123\");\n\n // Wait for the mock to be executed\n const rule = await twd.waitForRequest(\"getUser\");\n console.log(\"Request was made to:\", rule.url);\n\n // Verify UI displays the mocked data\n const userName = await twd.get(\"[data-testid='user-name']\");\n userName.should(\"have.text\", \"John Doe");\n\n const userEmail = await twd.get(\"[data-testid='user-email']\");\n userEmail.should(\"have.text\", \"john@example.com\");\n });\n}); ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/brikev/twd/blob/main/CONTRIBUTING.md Installs all necessary Node.js dependencies for the twd-js project using npm. This command should be run after cloning the repository. ```bash npm install ``` -------------------------------- ### TWD Example: Testing a Page in TypeScript Source: https://github.com/brikev/twd/blob/main/docs/index.md Demonstrates how to use TWD to visit a page, interact with elements, and assert their state. It utilizes TWD's `visit`, `get`, and `userEvent` functions, along with its `describe` and `it` test structure. Dependencies include 'twd-js' and 'twd-js/runner'. ```ts import { twd, userEvent } from "twd-js"; import { describe, it } from "twd-js/runner"; describe("Hello World Page", () => { it("should display the welcome title and counter button", async () => { await twd.visit("/"); const title = await twd.get("[data-testid='welcome-title']"); title.should("be.visible").should("have.text", "Welcome to TWD"); const counterButton = await twd.get("[data-testid='counter-button']"); counterButton.should("be.visible").should("have.text", "Count is 0"); await userEvent.click(counterButton.el); counterButton.should("have.text", "Count is 1"); }); }); ``` -------------------------------- ### Integrate coverage into GitHub Actions workflow Source: https://github.com/brikev/twd/blob/main/docs/tutorial/coverage.md This YAML configuration updates a GitHub Actions workflow to include steps for checking out code, setting up Node.js, installing dependencies, starting the Vite server, running tests, and displaying coverage. It depends on GitHub Actions runners and Node.js 24. Outputs are workflow logs and coverage summaries; limitations include potential timeouts for long-running tests. ```yaml name: CI - PR Tests on: 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: Start Vite dev server run: | nohup npm run dev:ci > vite.log 2>&1 & npx wait-on http://localhost:5173 env: CI: true - name: Run Puppeteer tests (test:ci) run: npm run test:ci env: CI: true - name: Display coverage run: | npm run collect:coverage:text ``` -------------------------------- ### BeforeEach: Setup Before Each TWD Test Source: https://github.com/brikev/twd/blob/main/docs/api/test-functions.md Runs a setup function before each test within the current `describe` block. This is ideal for resetting state or performing common setup tasks, ensuring a clean environment for every test. It can be asynchronous. ```typescript beforeEach(fn: () => Promise | void): void describe("User Dashboard", () => { beforeEach(() => { // Reset state before each test localStorage.clear(); twd.clearRequestMockRules(); }); it("should show user profile", async () => { // Clean state guaranteed }); it("should display recent orders", async () => { // Clean state guaranteed }); }); describe("API Integration", () => { beforeEach(async () => { // Initialize mocking await twd.initRequestMocking(); // Set up common mocks await twd.mockRequest("getUser", { method: "GET", url: "/api/user", response: { id: 1, name: "Test User" } }); }); it("should load user data", async () => { // Mocks are already set up }); }); ``` -------------------------------- ### Install TWD Service Worker Source: https://github.com/brikev/twd/blob/main/docs/tutorial/api-mocking.md Installs the TWD Service Worker to intercept network requests. It creates a `mock-sw.js` file in the specified public directory. ```bash npx twd-js init public --save ``` -------------------------------- ### GitHub Actions CI workflow for TWD with Puppeteer Source: https://github.com/brikev/twd/blob/main/docs/tutorial/ci-integration.md This YAML configuration sets up a GitHub Actions workflow to run TWD tests using Puppeteer on pull requests. It includes steps for checking out code, setting up Node.js, installing dependencies, starting a Vite dev server, and running Puppeteer tests. ```yml name: CI - PR Tests on: 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: Start Vite dev server run: | nohup npm run dev > vite.log 2>&1 & npx wait-on http://localhost:5173 env: CI: true - name: Run Puppeteer tests (test:ci) run: npm run test:ci env: CI: true ``` -------------------------------- ### Mock Simple GET Request for User Data Source: https://github.com/brikev/twd/blob/main/docs/api-mocking.md Example using `twd.mockRequest` to mock a GET request to fetch user data. It then visits a profile page, triggers the request, waits for it, and verifies the UI update. ```typescript import { twd, userEvent } from "twd-js"; import { describe, it } from "twd-js/runner"; describe("User Profile", () => { it("should load user data", async () => { // Mock the API request await twd.mockRequest("getUser", { method: "GET", url: "https://api.example.com/user/123", response: { id: 123, name: "John Doe", email: "john@example.com" } }); await twd.visit("/profile"); // Trigger the request const loadButton = await twd.get("button[data-testid='load-profile']"); await userEvent.click(loadButton.el); // Wait for the mock to be called await twd.waitForRequest("getUser"); // Verify the UI updated const userName = await twd.get("[data-testid='user-name']"); userName.should("have.text", "John Doe"); }); }); ``` -------------------------------- ### Basic Test Structure with TWD Source: https://github.com/brikev/twd/blob/main/docs/writing-tests.md Demonstrates the fundamental structure for writing tests in TWD, including imports, test suites using `describe`, setup hooks with `beforeEach`, and individual test cases defined by `it`. This setup is similar to Jest and Mocha. ```typescript import { twd, userEvent } from "twd-js"; import { describe, it, beforeEach } from "twd-js/runner"; describe("User Authentication", () => { beforeEach(() => { // Reset state before each test console.log("Setting up test environment"); }); it("should login with valid credentials", async () => { // Your test logic here }); it("should show error with invalid credentials", async () => { // Your test logic here }); }); ``` -------------------------------- ### Visit Page in TWD Test Source: https://github.com/brikev/twd/blob/main/docs/tutorial/installation.md Enhances a TWD test case by adding functionality to visit a specific URL within the application. It uses the `twd.visit` command, similar to Cypress's `cy.visit()`, to navigate to the root path ('/'). ```typescript import { twd } from "twd-js"; import { describe, it } from "twd-js/runner"; describe("Hello World Page", () => { it("should display the welcome title and counter button", async () => { await twd.visit('/'); }); }); ``` -------------------------------- ### Chainable Assertions for UI Verification in TWD Source: https://github.com/brikev/twd/blob/main/docs/tutorial/first-test.md TypeScript examples showing TWD's chainable assertion system using the should method. Demonstrates visibility checks, text content validation, and stacking multiple assertions. Supports built-in assertions like be.visible, have.text, have.class, and their negative counterparts. ```ts const title = await twd.get("[data-testid='welcome-title']"); title.should("be.visible").should("have.text", "Welcome to TWD"); const counterButton = await twd.get("[data-testid='counter-button']"); counterButton.should("be.visible").should("have.text", "Count is 0"); ``` -------------------------------- ### Migration from Cypress to TWD (TypeScript) Source: https://github.com/brikev/twd/blob/main/docs/api/index.md Provides a code example illustrating the migration from Cypress commands to equivalent TWD commands for element interaction and assertions. ```typescript // Cypress // cy.get('[data-testid="button"]').click(); // cy.get('[data-testid="message"]').should('contain', 'Success'); // TWD const button = await twd.get('[data-testid="button"]'); await userEvent.click(button.el); const message = await twd.get('[data-testid="message"]'); message.should('contain.text', 'Success'); ``` -------------------------------- ### Setup API Mocking with TWD CLI Source: https://github.com/brikev/twd/blob/main/README.md Initialize a mock service worker for API mocking using the TWD CLI. This command copies `mock-sw.js` to your public directory, and TWD automatically handles its registration during tests. Replace `` with your app's static asset directory. ```bash npx twd-js init [--save] ``` -------------------------------- ### Initialize TWD Tests in Vite React Applications Source: https://github.com/brikev/twd/blob/main/docs/frameworks.md This snippet demonstrates how to initialize TWD tests and request mocking within a Vite-based React application. It utilizes `import.meta.glob()` for dynamic test module loading and assumes the `twd-js` library is installed. It's suitable for standard Vite+React, Remix with Vite, and other Vite-based React setups. ```typescript // src/main.tsx if (import.meta.env.DEV) { const testModules = import.meta.glob("./**/*.twd.test.ts"); const { initTests, twd, TWDSidebar } = await import('twd-js'); initTests(testModules, , createRoot); twd.initRequestMocking() .then(() => { console.log("Request mocking initialized"); }) .catch((err) => { console.error("Error initializing request mocking:", err); }); } ``` -------------------------------- ### Install Puppeteer for CI Source: https://github.com/brikev/twd/blob/main/docs/ci-execution.md Installs Puppeteer, a Node.js library that provides a high-level API to control headless Chrome or Chromium over the DevTools Protocol. This is a development dependency. ```bash npm install --save-dev puppeteer ``` -------------------------------- ### TWD Test Case Example (TypeScript) Source: https://github.com/brikev/twd/blob/main/CONTRIBUTING.md Example of how to write test cases within the `twd-test-app`. It demonstrates importing TWD functionalities and test runner utilities from the local source code. ```typescript import { twd, userEvent } from "../../../../src"; import { describe, it } from "../../../../src/runner"; ``` -------------------------------- ### Navigate Between Routes with twd.js Source: https://github.com/brikev/twd/blob/main/docs/writing-tests.md Provides examples of how to programmatically navigate to different routes within your web application using `twd.visit()`. This includes navigating to root, specific pages, and pages with query parameters or hash fragments. ```typescript // Navigate to different routes await twd.visit("/"); await twd.visit("/login"); await twd.visit("/dashboard"); // Navigate with query parameters await twd.visit("/search?q=testing"); // Navigate with hash await twd.visit("/docs#getting-started"); ``` -------------------------------- ### Mock POST Request with Request Body for New User Creation Source: https://github.com/brikev/twd/blob/main/docs/api-mocking.md Example demonstrating how to mock a POST request to create a new user. It includes setting up the mock, visiting a new user page, filling a form, submitting it, and verifying the request body. ```typescript it("should create new user", async () => { await twd.mockRequest("createUser", { method: "POST", url: "https://api.example.com/users", response: { id: 456, name: "Jane Smith", email: "jane@example.com", created: true }, status: 201 }); await twd.visit("/users/new"); const user = userEvent.setup(); // Fill form await user.type(await twd.get("#name"), "Jane Smith"); await user.type(await twd.get("#email"), "jane@example.com"); // Submit form await user.click(await twd.get("button[type='submit']")); // Wait for request and verify const rule = await twd.waitForRequest("createUser"); // Check the request body expect(rule.request).to.deep.equal({ name: "Jane Smith", email: "jane@example.com" }); }); ``` -------------------------------- ### Install and Configure Vite Plugin for Istanbul Coverage Source: https://github.com/brikev/twd/blob/main/docs/tutorial/coverage.md Install the vite-plugin-istanbul package to instrument TypeScript and JSX code for coverage tracking. Add the plugin to vite.config.ts to include source files while excluding node_modules and tests directories. The plugin exposes coverage data via window.__coverage__ for extraction in browser-based tests, with conditional enabling in CI environments. ```bash npm i --save-dev vite-plugin-istanbul ``` ```typescript /// import path from "path" import tailwindcss from "@tailwindcss/vite" import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' // add plugin for code coverage import istanbul from 'vite-plugin-istanbul'; // https://vite.dev/config/ export default defineConfig({ plugins: [ react(), tailwindcss(), // configure istanbul plugin istanbul({ include: 'src/**/*', exclude: ['node_modules', 'tests/'], extension: ['.ts', '.tsx'], requireEnv: process.env.CI ? true : false, }), ], resolve: { alias: { "@": path.resolve(__dirname, "./src"), }, }, server: { watch: { ignored: ["**/data/data.json", "**data/routes.json"], }, }, }) ``` -------------------------------- ### Get All Active Mock Rules (TypeScript) Source: https://github.com/brikev/twd/blob/main/docs/api/twd-commands.md Illustrates how to retrieve all currently active mock request rules using twd.getRequestMockRules. The example shows logging the count and details of active mocks and verifying the existence and properties of a specific mock rule. ```typescript // Debug active mocks await twd.mockRequest("getUser", { method: "GET", url: "/api/user", response: { id: 1 } }); await twd.mockRequest("getPosts", { method: "GET", url: "/api/posts", response: [] }); const activeMocks = twd.getRequestMockRules(); console.log(`Active mocks: ${activeMocks.length}`); activeMocks.forEach(mock => { console.log(`Mock: ${mock.alias} - ${mock.method} ${mock.url}`); }); // Verify specific mock exists const userMock = activeMocks.find(mock => mock.alias === "getUser"); expect(userMock).to.exist; expect(userMock?.method).to.equal("GET"); ``` -------------------------------- ### Descriptive Selectors Best Practice (TypeScript) Source: https://github.com/brikev/twd/blob/main/docs/api/twd-commands.md Highlights the importance of using descriptive and semantic CSS selectors when selecting elements with twd.get. It contrasts good examples using attribute selectors with bad examples relying on fragile structural selectors. ```typescript // ✅ Good - Semantic and stable const submitButton = await twd.get("button[type='submit']"); const userCard = await twd.get("[data-testid='user-card']"); // ❌ Avoid - Fragile and non-semantic const button = await twd.get("div > div:nth-child(3) button"); ``` -------------------------------- ### Mock Realistic Data for API Requests (TypeScript) Source: https://github.com/brikev/twd/blob/main/docs/api-mocking.md This example promotes the best practice of mocking realistic and comprehensive data for API responses. It shows a detailed user object as a good example versus a minimal, less useful one. ```typescript // Good ✅ - Realistic user data await twd.mockRequest("getUser", { method: "GET", url: "/api/user/123", response: { id: 123, name: "John Doe", email: "john.doe@example.com", avatar: "https://example.com/avatar.jpg", createdAt: "2024-01-15T10:30:00Z", role: "user" } }); // Bad ❌ - Minimal/unrealistic data twd.mockRequest("getUser", { method: "GET", url: "/api/user/123", response: { name: "test" } }); ``` -------------------------------- ### Initialize TWD in Vite Application Source: https://github.com/brikev/twd/blob/main/docs/tutorial/installation.md Initializes TWD within a Vite development environment. It uses Vite's glob import to dynamically load test files and then integrates TWD's sidebar and test runner. This code should only run in development to avoid bundling TWD in production builds. ```typescript if (import.meta.env.DEV) { // You choose how to load the tests; this example uses Vite's glob import const testModules = import.meta.glob("./**/*.twd.test.ts"); const { initTests, TWDSidebar } = await import('twd-js'); // You need to pass the test modules, the sidebar component, and createRoot function initTests(testModules, , createRoot); } ``` -------------------------------- ### Use Realistic Mock Data Best Practice (TypeScript) Source: https://github.com/brikev/twd/blob/main/docs/api/twd-commands.md Recommends using realistic and well-structured data for mocks to better simulate actual API responses. It contrasts a detailed, realistic example with a minimal, less representative one. ```typescript // ✅ Good - Realistic data structure await twd.mockRequest("getUser", { method: "GET", url: "/api/user/123", response: { id: 123, name: "John Doe", email: "john.doe@example.com", avatar: "https://example.com/avatar.jpg", createdAt: "2024-01-15T10:30:00Z", preferences: { theme: "dark", notifications: true } } }); // ❌ Too minimal await twd.mockRequest("getUser", { method: "GET", url: "/api/user/123", response: { name: "test" } }); ``` -------------------------------- ### Mock API Requests with URL Patterns using RegExp Source: https://github.com/brikev/twd/blob/main/docs/api-mocking.md Example showing how to mock API requests using regular expressions for the URL. This allows mocking dynamic resource IDs, such as user IDs in the URL path. ```typescript it("should handle dynamic user IDs", async () => { // Mock any user ID await twd.mockRequest("getUserById", { method: "GET", url: /\/api\/users\/\d+/, // Matches /api/users/123, /api/users/456, etc. response: { id: 123, name: "Dynamic User" } }); // This will match the pattern await twd.visit("/users/123"); // Trigger request and verify const loadButton = await twd.get("button[data-testid='load-user']"); await userEvent.click(loadButton.el); await twd.waitForRequest("getUserById"); }); ``` -------------------------------- ### Simulate User Interactions with TWD.JS Source: https://context7.com/brikev/twd/llms.txt This code example shows how to simulate common user interactions such as clicking, double-clicking, typing into input fields, clearing inputs, selecting dropdown options, and setting values for specialized input types. ```typescript import { twd, userEvent } from "twd-js"; import { describe, it } from "twd-js/runner"; describe("User interactions", () => { it("should handle clicks, typing, and form interactions", async () => { await twd.visit("/"); // Click a button const counterButton = await twd.get("[data-testid='counter-button']"); counterButton.should("have.text", "Count is 0"); await userEvent.click(counterButton.el); counterButton.should("have.text", "Count is 1"); // Double click await userEvent.dblClick(counterButton.el); counterButton.should("have.text", "Count is 3"); // Type into text inputs const searchInput = await twd.get("input[type='search']"); await userEvent.type(searchInput.el, "Hello World"); searchInput.should("have.value", "Hello World"); // Clear input await userEvent.clear(searchInput.el); searchInput.should("have.value", ""); // Select dropdown option const categorySelect = await twd.get("select#category"); await userEvent.selectOptions(categorySelect.el, "technology"); // Specialized input types (range, color, time) const timeInput = await twd.get("input[type='time']"); twd.setInputValue(timeInput.el, "13:30"); timeInput.should("have.value", "13:30"); }); }); ``` -------------------------------- ### Navigate between pages and assert URLs using TWD-js (TypeScript) Source: https://context7.com/brikev/twd/llms.txt Demonstrates navigation to routes in a single-page application using twd.visit and URL assertions with twd.url(). Includes examples of exact match, partial match, forced reload, and handling redirects after unauthenticated access. ```TypeScript import { twd } from \"twd-js\";\nimport { describe, it } from \"twd-js/runner\";\n\ndescribe(\"Navigation\", () => {\n it(\"should navigate and verify URLs\", async () => {\n // Navigate to a route (uses pushState for SPA navigation)\n await twd.visit(\"/\");\n\n // Exact URL match\n twd.url().should(\"eq\", \"http://localhost:3000/\");\n\n // Navigate to contact page\n await twd.visit(\"/contact\");\n twd.url().should(\"contain.url\", \"/contact\");\n\n // Force reload even if already on the URL\n await twd.visit(\"/contact\", true);\n\n // Wait for async operations\n await twd.wait(500);\n });\n\n it(\"should handle redirects\", async () => {\n // Visit protected route when not authenticated\n await twd.visit(\"/dashboard\");\n await twd.wait(100);\n\n // Should redirect to login\n twd.url().should(\"contain.url\", \"/login\");\n });\n}); ``` -------------------------------- ### Form Validation Example in TypeScript Source: https://github.com/brikev/twd/blob/main/docs/api/assertions.md A practical example of form validation using TWD and userEvent. It covers submitting an empty form, checking for validation errors on specific fields, and verifying error message visibility and content. ```typescript describe("Form Validation", () => { it("should validate required fields", async () => { await twd.visit("/contact"); const user = userEvent.setup(); const submitButton = await twd.get("button[type='submit']"); // Submit empty form await user.click(submitButton.el); // Check validation errors const emailError = await twd.get(".error-email"); emailError .should("be.visible") .should("contain.text", "required") .should("have.class", "error-message"); const messageError = await twd.get(".error-message"); messageError .should("be.visible") .should("not.be.empty"); // Fix one error const emailInput = await twd.get("#email"); await user.type(emailInput.el, "test@example.com"); emailInput.should("have.value", "test@example.com"); emailError.should("not.be.visible"); }); }); ``` -------------------------------- ### twd.getRequestMockRules() Source: https://github.com/brikev/twd/blob/main/docs/api/twd-commands.md Gets all currently active mock rules. Useful for debugging and verifying which mocks are currently in effect. ```APIDOC ## twd.getRequestMockRules() ### Description Gets all currently active mock rules. Useful for debugging and verifying which mocks are currently in effect. ### Method `twd.getRequestMockRules()` ### Request Example ```ts const activeMocks = twd.getRequestMockRules(); ``` ### Response #### Success Response (200) `Rule[]` - Array of active mock rules #### Response Example ```ts // Debug active mocks await twd.mockRequest("getUser", { method: "GET", url: "/api/user", response: { id: 1 } }); await twd.mockRequest("getPosts", { method: "GET", url: "/api/posts", response: [] }); const activeMocks = twd.getRequestMockRules(); console.log(`Active mocks: ${activeMocks.length}`); activeMocks.forEach(mock => { console.log(`Mock: ${mock.alias} - ${mock.method} ${mock.url}`); }); ``` ``` -------------------------------- ### Simulate User Click Events in TWD Tests Source: https://github.com/brikev/twd/blob/main/docs/tutorial/first-test.md TypeScript code showing how to simulate real user interactions using userEvent from React Testing Library integrated with TWD. Demonstrates importing userEvent, selecting elements, and clicking them using the raw DOM element (.el property). Provides realistic user interaction simulation beyond simple click commands. ```ts import { twd, userEvent } from "twd-js"; ``` ```ts const counterButton = await twd.get("[data-testid='counter-button']"); await userEvent.click(counterButton.el); ``` -------------------------------- ### Define mock requests for creating todo and initial empty list Source: https://github.com/brikev/twd/blob/main/docs/tutorial/api-mocking.md Sets up mockRequest calls for POST createTodo and GET getTodoList returning an empty array, used before navigating to the page to simulate an initially empty todo list. ```typescript // request of creating a todo await twd.mockRequest("createTodo", { method: "POST", url: "/api/todos", response: todoListMock[0], status: 200, }); // empty list on first load await twd.mockRequest("getTodoList", { method: "GET", url: "/api/todos", response: [], status: 200, }); ``` -------------------------------- ### Test Complete User Workflows Source: https://github.com/brikev/twd/blob/main/docs/writing-tests.md Emphasizes testing end-to-end user workflows rather than isolated functions. This example demonstrates a user registration flow, from visiting the registration page to filling the form, submitting, and verifying the subsequent dashboard view. ```typescript describe("User Registration Flow", () => { it("should register new user and redirect to dashboard", async () => { await twd.visit("/register"); const user = userEvent.setup(); // Fill registration form await user.type(await twd.get("#email"), "user@example.com"); await user.type(await twd.get("#password"), "securePassword123"); await user.type(await twd.get("#confirmPassword"), "securePassword123"); // Submit form await user.click(await twd.get("button[type='submit']")); // Verify redirect and welcome message twd.url().should("contain.url", "/dashboard"); const welcome = await twd.get("h1"); welcome.should("contain.text", "Welcome"); }); }); ``` -------------------------------- ### Initialize Request Mocking (TypeScript) Source: https://github.com/brikev/twd/blob/main/docs/api/twd-commands.md Shows how to initialize the service worker for request interception using twd.initRequestMocking. It includes examples for initializing in a test loader and within individual test suites using Promise-based and async/await syntax. ```typescript // In test loader (src/loadTests.ts) import { twd } from "twd-js"; twd.initRequestMocking() .then(() => { console.log("Request mocking initialized"); }) .catch((err) => { console.error("Error initializing request mocking:", err); }); ``` ```typescript // In individual test (if needed) describe("API Tests", () => { beforeEach(async () => { await twd.initRequestMocking(); }); it("should mock API calls", async () => { // Mocking is now available }); }); ``` -------------------------------- ### GET be.empty Source: https://github.com/brikev/twd/blob/main/docs/api/assertions.md Verifies that an element has no text content. Use to assert cleared inputs or placeholder-only elements. ```APIDOC ## GET be.empty ### Description Verifies that an element has no text content. ### Method Assertion ### Endpoint be.empty ### Parameters #### Path Parameters - N/A #### Query Parameters - N/A #### Request Body - N/A ### Request Example { "example": "element.should(\"be.empty\")" } ### Response #### Success Response (200) - Assertion passes when element text is empty #### Response Example { "example": "// Pass: element is empty\nclearedInput.should(\"be.empty\");\n// After clearing\nconst user = userEvent.setup();\nconst textArea = await twd.get(\"textarea\");\nawait user.clear(textArea.el);\ntextArea.should(\"be.empty\");" } #### Negation Example { "example": "// Pass: element has text content\ncontentDiv.should(\"not.be.empty\");" } #### Error Handling - Useful after user actions like clear() - Negation confirms content exists ``` -------------------------------- ### GET have.class Source: https://github.com/brikev/twd/blob/main/docs/api/assertions.md Verifies that an element has a specific CSS class. Use to assert styling state, component status, and interaction readiness. ```APIDOC ## GET have.class ### Description Verifies that an element has a specific CSS class. ### Method Assertion ### Endpoint have.class ### Parameters #### Path Parameters - N/A #### Query Parameters - N/A #### Request Body - className (string) - Required - CSS class the element must possess ### Request Example { "example": "element.should(\"have.class\", \"btn-primary\")" } ### Response #### Success Response (200) - Assertion passes when element includes the specified class #### Response Example { "example": "// Pass: button states\nprimaryButton.should(\"have.class\", \"btn-primary\");\nprimaryButton.should(\"have.class\", \"btn\");\n// Status indicators\nalert.should(\"have.class\", \"alert-success\");\n// Dynamic classes\nactiveTab.should(\"have.class\", \"active\");\n// Multiple class checks\nconst element = await twd.get(\".complex-element\");\nelement.should(\"have.class\", \"component\");\nelement.should(\"have.class\", \"visible\");\nelement.should(\"have.class\", \"interactive\");" } #### Negation Example { "example": "// Pass: class is not present\nelement.should(\"not.have.class\", \"disabled\");" } #### Error Handling - Repeat the assertion for multiple classes as needed - Useful for validating UI state and conditional styling ``` -------------------------------- ### Select Elements with CSS Selectors in TWD Source: https://github.com/brikev/twd/blob/main/docs/tutorial/first-test.md TypeScript code examples demonstrating element selection using TWD's get method with CSS selectors. Uses data-testid attributes for reliable element targeting, similar to React Testing Library or Cypress patterns. The get method supports any CSS selector and automatically retries for up to 2 seconds. ```ts const title = await twd.get("[data-testid='welcome-title']"); ``` ```ts const counterButton = await twd.get("[data-testid='counter-button']"); ``` -------------------------------- ### Organize Tests with Lifecycle Hooks in TWD.JS Source: https://context7.com/brikev/twd/llms.txt This snippet illustrates how to structure test suites using `describe`, `it`, `beforeEach`, and `afterEach` hooks provided by TWD.JS runner. It covers setup and teardown logic for tests, including skipping and focusing specific tests. ```typescript import { twd, userEvent } from "twd-js"; import { describe, it, beforeEach, afterEach } from "twd-js/runner"; describe("User authentication", () => { // Run before each test in this suite beforeEach(async () => { // Reset application state localStorage.clear(); await twd.visit("/"); }); // Run after each test in this suite afterEach(() => { // Clean up mocks twd.clearRequestMockRules(); }); it("should login successfully with valid credentials", async () => { await twd.visit("/login"); const emailInput = await twd.get("input#email"); const passwordInput = await twd.get("input#password"); const submitButton = await twd.get("button[type='submit']"); await userEvent.type(emailInput.el, "user@example.com"); await userEvent.type(passwordInput.el, "password123"); await userEvent.click(submitButton.el); await twd.wait(500); // Wait for navigation twd.url().should("eq", "http://localhost:3000/dashboard"); }); // Skip this test temporarily it.skip("should handle forgotten password", async () => { // This test will not run }); // Run only this test (when any .only exists, only those run) it.only("should show validation errors", async () => { await twd.visit("/login"); const submitButton = await twd.get("button[type='submit']"); await userEvent.click(submitButton.el); const errorMessage = await twd.get(".error-message"); errorMessage.should("be.visible"); errorMessage.should("contain.text", "Email is required"); }); }); ``` -------------------------------- ### GET have.attr Source: https://github.com/brikev/twd/blob/main/docs/api/assertions.md Verifies that an element has a specific attribute with an optional value. Supports standard and custom attributes, including booleans. ```APIDOC ## GET have.attr ### Description Verifies that an element has a specific attribute with an optional value. ### Method Assertion ### Endpoint have.attr ### Parameters #### Path Parameters - N/A #### Query Parameters - N/A #### Request Body - attributeName (string) - Required - Name of the attribute to check - expectedValue (string) - Optional - Value the attribute must equal (omit for boolean attributes) ### Request Example { "example": "element.should(\"have.attr\", \"type\", \"email\")" } ### Response #### Success Response (200) - Assertion passes when attribute exists and matches expected value (if provided) #### Response Example { "example": "// Pass: form attributes\nemailInput.should(\"have.attr\", \"type\", \"email\");\nemailInput.should(\"have.attr\", \"required\");\n// Link attributes\nexternalLink.should(\"have.attr\", \"target\", \"_blank\");\n// Custom data attributes\nuserCard.should(\"have.attr\", \"data-user-id\", \"123\");" } #### Negation Example { "example": "// Pass: attribute missing or value mismatch\noptionalField.should(\"not.have.attr\", \"required\");\ninternalLink.should(\"not.have.attr\", \"target\", \"_blank\");" } #### Error Handling - Boolean attributes: only check existence by omitting expectedValue - Custom data-* attributes fully supported ``` -------------------------------- ### GET have.text Source: https://github.com/brikev/twd/blob/main/docs/api/assertions.md Verifies that an element's text content matches exactly. Use for precise string equality checks and case-sensitive validations. ```APIDOC ## GET have.text ### Description Verifies that an element's text content matches exactly. ### Method Assertion ### Endpoint have.text ### Parameters #### Path Parameters - N/A #### Query Parameters - N/A #### Request Body - expectedText (string) - Required - Exact text the element must contain ### Request Example { "example": "element.should(\"have.text\", \"Welcome to TWD\")" } ### Response #### Success Response (200) - Assertion passes when element text equals expectedText #### Response Example { "example": "// Pass: exact match\nconst heading = await twd.get(\"h1\");\nheading.should(\"have.text\", \"Welcome to TWD\");" } #### Negation Example { "example": "// Pass: element text is not the excluded value\nelement.should(\"not.have.text\", \"Error occurred\");" } #### Error Handling - Mismatch triggers assertion failure with expected vs actual text - Case-sensitive comparison; use contain.text for partial matching ``` -------------------------------- ### GET contain.text Source: https://github.com/brikev/twd/blob/main/docs/api/assertions.md Verifies that an element's text content contains a substring. Use for partial matches and flexible validations. ```APIDOC ## GET contain.text ### Description Verifies that an element's text content contains a substring. ### Method Assertion ### Endpoint contain.text ### Parameters #### Path Parameters - N/A #### Query Parameters - N/A #### Request Body - substring (string) - Required - Substring the element text must include ### Request Example { "example": "element.should(\"contain.text\", \"premium quality\")" } ### Response #### Success Response (200) - Assertion passes when element text includes the substring #### Response Example { "example": "// Pass: partial match\nconst title = await twd.get(\"h1\");\ntitle.should(\"contain.text\", \"Product\"); // Matches \"Product Details\"" } #### Negation Example { "example": "// Pass: element text does not contain the excluded substring\nsuccessMessage.should(\"not.contain.text\", \"error\");" } #### Error Handling - Use for partial matching; use have.text for exact matching - Case-sensitive by default ```