-
For each component, create a separate test file with the naming convention
componentName.test.js
. -
Inside the test file, write test functions using the
test
orit
keyword. Each function should have a descriptive name and a callback function containing the tests.
test("Your test name", () => {
// Test code goes here
});
-
Ensure compatibility with library
versions
to avoid any unexpected issues. -
Start the callback function with the
render
method to render the component being tested.
test("Your test name", () => {
// Test code goes here
// render the target component
render(<App />);
});
- Next step is
query
and find element (elements) we want to use test on them To query and select a DOM element, there are two popular ways to do it usingscreen
methods likescreen.getByRole("...")
,screen.getByText("...")
,sreen.getByDisplayValue("..")
, and more. However, in the case of a Table where you want to test the length of the table body rows to have a specific length, such as 2, it becomes a bit tricky. This is because the length will always include the table header rows, and it's not possible to differentiate between tr elements in the thead and tbody
Using container query selector
:
This solution involves destructuring the container from the render method and using container query selectors. You can inspect the rendered DOM using screen.logTestingPlaygroundURL()
to find an appropriate query.
Here's an example:
const container = screen.container;
const firstRowCell = container.querySelector('#sandbox > div > table > tbody');
Using within
and data-testid
:
In your JSX code, add a data-testid
attribute to the table body element, such as data-testid="users"
. Then, in your test function, retrieve the table body rows using the following code:
<tbody data-testid="users">
const rows = within(screen.getByTestId("users")).getAllByRole("row");
4.Handle User Events
(Optional)
5.โโExpections
To run the tests, use the following command:
npm run test