### Quickstart Test Implementation
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/react-testing-library/example-intro.mdx
A minimal test setup using React Testing Library and user-event to verify component behavior.
```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()
})
```
```jsx
// import react-testing methods
import {render, screen} from '@testing-library/react'
// userEvent library simulates user interactions by dispatching the events that would happen if the interaction took place in a browser.
import userEvent from '@testing-library/user-event'
// add custom jest matchers from jest-dom
import '@testing-library/jest-dom'
// the component to test
import Fetch from './fetch'
test('loads and displays greeting', async () => {
// Render a React element into the DOM
render()
await userEvent.click(screen.getByText('Load Greeting'))
// wait before throwing an error if it cannot find an element
await screen.findByRole('heading')
// assert that the alert message is correct using
// toHaveTextContent, a custom matcher from jest-dom.
expect(screen.getByRole('heading')).toHaveTextContent('hello there')
expect(screen.getByRole('button')).toBeDisabled()
})
```
--------------------------------
### Input Tag Setup and Querying
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/queries/bydisplayvalue.mdx
Examples for setting an input value and querying it across different frameworks.
```html
```
```javascript
document.getElementById('lastName').value = 'Norris'
```
```javascript
import {screen} from '@testing-library/dom'
const lastNameInput = screen.getByDisplayValue('Norris')
```
```jsx
import {render, screen} from '@testing-library/react'
render()
const lastNameInput = screen.getByDisplayValue('Norris')
```
```typescript
import {render, screen} from '@testing-library/angular'
await render(MyComponent)
const lastNameInput = screen.getByDisplayValue('Norris')
```
```javascript
cy.findByDisplayValue('Norris').should('exist')
```
--------------------------------
### Select Tag Setup and Querying
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/queries/bydisplayvalue.mdx
Examples for querying a select element by its currently selected option.
```html
```
```javascript
import {screen} from '@testing-library/dom'
const selectElement = screen.getByDisplayValue('Alaska')
```
```jsx
import {render, screen} from '@testing-library/react'
render()
const selectElement = screen.getByDisplayValue('Alaska')
```
```typescript
import {render, screen} from '@testing-library/angular'
await render(MyComponent)
const selectElement = screen.getByDisplayValue('Alaska')
```
```javascript
cy.findByDisplayValue('Alaska').should('exist')
```
--------------------------------
### Install bs-platform
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/bs-react-testing-library/intro.mdx
Install the BuckleScript compiler if it is missing from the project.
```bash
npm install --save-dev bs-platform
```
--------------------------------
### Setup Function for userEvent Tests
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/user-event/intro.mdx
Define a `setup` function that initializes `userEvent.setup()` and renders the component. This centralizes setup logic and returns the user instance along with other render utilities.
```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()
// ...
})
```
--------------------------------
### Setup Browser for Testing Library Queries
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/webdriverio-testing-library/intro.mdx
Use `setupBrowser` to integrate dom-testing-library queries into WebdriverIO. All queries are async and bound to `document.body` by default. This example demonstrates clicking a button and verifying its text.
```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')
})
```
--------------------------------
### Install Dependencies
Source: https://github.com/testing-library/testing-library-docs/blob/main/README.md
Run this command to install all necessary dependencies for the documentation website.
```sh
# Install dependencies
$ npm install
```
--------------------------------
### Textarea Tag Setup and Querying
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/queries/bydisplayvalue.mdx
Examples for setting a textarea value and querying it across different frameworks.
```html
```
```javascript
document.getElementById('messageTextArea').value = 'Hello World'
```
```javascript
import {screen} from '@testing-library/dom'
const messageTextArea = screen.getByDisplayValue('Hello World')
```
```jsx
import {render, screen} from '@testing-library/react'
render()
const messageTextArea = screen.getByDisplayValue('Hello World')
```
```typescript
import {render, screen} from '@testing-library/angular'
await render(MyComponent)
const messageTextArea = screen.getByDisplayValue('Hello World')
```
```javascript
cy.findByDisplayValue('Hello World').should('exist')
```
--------------------------------
### Start Development Server
Source: https://github.com/testing-library/testing-library-docs/blob/main/README.md
Execute this command to start the local development server for the documentation site.
```sh
# Start the site
$ npm start
```
--------------------------------
### Install React Testing Library
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/react-testing-library/intro.mdx
Install the library and its required peer dependency.
```bash
npm install --save-dev @testing-library/react @testing-library/dom
```
--------------------------------
### Install rtl-simple-queries
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/ecosystem-rtl-simple-queries.md
Install the rtl-simple-queries library as a development dependency using npm or yarn.
```bash
npm install --save-dev rtl-simple-queries
```
--------------------------------
### Install riot-testing-library
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/ecosystem-riot-testing-library.mdx
Install riot-testing-library as a development dependency using npm or yarn.
```bash
npm install --save-dev riot-testing-library
```
--------------------------------
### Install nightwatch-testing-library
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/nightwatch-testing-library/intro.mdx
Install the library using npm. Ensure Nightwatch is configured first.
```bash
npm install --save-dev @testing-library/nightwatch
```
--------------------------------
### Install development dependencies
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/svelte-testing-library/setup.mdx
Install the required testing packages using npm.
```bash
npm install --save-dev \
@testing-library/svelte \
@testing-library/jest-dom \
svelte-jester \
jest \
jest-environment-jsdom
```
--------------------------------
### Install pptr-testing-library
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/pptr-testing-library/intro.mdx
Install puppeteer and pptr-testing-library as development dependencies.
```bash
npm install --save-dev puppeteer pptr-testing-library
```
--------------------------------
### TypeScript Signature for setup()
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/user-event/setup.mdx
This is the TypeScript signature for the `setup` function, indicating it accepts optional options and returns a `UserEvent` instance.
```typescript
setup(options?: Options): UserEvent
```
--------------------------------
### Install Core Dependencies
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/qwik-testing-library/setup.mdx
Install the main testing library and its DOM counterpart as development dependencies.
```bash
npm install --save-dev @noma.to/qwik-testing-library @testing-library/dom
```
--------------------------------
### Install development dependencies
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/svelte-testing-library/setup.mdx
Install the required testing packages using npm.
```bash
npm install --save-dev \
@testing-library/svelte \
@testing-library/jest-dom \
@sveltejs/vite-plugin-svelte \
vitest \
jsdom
```
```bash
npm install --save-dev @vitest/ui
```
--------------------------------
### Install webdriverio-testing-library
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/webdriverio-testing-library/intro.mdx
Install the library using npm or yarn. Ensure WebdriverIO is configured first.
```bash
npm install --save-dev @testing-library/webdriverio
```
--------------------------------
### Install testcafe-testing-library
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/testcafe-testing-library/intro.mdx
Install the necessary packages for testcafe-testing-library using npm or yarn.
```bash
npm install --save-dev testcafe @testing-library/testcafe
```
--------------------------------
### Install react-select-event
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/ecosystem-react-select-event.mdx
Command to add the library as a development dependency.
```bash
npm install --save-dev react-select-event
```
--------------------------------
### Install and Configure bs-jest
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/bs-react-testing-library/intro.mdx
Install the recommended test runner and register it in the bsconfig.json file.
```bash
npm install --save-dev @glennsl/bs-jest
```
```json
{
"bs-dev-dependencies": ["@glennsl/bs-jest"]
}
```
--------------------------------
### Cypress Testing Library Query Examples
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/cypress-testing-library/intro.mdx
Demonstrates various ways to use `findBy` queries with Cypress Testing Library, including checking for existence, non-existence, and within specific elements. Note that `get*` and `query*` queries are not supported.
```javascript
cy.findByRole('button', {name: /Jackie Chan/i}).click()
cy.findByRole('button', {name: /Button Text/i}).should('exist')
cy.findByRole('button', {name: /Non-existing Button Text/i}).should('not.exist')
cy.findByLabelText(/Label text/i, {timeout: 7000}).should('exist')
// findByRole _inside_ a form element
cy.get('form')
.findByRole('button', {name: /Button Text/i})
.should('exist')
cy.findByRole('dialog').within(() => {
cy.findByRole('button', {name: /confirm/i})
})
```
--------------------------------
### Install query-extensions
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/ecosystem-query-extensions.mdx
Use this command to add the library as a development dependency to your project.
```bash
npm install --save-dev query-extensions
```
--------------------------------
### Install Testing Library Bindings
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/bs-react-testing-library/intro.mdx
Commands to install the necessary BuckleScript bindings for DOM or React testing.
```bash
npm install --save-dev bs-dom-testing-library
```
```bash
npm install --save-dev bs-react-testing-library
```
--------------------------------
### UserEvent Setup API
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/user-event/setup.mdx
The `userEvent.setup()` API allows you to configure an instance of `user-event` that simulates user interactions. Methods on this instance share one input device state, enabling consecutive interactions to behave as a real user would. This setup also replaces `window.navigator.clipboard` with a stub for testing clipboard-related workflows.
```APIDOC
## POST /api/users
### Description
Creates a new user in the system.
### Method
POST
### Endpoint
/api/users
### Parameters
#### Query Parameters
- **limit** (integer) - Optional - The maximum number of users to return.
#### Request Body
- **name** (string) - Required - The name of the user.
- **email** (string) - Required - The email address of the user.
### Request Example
```json
{
"name": "John Doe",
"email": "john.doe@example.com"
}
```
### Response
#### Success Response (200)
- **id** (integer) - The unique identifier for the newly created user.
- **name** (string) - The name of the user.
- **email** (string) - The email address of the user.
#### Response Example
```json
{
"id": 1,
"name": "John Doe",
"email": "john.doe@example.com"
}
```
```
--------------------------------
### Install jest-dom
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/ecosystem-jest-dom.mdx
Install the library as a development dependency using npm.
```bash
npm install --save-dev @testing-library/jest-dom
```
--------------------------------
### Install CLI Testing Library
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/ecosystem-cli-testing-library.mdx
Install the library as a development dependency using npm or yarn.
```bash
npm install --save-dev cli-testing-library
```
--------------------------------
### Install React Testing Library with TypeScript
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/react-testing-library/intro.mdx
Install the library along with necessary type definitions for React.
```bash
npm install --save-dev @testing-library/react @testing-library/dom @types/react @types/react-dom
```
--------------------------------
### HTML Input Example
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/queries/byplaceholdertext.mdx
Example of an input element with a placeholder attribute.
```html
```
--------------------------------
### Install testing-library-selector
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/ecosystem-testing-library-selector.md
Install the testing-library-selector package as a development dependency using npm or yarn.
```bash
npm install --save-dev testing-library-selector
```
--------------------------------
### Install jasmine-dom
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/ecosystem-jasmine-dom.mdx
Install the library as a development dependency using npm or yarn.
```bash
npm install --save-dev @testing-library/jasmine-dom
```
--------------------------------
### Install Solid Testing Library
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/solid-testing-library/intro.mdx
Install the Solid Testing Library package using npm or yarn. This is a required step before using the library in your project.
```bash
npm install --save-dev @solidjs/testing-library
```
--------------------------------
### ByAltText Usage Examples
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/queries/byalttext.mdx
Examples of using ByAltText across different testing frameworks.
```js
import {screen} from '@testing-library/dom'
const incrediblesPosterImg = screen.getByAltText(/incredibles.*? poster/i)
```
```jsx
import {render, screen} from '@testing-library/react'
render()
const incrediblesPosterImg = screen.getByAltText(/incredibles.*? poster/i)
```
```ts
import {render, screen} from '@testing-library/angular'
await render(MyComponent)
const incrediblesPosterImg = screen.getByAltText(/incredibles.*? poster/i)
```
```js
cy.findByAltText(/incredibles.*? poster/i).should('exist')
```
--------------------------------
### Install bs-jest-dom
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/ecosystem-bs-jest-dom.mdx
Install the library as a development dependency using npm or yarn.
```bash
npm install --save-dev bs-jest-dom
```
--------------------------------
### Install React Testing Library and jest-dom
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/react-testing-library/migrate-from-enzyme.mdx
Install the necessary testing dependencies as development dependencies.
```bash
npm install --save-dev @testing-library/react @testing-library/jest-dom
```
--------------------------------
### Install user-event package
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/user-event/install.mdx
Use this command to add the user-event library as a development dependency.
```bash
npm install --save-dev @testing-library/user-event
```
--------------------------------
### Install Preact Testing Library
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/preact-testing-library/intro.mdx
Use this command to add the library as a development dependency to your project.
```bash
npm install --save-dev @testing-library/preact
```
--------------------------------
### HTML Example for ByText
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/queries/bytext.mdx
An example of an HTML anchor tag that can be targeted by the ByText query.
```html
About ℹ️
```
--------------------------------
### Configure Vitest Manual Cleanup via Setup File
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/react-testing-library/setup.mdx
Use a setup file to manually invoke cleanup after each test if globals are disabled.
```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 Cypress Testing Library
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/cypress-testing-library/intro.mdx
Install the necessary packages for Cypress Testing Library using npm or yarn.
```bash
npm install --save-dev cypress @testing-library/cypress
```
--------------------------------
### Install Angular Testing Library via npm
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/angular-testing-library/intro.mdx
Install the library and its required DOM dependency using npm.
```bash
npm install --save-dev @testing-library/angular @testing-library/dom
```
--------------------------------
### Install user-event and DOM Testing Library
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/react-testing-library/migrate-from-enzyme.mdx
Install the necessary packages for using user-event and DOM Testing Library. This command works for both npm and yarn.
```bash
npm install --save-dev @testing-library/user-event @testing-library/dom
```
--------------------------------
### Query by Role Example
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/queries/about.mdx
Demonstrates selecting a button element by its role and accessible name.
```js
getByRole('button', {name: /submit/i})
```
--------------------------------
### Example DOM Structure
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/queries/about.mdx
Sample HTML structure used to demonstrate query functionality.
```js
```
--------------------------------
### Install Angular Testing Library via ng add
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/angular-testing-library/intro.mdx
Use the Angular CLI to automatically configure the project and install necessary dependencies.
```bash
ng add @testing-library/angular
```
--------------------------------
### Input Element Example
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/queries/bytext.mdx
An example of an input element with a 'value' attribute that can be matched using ByText.
```html
```
--------------------------------
### Install DOM Environment
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/qwik-testing-library/setup.mdx
Install a DOM environment like jsdom or happy-dom to run tests. Choose one based on your project's needs.
```bash
npm install --save-dev jsdom
```
```bash
npm install --save-dev happy-dom
```
--------------------------------
### Install Marko Testing Library
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/marko-testing-library/intro.mdx
Use this command to add the library as a development dependency to your project.
```bash
npm install --save-dev @marko/testing-library
```
--------------------------------
### Install Optional Testing Dependencies
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/qwik-testing-library/setup.mdx
Install additional libraries for enhanced testing capabilities, such as Jest DOM matchers and user event simulation.
```bash
npm install --save-dev @testing-library/jest-dom @testing-library/user-event
```
--------------------------------
### Install Svelte Testing Library
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/svelte-testing-library/intro.mdx
Use this command to add the library as a development dependency to your project.
```bash
npm install --save-dev @testing-library/svelte
```
--------------------------------
### Install DOM Testing Library
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/dom-testing-library/install.mdx
Install the core DOM Testing Library as a development dependency in your project using npm or yarn.
```bash
npm install --save-dev @testing-library/dom
```
--------------------------------
### Install Vue Testing Library for Vue 2
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/vue-testing-library/intro.mdx
Use this command to install Vue Testing Library version 5 for Vue 2 projects.
```bash
npm install --save-dev @testing-library/vue@5
```
--------------------------------
### Add New Doc ID to Sidebar
Source: https://github.com/testing-library/testing-library-docs/blob/main/README.md
After creating a new docs page, refer to its ID in the `sidebar.json` file to include it in the documentation's sidebar navigation. This example shows adding `newly-created-doc` to the 'Getting Started' category.
```javascript
// Add newly-created-doc to the Getting Started category of docs
{
"docs": {
"Getting Started": [
"quick-start",
"newly-created-doc" // new doc here
],
...
},
...
```
--------------------------------
### Install Vue Testing Library for Vue 3
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/vue-testing-library/intro.mdx
Use this command to install the latest version of Vue Testing Library for Vue 3 projects.
```bash
npm install --save-dev @testing-library/vue
```
--------------------------------
### Simulate Pointer Movement
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/user-event/api-pointer.mdx
Example of moving a touch pointer across elements.
```js
pointer([
// touch the screen at element1
{keys: '[TouchA>]', target: element1},
// move the touch pointer to element2
{pointerName: 'TouchA', target: element2},
// release the touch pointer at the last position (element2)
{keys: '[/TouchA]'},
])
```
--------------------------------
### Install jsdom and global-jsdom
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/dom-testing-library/setup.mdx
Required dependencies for simulating browser APIs in a Node environment.
```bash
npm install --save-dev jsdom global-jsdom
```
--------------------------------
### Setup JSDOM for non-Jest environments
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/react-testing-library/setup.mdx
Install and register JSDOM for use with test runners like Mocha.
```bash
npm install --save-dev jsdom global-jsdom
```
```bash
mocha --require global-jsdom/register
```
--------------------------------
### Install React Native Testing Library
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/react-native-testing-library/intro.mdx
Use this command to add the library as a development dependency to your project.
```bash
npm install --save-dev @testing-library/react-native
```
--------------------------------
### Setup Vitest Environment
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/qwik-testing-library/setup.mdx
Create `vitest.setup.ts` to configure DOM matchers and ensure Qwik runs in a browser-like environment for testing.
```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
```
--------------------------------
### Simulate Selection with Pointer
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/user-event/api-pointer.mdx
Examples of using pointer actions to alter document selection.
```jsx
pointer({target: element, offset: 2, keys: '[MouseLeft]'})
```
```jsx
pointer([{target: element, offset: 2, keys: '[MouseLeft>]'}, {offset: 5}])
```
```jsx
pointer({target: element, node: element, offset: 1, keys: '[MouseLeft]'})
```
--------------------------------
### Vue Testing Library: Get By Label Text Example
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/vue-testing-library/cheatsheet.mdx
Use getByLabelText to find an element associated with a label. It throws an error if no element or more than one element is found.
```javascript
getByLabelText('Username')
```
--------------------------------
### Create Entrypoint for Testing
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/qwik-testing-library/setup.mdx
Create an `src/index.ts` file. This is required by @noma.to/qwik-testing-library to correctly run your tests.
```typescript
/**
* DO NOT DELETE THIS FILE
*
* This entrypoint is needed by @noma.to/qwik-testing-library to run your tests
*/
```
--------------------------------
### Querying by Placeholder Text
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/queries/byplaceholdertext.mdx
Usage examples for finding elements by placeholder text across different frameworks.
```js
import {screen} from '@testing-library/dom'
const inputNode = screen.getByPlaceholderText('Username')
```
```jsx
import {render, screen} from '@testing-library/react'
render()
const inputNode = screen.getByPlaceholderText('Username')
```
```ts
import {render, screen} from '@testing-library/angular'
await render(MyComponent)
const inputNode = screen.getByPlaceholderText('Username')
```
```js
cy.findByPlaceholderText('Username').should('exist')
```
--------------------------------
### Direct API Usage
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/user-event/setup.mdx
You can also call user event APIs directly on the default export. This internally calls `setup()` and then uses the method on the instance. While this eases transition, using methods on instances returned by `userEvent.setup()` is recommended for better control and state management.
```APIDOC
## GET /api/users/{id}
### Description
Retrieves a specific user by their ID.
### Method
GET
### Endpoint
/api/users/{id}
### Parameters
#### Path Parameters
- **id** (integer) - Required - The unique identifier of the user to retrieve.
#### Query Parameters
- **fields** (string) - Optional - Comma-separated list of fields to include in the response.
### Response
#### Success Response (200)
- **id** (integer) - The unique identifier for the user.
- **name** (string) - The name of the user.
- **email** (string) - The email address of the user.
- **createdAt** (string) - The timestamp when the user was created.
#### Response Example
```json
{
"id": 1,
"name": "John Doe",
"email": "john.doe@example.com",
"createdAt": "2023-10-27T10:00:00Z"
}
```
```
--------------------------------
### Basic render usage
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/react-testing-library/api.mdx
Simple examples of rendering a component using React Testing Library.
```jsx
import {render} from '@testing-library/react'
render()
```
```jsx
import {render} from '@testing-library/react'
import '@testing-library/jest-dom'
test('renders a message', () => {
const {asFragment, getByText} = render()
expect(getByText('Hello, world!')).toBeInTheDocument()
expect(asFragment()).toMatchInlineSnapshot(`
Hello, World!
`)
})
```
--------------------------------
### Automatic DOM logging example
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/dom-testing-library/api-debugging.mdx
Demonstrates how a failing query automatically prints the DOM state to the console.
```javascript
//
Hello world
getByText(container, 'Goodbye world') // will fail by throwing error
```
--------------------------------
### HTML Element Example
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/queries/byalttext.mdx
Example of an image element with an alt attribute.
```html
```
--------------------------------
### Render and interact with a form
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/example-findByText.md
This example sets up a simple login form and demonstrates how to render it, simulate user input, and trigger form submission with validation messages.
```javascript
// src/__tests__/example.test.js
// This is an example of how to use findByText to query for text that
// is not visible right away
import {screen} from '@testing-library/dom'
import userEvent from '@testing-library/user-event'
// provides a set of custom jest matchers that you can use to extend jest
// i.e. `.toBeVisible`
import '@testing-library/jest-dom'
function renderApp() {
const el = document.body.appendChild(document.createElement('div'))
el.innerHTML = `
`
const submitButton = el.querySelector('#submit')
const formEl = el.querySelector('#login_form')
submitButton.addEventListener('click', () => {
const userInput = el.querySelector('#username_input')
const passwordInput = el.querySelector('#password_input')
const userName = userInput.value
const password = passwordInput.value
if (!userName) {
el.querySelector('#username_required_error').style.display = 'inline'
}
if (!password) {
el.querySelector('#password_required_error').style.display = 'inline'
}
if (userName && userName !== 'Bob') {
el.querySelector('#invalid_username_error').style.display = 'inline'
}
if (password && password !== 'theBuilder') {
el.querySelector('#invalid_password_error').style.display = 'inline'
}
})
formEl.addEventListener('submit', function (evt) {
evt.preventDefault()
window.history.back()
})
return {user: userEvent.setup()}
}
afterEach(() => (document.body.innerHTML = ``))
describe('findByText Examples', () => {
it('should show a required field warning for each empty input field', async () => {
const {user} = renderApp()
await user.click(
screen.getByRole('button', {
name: 'Login',
}),
)
expect(await screen.findByText('User Name Required')).toBeVisible()
expect(await screen.findByText('Password Required')).toBeVisible()
})
it('should show invalid field errors for each invalid input field', async () => {
const {user} = renderApp()
const userNameField = screen.getByPlaceholderText('Enter user name')
const passwordField = screen.getByPlaceholderText('Enter password')
expect(await screen.findByText('Invalid Password')).not.toBeVisible()
expect(await screen.findByText('Invalid User Name')).not.toBeVisible()
await user.type(userNameField, 'Philchard')
await user.type(passwordField, 'theCat')
expect(userNameField).toHaveValue('Philchard')
expect(passwordField).toHaveValue('theCat')
await user.click(
screen.getByRole('button', {
name: 'Login',
}),
)
expect(await screen.findByText('Invalid User Name')).toBeVisible()
expect(await screen.findByText('Invalid Password')).toBeVisible()
})
})
```
--------------------------------
### Initialize user-event instance
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/user-event/setup.mdx
Initialize a user-event instance using `userEvent.setup()`. This instance can be used for multiple consecutive interactions, maintaining shared input device state.
```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`
```
--------------------------------
### Simulate Button Click with userEvent
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/user-event/intro.mdx
Use `userEvent.setup()` to get a user instance, then call `user.click()` to simulate a button click. 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...
})
```
--------------------------------
### Configure jest-setup.js
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/svelte-testing-library/setup.mdx
Import jest-dom to extend Jest matchers.
```ts
import '@testing-library/jest-dom'
```
--------------------------------
### setupBrowser API
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/webdriverio-testing-library/intro.mdx
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 and selectors. All queries are asynchronous by default and are bound to `document.body`. It also adds these queries as commands to the browser and WebdriverIO elements.
```APIDOC
## setupBrowser
### Description
Accepts a WebdriverIO [browser object](https://webdriver.io/docs/browserobject) and returns dom-testing-library [queries](/docs/queries/about.mdx) modified to return WebdriverIO elements like normal [selectors](https://webdriver.io/docs/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')
})
```
`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`](#within).
### Browser and Element Commands
```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')
})
```
When using [sync mode](https://webdriver.io/docs/sync-vs-async#sync-mode) these commands are also synchronous:
### Sync Mode Commands
```javascript
it('adds queries as browser commands', async () => {
setupBrowser(browser)
expect(browser.getByText('Page Heading')).toBeDefined()
})
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')
})
```
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}$`.
### Chainable Queries
```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')
})
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')
})
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)
})
```
```
--------------------------------
### Add Vitest to Project
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/qwik-testing-library/setup.mdx
Use the Qwik CLI to add Vitest as your test runner.
```bash
npm run qwik add vitest
```
--------------------------------
### Mock API Requests with MSW
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/react-testing-library/example-intro.mdx
Use setupServer to intercept and mock network requests during tests. Reset handlers between tests to ensure isolation.
```js
// declare which API requests to mock
const server = setupServer(
// capture "GET /greeting" requests
http.get('/greeting', (req, res, ctx) => {
// respond using a mocked JSON body
return HttpResponse.json({greeting: 'hello there'})
}),
)
// establish API mocking before all tests
beforeAll(() => server.listen())
// reset any request handlers that are declared as a part of our tests
// (i.e. for testing one-time error scenarios)
afterEach(() => server.resetHandlers())
// clean up once the tests are done
afterAll(() => server.close())
// ...
test('handles server error', async () => {
server.use(
// override the initial "GET /greeting" request handler
// to return a 500 Server Error
http.get('/greeting', (req, res, ctx) => {
return new HttpResponse(null, {status: 500})
}),
)
// ...
})
```
--------------------------------
### Enzyme Test for Welcome Component
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/react-testing-library/migrate-from-enzyme.mdx
An example of how to test the Welcome component using Enzyme, specifically checking the initial text content of the h1 element.
```jsx
test('has correct welcome text', () => {
const wrapper = shallow()
expect(wrapper.find('h1').text()).toEqual('Welcome, John Doe')
})
```
--------------------------------
### TextMatch Examples: String Matching
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/queries/about.mdx
Demonstrates various ways to match text content using strings with `screen.getByText`. Options include exact full string matches, substring matches, and case-insensitive matching.
```javascript
// Matching a string:
screen.getByText('Hello World') // full string match
screen.getByText('llo Worl', {exact: false}) // substring match
screen.getByText('hello world', {exact: false}) // ignore case
```
--------------------------------
### Example: Type into an input by placeholder text
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/testcafe-testing-library/intro.mdx
Demonstrates using screen.getByPlaceholderText to find an input element and type text into it.
```javascript
import {screen} from '@testing-library/testcafe'
test('getByPlaceHolderText', async t => {
await t.typeText(
screen.getByPlaceholderText('Placeholder Text'),
'Hello Placeholder',
)
})
```
--------------------------------
### Add Queries as Browser Commands
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/webdriverio-testing-library/intro.mdx
After calling `setupBrowser`, queries are added as commands to the browser object, scoped to `document.body`.
```javascript
it('adds queries as browser commands', async () => {
setupBrowser(browser)
expect(await browser.getByText('Page Heading')).toBeDefined()
})
```
--------------------------------
### TextMatch Examples: Non-Matches
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/queries/about.mdx
Provides examples of `screen.getByText` queries that will not find the target element, illustrating cases where string, regex, or function matching fails.
```javascript
// full string does not match
screen.getByText('Goodbye World')
// case-sensitive regex with different case
screen.getByText(/hello world/)
// function looking for a span when it's actually a div:
screen.getByText((content, element) => {
return element.tagName.toLowerCase() === 'span' && content.startsWith('Hello')
})
```
--------------------------------
### Configure vitest-setup.js
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/svelte-testing-library/setup.mdx
Import jest-dom matchers to enable custom expect assertions.
```js
import '@testing-library/jest-dom/vitest'
```
--------------------------------
### Vue Testing Library: Configure Global Options Example
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/vue-testing-library/cheatsheet.mdx
Use configure to change global options for Vue Testing Library. For example, you can set a custom testIdAttribute.
```javascript
configure({testIdAttribute: 'my-test-id'})
```
--------------------------------
### React Component Example
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/react-testing-library/migrate-from-enzyme.mdx
A React component that displays a welcome message and allows users to update their name via input fields. This component serves as the basis for migration examples.
```jsx
const Welcome = props => {
const [values, setValues] = useState({
firstName: props.firstName,
lastName: props.lastName,
})
const handleChange = event => {
setValues({...values, [event.target.name]: event.target.value})
}
return (
Welcome, {values.firstName} {values.lastName}
)
}
export default Welcome
```
--------------------------------
### Example: Query all elements by text and check existence
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/testcafe-testing-library/intro.mdx
Demonstrates using screen.queryAllByText to find all elements with specific text and assert their existence or non-existence.
```javascript
test('queryAllByText', async t => {
await t.expect(screen.queryAllByText('Button Text').exists).ok()
await t
.expect(screen.queryAllByText('Non-existing Button Text').exists)
.notOk()
})
```
--------------------------------
### DOM Testing Library: getByText Examples
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/bs-react-testing-library/examples.mdx
Demonstrates the usage of `getByText` with string, regex, and function matchers. Requires DomTestingLibrary and Jest. The example HTML is parsed using bs-webapi.
```reason
open Jest;
open DomTestingLibrary;
open Expect;
type parser;
[@bs.new]
external domParser : unit => parser = "DOMParser";
[@bs.send.pipe : parser]
external parseFromString : ( string, [@bs.as "text/html"] _) => Dom.element = "";
[@bs.get]
external body : Dom.element => Dom.element = "";
[@bs.get]
external firstChild : Dom.element => Dom.element = "";
let div = domParser()
|> parseFromString({j|
Hello,
World!
|j})
|> body
|> firstChild;
describe("getByText", () => {
test("works with string matcher", () => {
let actual = div |> getByText(~matcher=`Str("Hello,"));
expect(actual) |> toMatchSnapshot;
});
test("works with regex matcher", () => {
let actual = div |> getByText(~matcher=`RegExp([%bs.re "/\\w!/"]));
expect(actual) |> toMatchSnapshot;
});
test("works with function matcher", () => {
let matcher = ( _text, node ) => (node |> tagName) === "P";
let actual = div |> getByText(~matcher=`Func(matcher));
expect(actual) |> toMatchSnapshot;
});
});
```
--------------------------------
### Simulate File Uploads
Source: https://github.com/testing-library/testing-library-docs/blob/main/docs/user-event/api-utility.mdx
Examples demonstrating how to use userEvent.upload to simulate single and multiple file selections in a test environment.
```jsx
test('upload file', async () => {
const user = userEvent.setup()
render(