data-testid
is an attribute used to identify a DOM node for testing purposes. It should be used as a handler to the test code. We need to make sure its value is unique. Therefore, we do not cause conflicts between components.
data-testid
The React testing library is mainly used for functional black-box testing. A selector might imply a test implementation. Selectors can be ambiguous and change unexpectedly when the implementation changes. However, the use of data-testid
shows that it is unambiguous and has been added on purpose to facilitate testing.
data-testid
?To enable test automation support in applications using a React testing library, we need to provide a special data-testid
attribute for each component. It must be placed on the containing element of each section and all related subsections.
data-testid
Instead of implementing it in the file, we pass the data-testid
as a hook. The following code example is from Cypress testing.
const SubCategories = ({ category, subCategory, dataTestId }) => (
<div className={styles.subCategoriesContainer} data-testid={dataTestId}>
<div className={styles.subCategoriesHeader}>
......
</div>
</div>
);
That is a component that renders a div
with its test id
.
it('should render the SubCategories component', () => {
render(
<SubCategories
category="Moda"
subCategory={['Sukienki', 'Buty', 'Koszulki']}
dataTestId="testSubCategories"
/>
);
expect(screen.getByTestId('testSubCategories')).toBeInTheDocument();
});
Let's see the complete example of the above code. To run the following code, please follow the steps:
Click the "Continue" button.
Select the "E2E Testing" option.
Click on the "Start E2E Testing in Electron" option.
Click on spec.cy.js
file to execute the test.