What is the data-testid attribute in testing?
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.
Need for 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.
Where do we put 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.
Defining 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.
Component
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.
Test
it('should render the SubCategories component', () => {
render(
<SubCategories
category="Moda"
subCategory={['Sukienki', 'Buty', 'Koszulki']}
dataTestId="testSubCategories"
/>
);
expect(screen.getByTestId('testSubCategories')).toBeInTheDocument();
});
Complete code
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.jsfile to execute the test.