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.

data-testid

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:

  1. Click the "Continue" button.

  2. Select the "E2E Testing" option.

  3. Click on the "Start E2E Testing in Electron" option.

  4. Click on spec.cy.js file to execute the test.

Bud1�essvSrnlocypressvSrnlong @� @� @� @E�DSDB `� @� @� @
Using data-testid in React-Cypress application

When we run the React application, App.js is the main entry point. App.js imports and renders the SubCategories component. The SubCategories.js component defines the structure and content of the SubCategories component. When we run the Cypress test, Cypress opens and runs the test defined in spec.cy.js. The Cypress test visits the URL where the React app is running, interacts with it, and asserts that the SubCategories component is rendered correctly.

Copyright ©2024 Educative, Inc. All rights reserved