getBy
, findBy
, queryBy
,…<aside>
☝ You should find your elements in the test the same way users will find them! For example, testing-library doesn’t have getById
for an input because users don’t care about an id of an element, they find that element by its placeholder text instead.
</aside>
Use data-testid
and .getByTestId()
.
// .tsx
<input
data-testid="ulid-input"
/>
// .test.tsx
const input = screen.getByTestId('ulid-input')
yarn test
(jest --watch
in package.json) then press p
to filter based on file name regex.
Expect not to be in the document → queryBy
instead of findBy
because queryBy
returns a null (no error) whereas findBy
throws an error instead!
const nameInput = screen.queryByPlaceholderText('Enter name...')
expect(nameInput).not.toBeInTheDocument()
Expect to be in the docyment → can use either queryBy
or findBy
!
Find an image → getByAltText
Find an input
<label htmlFor="abc">Text Input</label>
<input id="abc" ... />
import {screen} from '@testing-library/dom'
const inputNode = screen.getByLabelText('Text Input')
Or using ByPlacehoderText
Dropdown options → check this SO.
Idea: Add data-testid
to options, then get the options by getAllByTestId
, then check the sected option.
<option data-testid="select-option" key={item.key} value={item.key}>
{item.label}
</option>
// in test
//
const options = getAllByTestId(container, 'select-option')
expect(options[0].selected).toBeFalsy();
expect(options[1].selected).toBeTruthy();
Can use getByDisplayValue
for selected option.
Check more in Unit Testing with JestJS