Learn Test Utils: @react-testing-library
A library for helping us testing React
This library is what we use to get elements in the screen. Also to simulate user event behavior like typing, click and others.
Below is utils that will usually used by us.
screen.getByText
Get element by text. If not found, throw error.
import { screen } from '@testing-library/react';
import { button } from '../inputUtils';
import { renderFor } from '../utils';test('User see Delete Confirmation after clicks on Delete', () => {
renderFor(<LandingPage />); button('Delete').click(); expect(screen.getByText('Do you wish to delete?')
.toBeInTheDocument();
});
For example that getByText returns <p>Do you wish to delete?</p>
screen.queryByText
Get element by text. If not found, return null.
Useful for checking element should be hidden.
import { screen } from '@testing-library/react';
import { button } from '../inputUtils';
import { renderFor } from '../utils';test('User see Delete Confirmation disappeared after clicks "No"',
() => {
renderFor(<LandingPage />); button('Delete').click();
button('No').click(); expect(screen.queryByText('Do you wish to delete?')
.not.toBeInTheDocument();
});
screen.getByLabelText
Get form element by <label>
text.
import userEvent from '@testing-library/user-event';
import { renderFor } from '../utils';function Form() {
return (
<label for="desc">Description</label>
<input type="text" id="desc" />
)
}test('User can enters Description', () => {
renderFor(<Form />); const inputElement = screen.getByLabelText('Description');
userEvent.type(inputElement, 'I Love Description'); expect(inputElement).toHaveValue('I Love Description');
});
screen.getByTestId
Get element by data-testid attribute. There is a chance that your element doesn’t contain any text then we can use this.
<img src={loading.gif} data-testid="loading-spinner" />screen.getByTestId('loading-spinner');
Actually there is better option than that but for first learning we can use this. Prevent our brain overloaded.
userEvent.click(element)
Simulate clicking
userEvent.type(inputElement, ‘What you want to type here’)
Simulate typing
userEvent.clear(inputElement)
clear input element’s value.
const inputText = screen.getByLabelText('Description');
userEvent.type(inputText, 'hello');
userEvent.clear(inputText);
userEvent.type(inputText, 'world');
console.log(inpuText.value) // result is "world" only
screen.debug(null, 9999999)
Similar to console.log. If you want to see full html of current rendered component you can use this.
For complete information please check documentation of @react-testing-library.