In Jest, particularly when used with React Testing Library (RTL), you can find elements with a specific data-* attribute like data-qa using the getByAttribute queries or the queryByAttribute method.
To effectively utilize data-qa attributes in your tests, follow the approach below:
Example of Testing with Jest and React Testing Library
Here's an example of how to implement a test that looks for an element with the data-qa attribute:
-
Install React Testing Library (if you haven't already):
If you're using the library, make sure to include it in your project's dependencies:
npm install --save-dev @testing-library/react
-
Create a Component: For demonstration, let's assume you have a simple component that includes a data-qa attribute:
// ExampleComponent.js
import React from 'react';
const ExampleComponent = () => {
return (
<button data-qa="submit-button">Submit</button>
);
};
export default ExampleComponent;
-
Write the Test Case:
Here’s how you would write a Jest test that finds an element by its data-qa attribute:
// ExampleComponent.test.js
import React from 'react';
import { render, screen } from '@testing-library/react';
import ExampleComponent from './ExampleComponent';
test('should find the submit button by data-qa attribute', () => {
render(<ExampleComponent />);
// Use a selector to find the element by data-qa attribute
const submitButton = screen.getByAttribute('data-qa', 'submit-button');
// Verify that the button is in the document
expect(submitButton).toBeInTheDocument();
});
Using getBy Variant
Alternatively, it's common to use getByTestId directly to find elements, especially since data-test or data-testid is a more standard way to present testing hooks. If you can modify your component, doing this would simplify the query:
-
Update your component:
const ExampleComponent = () => {
return (
<button data-testid="submit-button">Submit</button>
);
};
-
Update your test:
test('should find the submit button by testid attribute', () => {
render(<ExampleComponent />);
// Now using getByTestId to find the button
const submitButton = screen.getByTestId('submit-button');
// Verify the button is present
expect(submitButton).toBeInTheDocument();
});
Conclusion
In summary, while you can directly use attributes like data-qa, using data-testid or data-test is a more common practice within the React Testing Library because it clearly indicates its purpose for testing and is widely recognized in the community. Use whichever method aligns best with your project’s guidelines.