### Configuration Examples Source: https://testing-library.com/docs/dom-testing-library/api-configuration Examples of how to use the `configure` function with different frameworks. ```APIDOC ## Example: DOM Testing Library Configuration ### Description Configures DOM Testing Library with a custom `testIdAttribute` and a custom `getElementError` function. ### Method POST ### Endpoint /configure ### Parameters #### Request Body - **options** (object) - Required - Configuration object. - **testIdAttribute** (string) - Optional - The attribute used by `getByTestId`. Defaults to `data-testid`. - **getElementError** (function) - Optional - A function that returns the error used when get or find queries fail. Takes the error message and container object as arguments. ### Request Example ```javascript import {configure} from '@testing-library/dom' import serialize from 'my-custom-dom-serializer' configure({ testIdAttribute: 'data-my-test-id', getElementError: (message, container) => { const customMessage = [message, serialize(container.firstChild)].join( '\n\n', ) return new Error(customMessage) }, }) ``` ``` ```APIDOC ## Example: React Testing Library Configuration ### Description Configures React Testing Library with a custom `testIdAttribute`. ### Method POST ### Endpoint /configure ### Parameters #### Request Body - **options** (object) - Required - Configuration object. - **testIdAttribute** (string) - Optional - The attribute used by `getByTestId`. Defaults to `data-testid`. ### Request Example ```javascript import {configure} from '@testing-library/react' configure({testIdAttribute: 'data-my-test-id'}) ``` ``` ```APIDOC ## Example: Angular Testing Library Configuration ### Description Configures Angular Testing Library with a custom `testIdAttribute` nested within the `dom` configuration. ### Method POST ### Endpoint /configure ### Parameters #### Request Body - **options** (object) - Required - Configuration object. - **dom** (object) - Optional - DOM-specific configuration. - **testIdAttribute** (string) - Optional - The attribute used by `getByTestId`. Defaults to `data-testid`. ### Request Example ```typescript import {configure} from '@testing-library/angular' configure({ dom: { testIdAttribute: 'data-my-test-id', }, }) ``` ``` ```APIDOC ## Example: Cypress Testing Library Configuration ### Description Configures Cypress Testing Library with a custom `testIdAttribute`. ### Method POST ### Endpoint /configure ### Parameters #### Request Body - **options** (object) - Required - Configuration object. - **testIdAttribute** (string) - Optional - The attribute used by `getByTestId`. Defaults to `data-testid`. ### Request Example ```javascript import {configure} from '@testing-library/cypress' configure({testIdAttribute: 'data-my-test-id'}) ``` ``` -------------------------------- ### React Component Quickstart Test Source: https://testing-library.com/docs/react-testing-library/example-intro A minimal setup for testing a React component. It renders the component, simulates a user click, and asserts the expected output. Requires @testing-library/react, @testing-library/user-event, and @testing-library/jest-dom. ```jsx import {render, screen} from '@testing-library/react' import userEvent from '@testing-library/user-event' import '@testing-library/jest-dom' import Fetch from './fetch' test('loads and displays greeting', async () => { // ARRANGE render() // ACT await userEvent.click(screen.getByText('Load Greeting')) await screen.findByRole('heading') // ASSERT expect(screen.getByRole('heading')).toHaveTextContent('hello there') expect(screen.getByRole('button')).toBeDisabled() }) ``` -------------------------------- ### Install rtl-simple-queries Source: https://testing-library.com/docs/ecosystem-rtl-simple-queries Installation commands for npm and Yarn package managers. ```shell npm install --save-dev rtl-simple-queries ``` ```shell yarn add --dev rtl-simple-queries ``` -------------------------------- ### Install react-select-event Source: https://testing-library.com/docs/ecosystem-react-select-event Installation commands for npm and yarn package managers. ```bash npm install --save-dev react-select-event ``` ```bash yarn add --dev react-select-event ``` -------------------------------- ### Install riot-testing-library with npm Source: https://testing-library.com/docs/ecosystem-riot-testing-library Install the library as a development dependency using npm. ```bash npm install --save-dev riot-testing-library ``` -------------------------------- ### Install riot-testing-library with Yarn Source: https://testing-library.com/docs/ecosystem-riot-testing-library Install the library as a development dependency using Yarn. ```bash yarn add --dev riot-testing-library ``` -------------------------------- ### Install WebdriverIO Testing Library Source: https://testing-library.com/docs/webdriverio-testing-library/intro Commands to install the library using npm or Yarn. ```bash npm install --save-dev @testing-library/webdriverio ``` ```bash yarn add --dev @testing-library/webdriverio ``` -------------------------------- ### Install React Testing Library Source: https://testing-library.com/docs/react-testing-library/intro Install the library and its peer dependency using npm or yarn. ```bash npm install --save-dev @testing-library/react @testing-library/dom ``` ```bash yarn add --dev @testing-library/react @testing-library/dom ``` -------------------------------- ### MSW API Mocking Setup Source: https://testing-library.com/docs/react-testing-library/example-intro Sets up a Mock Service Worker server to intercept network requests. This example configures a GET request to '/greeting' to return a JSON response and includes lifecycle handlers for the server. ```jsx import React from 'react' import {http, HttpResponse} from 'msw' import {setupServer} from 'msw/node' import {render, fireEvent, screen} from '@testing-library/react' import '@testing-library/jest-dom' import Fetch from '../fetch' const server = setupServer( http.get('/greeting', () => { return HttpResponse.json({greeting: 'hello there'}) }), ) beforeAll(() => server.listen()) afterEach(() => server.resetHandlers()) afterAll(() => server.close()) ``` -------------------------------- ### Install testing-library-selector with npm Source: https://testing-library.com/docs/ecosystem-testing-library-selector Install the library as a dev dependency using npm. ```bash npm install --save-dev testing-library-selector ``` -------------------------------- ### Install Puppeteer Testing Library (Yarn) Source: https://testing-library.com/docs/pptr-testing-library/intro Install the necessary packages using Yarn. ```bash yarn add --dev puppeteer pptr-testing-library ``` -------------------------------- ### Install Qwik Testing Library and DOM dependencies Source: https://testing-library.com/docs/qwik-testing-library/setup Install the core testing libraries as development dependencies. ```bash npm install --save-dev @noma.to/qwik-testing-library @testing-library/dom ``` ```bash yarn add --dev @noma.to/qwik-testing-library @testing-library/dom ``` -------------------------------- ### Install development dependencies Source: https://testing-library.com/docs/svelte-testing-library/setup Install the required testing packages using npm or yarn. ```bash npm install --save-dev \ @testing-library/svelte \ @testing-library/jest-dom \ @sveltejs/vite-plugin-svelte \ vitest \ jsdom ``` ```bash yarn add --dev \ @testing-library/svelte \ @testing-library/jest-dom \ @sveltejs/vite-plugin-svelte \ vitest \ jsdom ``` -------------------------------- ### Install testing-library-selector with Yarn Source: https://testing-library.com/docs/ecosystem-testing-library-selector Install the library as a dev dependency using Yarn. ```bash yarn add --dev testing-library-selector ``` -------------------------------- ### Setup JSDOM without Jest Source: https://testing-library.com/docs/react-testing-library/setup Install JSDOM and global-jsdom to simulate browser APIs in Node environments like Mocha. ```bash npm install --save-dev jsdom global-jsdom ``` ```bash yarn add --dev jsdom global-jsdom ``` ```bash mocha --require global-jsdom/register ``` -------------------------------- ### Full React Example with MSW Mocking Source: https://testing-library.com/docs/react-testing-library/example-intro A comprehensive example demonstrating API mocking using Mock Service Worker (MSW) for testing React components. It includes setup for the mock server, handling successful responses, and managing server errors. ```jsx import React from 'react' import {http, HttpResponse} from 'msw' import {setupServer} from 'msw/node' import {render, fireEvent, screen} from '@testing-library/react' import '@testing-library/jest-dom' import Fetch from '../fetch' const server = setupServer( http.get('/greeting', () => { return HttpResponse.json({greeting: 'hello there'}) }), ) beforeAll(() => server.listen()) afterEach(() => server.resetHandlers()) afterAll(() => server.close()) test('loads and displays greeting', async () => { render() fireEvent.click(screen.getByText('Load Greeting')) await screen.findByRole('heading') expect(screen.getByRole('heading')).toHaveTextContent('hello there') expect(screen.getByRole('button')).toBeDisabled() }) test('handles server error', async () => { server.use( http.get('/greeting', () => { return new HttpResponse(null, {status: 500}) }), ) render() fireEvent.click(screen.getByText('Load Greeting')) await screen.findByRole('alert') expect(screen.getByRole('alert')).toHaveTextContent('Oops, failed to fetch!') expect(screen.getByRole('button')).not.toBeDisabled() }) ``` -------------------------------- ### Install Vitest UI Source: https://testing-library.com/docs/svelte-testing-library/setup Optionally install the Vitest UI for interactive test progress tracking. ```bash npm install --save-dev @vitest/ui ``` ```bash yarn add --dev @vitest/ui ``` -------------------------------- ### Install Solid Testing Library Source: https://testing-library.com/docs/solid-testing-library/intro Commands to install the library as a development dependency using npm or Yarn. ```shell npm install --save-dev @solidjs/testing-library ``` ```shell yarn add --dev @solidjs/testing-library ``` -------------------------------- ### Install Puppeteer Testing Library (npm) Source: https://testing-library.com/docs/pptr-testing-library/intro Install the necessary packages using npm. ```bash npm install --save-dev puppeteer pptr-testing-library ``` -------------------------------- ### Setup Function for userEvent Tests Source: https://testing-library.com/docs/user-event/intro Define a setup function to initialize userEvent.setup() and render the component. This promotes reusability for tests involving user interactions. ```javascript import userEvent from '@testing-library/user-event' // setup function function setup(jsx) { return { user: userEvent.setup(), // Import `render` from the framework library of your choice. // See https://testing-library.com/docs/dom-testing-library/install#wrappers ...render(jsx), } } test('render with a setup function', async () => { const {user} = setup() // ... }) ``` -------------------------------- ### Install Preact Testing Library Source: https://testing-library.com/docs/preact-testing-library/intro Install the library as a development dependency using npm or yarn. ```bash npm install --save-dev @testing-library/preact ``` ```bash yarn add --dev @testing-library/preact ``` -------------------------------- ### Install testing dependencies Source: https://testing-library.com/docs/svelte-testing-library/setup Install the required testing libraries and environment tools using npm or yarn. ```bash npm install --save-dev \ @testing-library/svelte \ @testing-library/jest-dom \ svelte-jester \ jest \ jest-environment-jsdom ``` ```bash yarn add --dev \ @testing-library/svelte \ @testing-library/jest-dom \ svelte-jester \ jest \ jest-environment-jsdom ``` -------------------------------- ### userEvent.setup() Options Source: https://testing-library.com/docs/user-event/options Configuration options for customizing user-event behavior during test setup. ```APIDOC ## userEvent.setup() Options ### Description These options allow you to adjust the behavior of user-event APIs when initialized via `userEvent.setup()`. ### Parameters - **advanceTimers** (function) - Optional - Function to advance timers when using fake timers (e.g., jest.advanceTimersByTime). - **applyAccept** (boolean) - Optional - Automatically discard files not matching the 'accept' property in upload(). Default: true. - **autoModify** (boolean) - Optional - Automatically apply modifier keys for printable characters. Default: true. - **delay** (number | null) - Optional - Delay in milliseconds between subsequent inputs. Default: 0. - **document** (Document) - Optional - The document object to use. Default: element.ownerDocument or globalThis.document. - **keyboardMap** (Array) - Optional - Array of keyboard keys for layout/localization. Default: US-104-QWERTY. - **pointerEventsCheck** (PointerEventsCheckLevel) - Optional - Frequency of pointer-events: none checks. Default: PointerEventsCheckLevel.EachApiCall. - **pointerMap** (Array) - Optional - Array of available pointer keys. Default: Mouse and touchscreen. - **skipAutoClose** (boolean) - Optional - Opt out of automatically releasing keys after type(). Default: false. - **skipClick** (boolean) - Optional - Opt out of implied click during type(). Default: false. - **skipHover** (boolean) - Optional - Opt out of implied hover during click(). Default: false. - **writeToClipboard** (boolean) - Optional - Whether to write to the Clipboard API on cut/copy. Default: true (when using setup()). ### Request Example const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime, delay: 10, skipHover: true }); ``` -------------------------------- ### Install jasmine-dom Source: https://testing-library.com/docs/ecosystem-jasmine-dom Install the library as a development dependency using npm or yarn. ```bash npm install --save-dev @testing-library/jasmine-dom ``` ```bash yarn add --dev @testing-library/jasmine-dom ``` -------------------------------- ### Install bs-platform with npm Source: https://testing-library.com/docs/bs-react-testing-library/intro Install bs-platform, the BuckleScript compiler, as a development dependency using npm. ```bash npm install --save-dev bs-platform ``` -------------------------------- ### Install bs-platform with Yarn Source: https://testing-library.com/docs/bs-react-testing-library/intro Install bs-platform, the BuckleScript compiler, as a development dependency using Yarn. ```bash yarn add --dev bs-platform ``` -------------------------------- ### Install CLI Testing Library with npm Source: https://testing-library.com/docs/ecosystem-cli-testing-library Install the library as a dev dependency using npm. ```bash npm install --save-dev cli-testing-library ``` -------------------------------- ### Install jest-dom Source: https://testing-library.com/docs/ecosystem-jest-dom Install the library as a development dependency using npm or Yarn. ```bash npm install --save-dev @testing-library/jest-dom ``` ```bash yarn add --dev @testing-library/jest-dom ``` -------------------------------- ### Install CLI Testing Library with Yarn Source: https://testing-library.com/docs/ecosystem-cli-testing-library Install the library as a dev dependency using Yarn. ```bash yarn add --dev cli-testing-library ``` -------------------------------- ### Install React Testing Library with TypeScript Source: https://testing-library.com/docs/react-testing-library/intro Install the library along with necessary type definitions for React and ReactDOM. ```bash npm install --save-dev @testing-library/react @testing-library/dom @types/react @types/react-dom ``` ```bash yarn add --dev @testing-library/react @testing-library/dom @types/react @types/react-dom ``` -------------------------------- ### Install DOM environment providers Source: https://testing-library.com/docs/qwik-testing-library/setup Install a DOM environment like jsdom or happy-dom to execute tests. ```bash npm install --save-dev jsdom ``` ```bash yarn add --dev jsdom ``` ```bash npm install --save-dev happy-dom ``` ```bash yarn add --dev happy-dom ``` -------------------------------- ### Install Marko Testing Library Source: https://testing-library.com/docs/marko-testing-library/intro Commands to install the library as a development dependency using npm or Yarn. ```bash npm install --save-dev @marko/testing-library ``` ```bash yarn add --dev @marko/testing-library ``` -------------------------------- ### Install user-event dependencies Source: https://testing-library.com/docs/react-testing-library/migrate-from-enzyme Install the required packages for user-event via npm or yarn. ```bash npm install --save-dev @testing-library/user-event @testing-library/dom ``` ```bash yarn add --dev @testing-library/user-event @testing-library/dom ``` -------------------------------- ### Install query-extensions Source: https://testing-library.com/docs/ecosystem-query-extensions Use npm or yarn to add the experimental query-extensions library as a development dependency. ```bash npm install --save-dev query-extensions ``` ```bash yarn add --dev query-extensions ``` -------------------------------- ### Install jsdom and global-jsdom Source: https://testing-library.com/docs/dom-testing-library/setup Install the necessary packages as development dependencies using npm or Yarn. ```bash npm install --save-dev jsdom global-jsdom ``` ```bash yarn add --dev jsdom global-jsdom ``` -------------------------------- ### Query by Role Example Source: https://testing-library.com/docs/queries/about Demonstrates the recommended approach for querying elements by their role and accessible name. ```javascript getByRole('button', {name: /submit/i}) ``` -------------------------------- ### Install Nightwatch Testing Library Source: https://testing-library.com/docs/nightwatch-testing-library/intro Install the package as a development dependency using npm or yarn. ```bash npm install --save-dev @testing-library/nightwatch ``` ```bash yarn add --dev @testing-library/nightwatch ``` -------------------------------- ### Install DOM Testing Library with Yarn Source: https://testing-library.com/docs/dom-testing-library/install Install the DOM Testing Library as a development dependency using Yarn. ```bash yarn add --dev @testing-library/dom ``` -------------------------------- ### Install DOM Testing Library with npm Source: https://testing-library.com/docs/dom-testing-library/install Install the DOM Testing Library as a development dependency using npm. ```bash npm install --save-dev @testing-library/dom ``` -------------------------------- ### Install React Testing Library with npm Source: https://testing-library.com/docs/react-testing-library/migrate-from-enzyme Install React Testing Library and jest-dom using npm. These are essential for setting up your testing environment. ```bash npm install --save-dev @testing-library/react @testing-library/jest-dom ``` -------------------------------- ### Install Svelte Testing Library with npm Source: https://testing-library.com/docs/svelte-testing-library/intro Use this command to install the library as a development dependency using npm. ```bash npm install --save-dev @testing-library/svelte ``` -------------------------------- ### Install React Native Testing Library Source: https://testing-library.com/docs/react-native-testing-library/intro Commands to install the library as a development dependency using npm or Yarn. ```bash npm install --save-dev @testing-library/react-native ``` ```bash yarn add --dev @testing-library/react-native ``` -------------------------------- ### Install Svelte Testing Library with Yarn Source: https://testing-library.com/docs/svelte-testing-library/intro Use this command to install the library as a development dependency using Yarn. ```bash yarn add --dev @testing-library/svelte ``` -------------------------------- ### DOM Structure Example Source: https://testing-library.com/docs/queries/about Sample HTML structure used for demonstrating query methods. ```html
``` -------------------------------- ### Install bs-jest with npm Source: https://testing-library.com/docs/bs-react-testing-library/intro Install bs-jest, the recommended Jest wrapper for ReasonML, as a development dependency using npm. ```bash npm install --save-dev @glennsl/bs-jest ``` -------------------------------- ### Install bs-jest-dom with npm Source: https://testing-library.com/docs/ecosystem-bs-jest-dom Use this command to install bs-jest-dom as a development dependency using npm. ```bash npm install --save-dev bs-jest-dom ``` -------------------------------- ### Testing Library - By Placeholder Text Usage Examples Source: https://testing-library.com/docs/queries/byplaceholdertext Examples of using `getByPlaceholderText` with different frameworks and tools. ```APIDOC ## Usage Examples ### React ```javascript import { render, screen } from '@testing-library/react'; render(); const inputNode = screen.getByPlaceholderText('Username'); ``` ### Angular ```javascript import { render, screen } from '@testing-library/angular'; await render(MyComponent); const inputNode = screen.getByPlaceholderText('Username'); ``` ### Cypress ```javascript cy.findByPlaceholderText('Username').should('exist'); ``` ``` -------------------------------- ### Install @testing-library/user-event with npm Source: https://testing-library.com/docs/user-event/install Use this command to install the user-event package as a development dependency in your project using npm. ```bash npm install --save-dev @testing-library/user-event ``` -------------------------------- ### Testcafe Testing Library Examples Source: https://testing-library.com/docs/testcafe-testing-library/intro Examples demonstrating various query methods like getByPlaceholderText, getByText, getByLabelText, and queryAllByText provided by testcafe-testing-library. ```javascript import {screen} from '@testing-library/testcafe' test('getByPlaceHolderText', async t => { await t.typeText( screen.getByPlaceholderText('Placeholder Text'), 'Hello Placeholder', ) }) test('getByText', async t => { await t.click(screen.getByText('getByText')) }) test('getByLabelText', async t => { await t.typeText( screen.getByLabelText('Label For Input Labelled By Id'), 'Hello Input Labelled By Id', ) }) test('queryAllByText', async t => { await t.expect(screen.queryAllByText('Button Text').exists).ok() await t .expect(screen.queryAllByText('Non-existing Button Text').exists) .notOk() }) ``` -------------------------------- ### Install bs-jest with Yarn Source: https://testing-library.com/docs/bs-react-testing-library/intro Install bs-jest, the recommended Jest wrapper for ReasonML, as a development dependency using Yarn. ```bash yarn add --dev @glennsl/bs-jest ``` -------------------------------- ### Vitest Manual Cleanup Setup Source: https://testing-library.com/docs/react-testing-library/setup If not using Vitest globals, import 'cleanup' and call it manually in a top-level 'afterEach' hook. This requires a separate setup file. ```typescript import {defineConfig} from 'vitest/config' export default defineConfig({ test: { setupFiles: ['vitest-cleanup-after-each.ts'], }, }) ``` ```typescript import {cleanup} from '@testing-library/react' import {afterEach} from 'vitest' afterEach(() => { cleanup() }) ``` -------------------------------- ### Install React Testing Library with Yarn Source: https://testing-library.com/docs/react-testing-library/migrate-from-enzyme Install React Testing Library and jest-dom using Yarn. This command adds the necessary testing utilities as development dependencies. ```bash yarn add --dev @testing-library/react @testing-library/jest-dom ``` -------------------------------- ### Install Cypress Testing Library Source: https://testing-library.com/docs/cypress-testing-library/intro Install the necessary dependencies for Cypress Testing Library using npm or Yarn. ```bash npm install --save-dev cypress @testing-library/cypress ``` ```bash yarn add --dev cypress @testing-library/cypress ``` -------------------------------- ### Setup Browser Queries Source: https://testing-library.com/docs/webdriverio-testing-library/intro Initializes WebdriverIO browser object with DOM Testing Library queries. ```javascript import {setupBrowser} from '@testing-library/webdriverio' it('can click button', async () => { const {getByText} = setupBrowser(browser) const button = await getByText('Button Text') await button.click() expect(await button.getText()).toEqual('Button Clicked') }) ``` -------------------------------- ### Setup User Event Instance Source: https://testing-library.com/docs/user-event/setup Use `userEvent.setup()` to create a configured instance for simulating user interactions. This instance shares input device state across multiple interactions. ```javascript import userEvent from '@testing-library/user-event' const user = userEvent.setup() await user.keyboard('[ShiftLeft>]') // Press Shift (without releasing it) await user.click(element) // Perform a click with `shiftKey: true` ``` -------------------------------- ### Install Angular Testing Library dependencies Source: https://testing-library.com/docs/angular-testing-library/intro Commands to install the library and its required DOM dependency using package managers. ```bash npm install --save-dev @testing-library/angular @testing-library/dom ``` ```bash yarn add --dev @testing-library/angular @testing-library/dom ``` -------------------------------- ### Direct APIs Source: https://testing-library.com/docs/user-event/setup You can also call the APIs directly on the default export. This will call `setup` internally and then use the method on the instance. Using the methods on the instances returned by `userEvent.setup()` is recommended for more complex scenarios. ```APIDOC ## Direct APIs ### Description This section describes the direct API methods available on the default export of the `user-event` library. These methods internally call `setup()` and then use the resulting instance. While convenient for simple tests, using methods on an instance obtained from `userEvent.setup()` is generally recommended for better control and state management. ### Methods - **`userEvent.click(element, options?)`**: Simulates a click event on an element. - **`userEvent.keyboard(value)`**: Simulates keyboard input. - **`userEvent.type(element, text, options?)`**: Simulates typing text into an element. *(Note: This is a simplified representation. Refer to the official documentation for a complete list of direct APIs and their options.)* ### Request Example ```javascript import userEvent from '@testing-library/user-event' // Simulating a click directly await userEvent.click(document.getElementById('myButton')) // Simulating typing directly await userEvent.type(document.getElementById('myInput'), 'Hello World') ``` ### Response These methods typically return a Promise that resolves when the interaction is complete. Specific return values depend on the method used. ``` -------------------------------- ### Basic component rendering Source: https://testing-library.com/docs/marko-testing-library/api Examples of rendering a Marko template into the document body. ```javascript import {render} from '@marko/testing-library' import MyTemplate from './my-template.marko' render(MyTemplate) ``` ```javascript import {render, screen} from '@marko/testing-library' import Greeting from './greeting.marko' test('renders a message', async () => { const {container} = await render(Greeting, {name: 'Marko'}) expect(screen.getByText(/Marko/)).toBeInTheDocument() expect(container.firstChild).toMatchInlineSnapshot(`

Hello, Marko!

`) }) ``` -------------------------------- ### Configure Vitest setup file Source: https://testing-library.com/docs/qwik-testing-library/setup Initialize DOM matchers and force Qwik runtime flags for the test environment. ```typescript // Configure DOM matchers to work in Vitest import '@testing-library/jest-dom/vitest' // This has to run before qdev.ts loads. `beforeAll` is too late globalThis.qTest = false // Forces Qwik to run as if it was in a Browser globalThis.qRuntimeQrl = true globalThis.qDev = true globalThis.qInspector = false ``` -------------------------------- ### Custom Render Function for Abstract Router Mode Source: https://testing-library.com/docs/vue-testing-library/faq Provides an example of creating a custom `renderApp` function that encapsulates the setup for Vue Router in `abstract` mode. This reduces boilerplate code when rendering components that rely on routing. ```javascript // test-utils.js import {render} from '@testing-library/vue' import VueRouter from 'vue-router' export async function renderApp(component, options) { const router = new VueRouter({ mode: 'abstract', routes: [ // Your routes here ], }) const renderResult = render(component, { routes: router, ...options, }) // Unlike the router in `hash` mode, the initial routing stack is empty. So, // you need to push an initial route to the stack. await router.push('/') return renderResult } ``` -------------------------------- ### Setup a User Event Instance Source: https://testing-library.com/docs/user-event/setup The `userEvent.setup()` API allows you to configure an instance of user-event that shares input device state, enabling multiple consecutive interactions that mimic real user behavior. ```APIDOC ## Setup a User Event Instance ### Description The `userEvent.setup()` API applies workarounds to the document and allows you to configure an "instance" of `user-event`. Methods on this instance share one input device state, e.g. which keys are pressed. This allows to write multiple consecutive interactions that behave just like the described interactions by a real user. ### Method `setup(options?: Options): UserEvent` ### Parameters #### Options - **delay** (number) - Optional - The delay in milliseconds between each interaction. - **advanceTimers** (boolean) - Optional - Whether to advance timers during interactions. ### Request Example ```javascript import userEvent from '@testing-library/user-event' const user = userEvent.setup() await user.keyboard('[ShiftLeft>]') // Press Shift (without releasing it) await user.click(element) // Perform a click with `shiftKey: true` ``` ### Response Returns a `UserEvent` instance with methods for simulating user interactions. ``` -------------------------------- ### Setup Browser with setupBrowser Source: https://testing-library.com/docs/webdriverio-testing-library/intro The `setupBrowser` function integrates dom-testing-library queries into WebdriverIO. It accepts a WebdriverIO browser object and returns modified queries that work with WebdriverIO elements. All queries are asynchronous and default to `document.body`. It also adds these queries as commands to the browser and WebdriverIO elements. ```APIDOC ## setupBrowser ### Description Accepts a WebdriverIO browser object and returns dom-testing-library queries modified to return WebdriverIO elements like normal selectors. All queries are async and are bound to `document.body` by default. ### Usage ```javascript import { setupBrowser } from '@testing-library/webdriverio' it('can click button', async () => { const { getByText } = setupBrowser(browser) const button = await getByText('Button Text') await button.click() expect(await button.getText()).toEqual('Button Clicked') }) ``` ### Browser and Element Commands `setupBrowser` also adds queries as commands to the browser and to all WebdriverIO elements. The browser commands are scoped to `document.body`. The element commands are scoped to the element in the same way as if it was passed to `within`. #### Browser Command Example ```javascript it('adds queries as browser commands', async () => { setupBrowser(browser) expect(await browser.getByText('Page Heading')).toBeDefined() }) ``` #### Element Command Example ```javascript it('adds queries as element commands scoped to element', async () => { setupBrowser(browser) const nested = await browser.$('*[data-testid="nested"]') const button = await nested.getByText('Button Text') await button.click() expect(await button.getText()).toEqual('Button Clicked') }) ``` ### Synchronous Mode When using sync mode these commands are also synchronous: #### Synchronous Browser Command Example ```javascript it('adds queries as browser commands', async () => { setupBrowser(browser) expect(browser.getByText('Page Heading')).toBeDefined() }) ``` #### Synchronous Element Command Example ```javascript it('adds queries as element commands scoped to element', async () => { setupBrowser(browser) const nested = browser.$('*[data-testid="nested"]') const button = nested.getByText('Button Text') button.click() expect(button.getText()).toEqual('Button Clicked') }) ``` ### Chainable Queries When using v7.19 or higher of WebdriverIO you can also use chainable queries. Chainable queries are added to the browser and element as commands with the format `{query}$`. #### Chain Browser getBy Queries Example ```javascript it('can chain browser getBy queries', async () => { setupBrowser(browser) await browser.getByTestId$('nested').getByText$('Button Text').click() const buttonText = await browser .getByTestId$('nested') .getByText$('Button Text') .getText() expect(buttonText).toEqual('Button Clicked') }) ``` #### Chain Element getBy Queries Example ```javascript it('can chain element getBy queries', async () => { const { getByTestId } = setupBrowser(browser) const nested = await getByTestId('nested') await nested.getByText$('Button Text').click() const buttonText = await browser.getByText$('Button Clicked').getText() expect(buttonText).toEqual('Button Clicked') }) ``` #### Chain getAllBy Queries Example ```javascript it('can chain getAllBy queries', async () => { setupBrowser(browser) await browser.getByTestId$('nested').getAllByText$('Button Text')[0].click() expect(await browser.getAllByText('Button Clicked')).toHaveLength(1) }) ``` ``` -------------------------------- ### Example of Suggestion Error Source: https://testing-library.com/docs/dom-testing-library/api-configuration An example of the error message thrown when throwSuggestions is enabled. ```text TestingLibraryElementError: A better query is available, try this: getByRole('paragraph') ``` -------------------------------- ### Configure jest-setup.js Source: https://testing-library.com/docs/svelte-testing-library/setup Import jest-dom to extend Jest matchers. ```javascript import '@testing-library/jest-dom' ``` -------------------------------- ### Add Vitest via Qwik CLI Source: https://testing-library.com/docs/qwik-testing-library/setup Initialize Vitest configuration using the Qwik CLI. ```bash npm run qwik add vitest ``` ```bash yarn run qwik add vitest ``` -------------------------------- ### Simulate Button Click with userEvent Source: https://testing-library.com/docs/user-event/intro Use userEvent.setup() to create a user event instance for simulating interactions like clicks. This approach is recommended for testing user interactions. ```javascript import userEvent from '@testing-library/user-event' // inlining test('trigger some awesome feature when clicking the button', async () => { const user = userEvent.setup() // Import `render` and `screen` from the framework library of your choice. // See https://testing-library.com/docs/dom-testing-library/install#wrappers render() await user.click(screen.getByRole('button', {name: /click me!/i})) // ...assertions... }) ``` -------------------------------- ### Direct API Usage Source: https://testing-library.com/docs/user-event/setup Direct APIs can be called on the default export for simpler tests, which internally calls `setup`. However, using instances from `userEvent.setup()` is recommended for more complex scenarios. ```javascript setup(options?: Options): UserEvent ``` -------------------------------- ### Install bs-jest-dom with Yarn Source: https://testing-library.com/docs/ecosystem-bs-jest-dom Use this command to install bs-jest-dom as a development dependency using Yarn. ```bash yarn add --dev bs-jest-dom ``` -------------------------------- ### Use Browser and Element Commands Source: https://testing-library.com/docs/webdriverio-testing-library/intro Demonstrates adding queries as commands to the browser and elements. ```javascript it('adds queries as browser commands', async () => { setupBrowser(browser) expect(await browser.getByText('Page Heading')).toBeDefined() }) it('adds queries as element commands scoped to element', async () => { setupBrowser(browser) const nested = await browser.$('*[data-testid="nested"]') const button = await nested.getByText('Button Text') await button.click() expect(await button.getText()).toEqual('Button Clicked') }) ``` -------------------------------- ### Configure vitest-setup.js Source: https://testing-library.com/docs/svelte-testing-library/setup Import jest-dom matchers to extend Vitest's expect functionality. ```javascript import '@testing-library/jest-dom/vitest' ``` -------------------------------- ### HTML Example with data-testid Source: https://testing-library.com/docs/queries/bytestid An example of an HTML element with the 'data-testid' attribute, which is used by the ByTestId queries. ```html
``` -------------------------------- ### Text matching examples Source: https://testing-library.com/docs/vue-testing-library/cheatsheet Demonstrates various ways to match text content using strings, regular expressions, or custom functions. ```html
Hello World
``` ```javascript // Matching a string: getByText('Hello World') // full string match getByText('llo Worl', {exact: false}) // substring match getByText('hello world', {exact: false}) // ignore case // Matching a regex: getByText(/World/) // substring match getByText(/world/i) // substring match, ignore case getByText(/^hello world$/i) // full string match, ignore case getByText(/Hello W?oRlD/i) // advanced regex // Matching with a custom function: getByText((content, element) => content.startsWith('Hello')) ``` -------------------------------- ### Complete Example: Testing FormattedDate Source: https://testing-library.com/docs/example-react-intl Demonstrates a full test case using a custom render function and `setupTests` to verify the rendering of a `FormattedDate` component from `react-intl` with specific formatting options. ```javascript import React from 'react' import '@testing-library/jest-dom' // We're importing from our own created test-utils and not RTL's import {render, screen, setupTests} from '../test-utils.js' import {FormattedDate} from 'react-intl' const FormatDateView = () => { return (
) } setupTests() test('it should render FormattedDate and have a formatted pt date', () => { render() expect(screen.getByTestId('date-display')).toHaveTextContent('11/03/2019') }) ``` -------------------------------- ### Example HTML Element Source: https://testing-library.com/docs/queries/bytext An example of an HTML anchor tag with text content that can be targeted by ByText queries. ```html About ℹ️ ``` -------------------------------- ### Install @testing-library/user-event with Yarn Source: https://testing-library.com/docs/user-event/install Use this command to install the user-event package as a development dependency in your project using Yarn. ```bash yarn add --dev @testing-library/user-event ``` -------------------------------- ### Install Jest DOM and User Event utilities Source: https://testing-library.com/docs/qwik-testing-library/setup Optional packages for enhanced DOM matchers and user interaction simulation. ```bash npm install --save-dev @testing-library/jest-dom @testing-library/user-event ``` ```bash yarn add --dev @testing-library/jest-dom @testing-library/user-event ``` -------------------------------- ### Install and configure JSDOM for Jest 28+ Source: https://testing-library.com/docs/react-testing-library/setup Install the separate JSDOM environment package and enable it in the Jest configuration or via docblocks. ```bash npm install --save-dev jest-environment-jsdom ``` ```bash yarn add --dev jest-environment-jsdom ``` ```javascript module.exports = { + testEnvironment: 'jsdom', // ... other options ... } ``` ```javascript /** * @jest-environment jsdom */ ``` -------------------------------- ### HTML Example with Alt Text Source: https://testing-library.com/docs/queries/byalttext An example of an HTML image tag with an 'alt' attribute. This is the type of element that ByAltText queries will target. ```html Incredibles 2 Poster ``` -------------------------------- ### Configuration Options Details Source: https://testing-library.com/docs/dom-testing-library/api-configuration Detailed explanations of the available configuration options for Testing Library. ```APIDOC ## Option: `computedStyleSupportsPseudoElements` ### Description Set to `true` if `window.getComputedStyle` supports pseudo-elements (i.e., a second argument). This is generally recommended for browser environments, except for very old browsers (like IE 8 and earlier). `jsdom` versions prior to `16.4.0` do not support the second argument. ### Type boolean ### Default `false` ``` ```APIDOC ## Option: `defaultHidden` ### Description The default value for the `hidden` option used by `getByRole` queries. ### Type boolean ### Default `false` ``` ```APIDOC ## Option: `defaultIgnore` ### Description The default value for the `ignore` option used by `getByText` queries. It also determines which nodes are ignored when errors are printed. ### Type string (CSS selector) ### Default `'script, style'` ``` ```APIDOC ## Option: `showOriginalStackTrace` ### Description When enabled, Testing Library cleans up and shortens stack traces for errors thrown by `waitFor` utilities to simplify debugging. Set to `false` to disable this behavior. This can also be disabled for a specific `waitFor` call. ### Type boolean ### Default `true` ``` ```APIDOC ## Option: `throwSuggestions` (experimental) ### Description When enabled, the test will fail and provide a suggested query if a better one is available. This can be disabled for a single query by passing `{suggest: false}` as an option. ### Type boolean ### Default `false` ### Note This option may provide suggestions that are not intuitively implementable, especially for roles that cannot be named (e.g., paragraphs). In such cases, a custom function can be used to validate the element's structure. ### Example ```javascript screen.getByTestId('foo', {suggest: false}) // Example for handling paragraphs: getByRole('paragraph', { name: (_, element) => element.textContent === 'Hello world', }) ``` ``` ```APIDOC ## Option: `testIdAttribute` ### Description The attribute used by `getByTestId` and related queries. ### Type string ### Default `'data-testid'` ``` ```APIDOC ## Option: `getElementError` ### Description A function that returns the error message used when `get` or `find` queries fail. It receives the error message and the container object as arguments. ### Type function(message: string, container: Element) => Error ### Default (message, container) => new Error(message) ``` ```APIDOC ## Option: `asyncUtilTimeout` ### Description The global timeout value in milliseconds used by `waitFor` utilities. ### Type number ### Default `1000` ``` -------------------------------- ### DOM Testing Library: FireEvent Examples Source: https://testing-library.com/docs/bs-react-testing-library/examples Demonstrates how to simulate user events like 'click' and 'change' on DOM elements using `FireEvent`. Requires `bs-webapi` for DOM manipulation. ```re open Jest; open DomTestingLibrary; open Expect; describe("FireEvent", () => { test("click works", () => { open Webapi.Dom; let node = document |> Document.createElement("button"); let spy = JestJs.inferred_fn(); let fn = spy |> MockJs.fn; let clickHandler = _ => [@bs] fn("clicked!") |> ignore; node |> Element.addEventListener("click", clickHandler); FireEvent.click(node); expect(spy |> MockJs.calls) |> toEqual([|"clicked!"|]); }); test("change works", () => { open Webapi.Dom; let node = document |> Document.createElement("input"); let spy = JestJs.inferred_fn(); let fn = spy |> MockJs.fn; let changeHandler = _ => [@bs] fn("changed!") |> ignore; let event = Event.makeWithOptions("change", { "target": { "value": "1" } }); node |> Element.addEventListener("change", changeHandler); FireEvent.change(node, event); expect(spy |> MockJs.calls) |> toEqual([|"changed!"|]); }); }); ``` -------------------------------- ### Install bs-react-testing-library with npm Source: https://testing-library.com/docs/bs-react-testing-library/intro Use this command to add bs-react-testing-library as a development dependency in your ReasonML project using npm. ```bash npm install --save-dev bs-react-testing-library ``` -------------------------------- ### Install Vue Testing Library for Vue 3 (Yarn) Source: https://testing-library.com/docs/vue-testing-library/intro Use this command to install the latest version of Vue Testing Library for Vue 3 projects when using Yarn. ```bash yarn add --dev @testing-library/vue ``` -------------------------------- ### Install Vue Testing Library for Vue 3 (npm) Source: https://testing-library.com/docs/vue-testing-library/intro Use this command to install the latest version of Vue Testing Library for Vue 3 projects when using npm. ```bash npm install --save-dev @testing-library/vue ``` -------------------------------- ### Install Vue Testing Library for Vue 2 (Yarn) Source: https://testing-library.com/docs/vue-testing-library/intro Use this command to install Vue Testing Library version 5 for Vue 2 projects when using Yarn. ```bash yarn add --dev @testing-library/vue@5 ``` -------------------------------- ### Install Vue Testing Library for Vue 2 (npm) Source: https://testing-library.com/docs/vue-testing-library/intro Use this command to install Vue Testing Library version 5 for Vue 2 projects when using npm. ```bash npm install --save-dev @testing-library/vue@5 ``` -------------------------------- ### ReasonML Test Example with bs-jest-dom Source: https://testing-library.com/docs/ecosystem-bs-jest-dom This example demonstrates how to use bs-jest-dom with bs-react-testing-library to test a ReasonReact component. It renders a component and asserts that an element containing specific text is present in the document. ```reasonml open Jest; open JestDom; open ReactTestingLibrary; module Heading = { let component = ReasonReact.statelessComponent("Heading"); let make = (~text, _children) => { ...component, render: _self =>

{ReasonReact.string(text)}

, }; }; test("renders with text", () => |> render |> getByText(~matcher=`Str("Hello, World!")) |> expect |> toBeInTheDocument ); ``` -------------------------------- ### Test a Hook or Primitive Source: https://testing-library.com/docs/solid-testing-library/api Example usage of renderHook to test a simple primitive. ```javascript const {result} = renderHook(createResult) expect(result).toBe(true) ```