2

I need to override default testID attribute in React Testing Library. Using Jest as a testing framework.

For this, I have followed the steps given here at individual test file level.

Is there any way to have this configuration at global (project) level, so that all the test files in the project will adhere to such custom configuration and will not have need to define custom configuration explicitly at test file level?

2
  • Are you using jest ? Can you post your general testing configuration file ? Commented Dec 31, 2020 at 8:38
  • Yes using Jest. Updated the question. Commented Dec 31, 2020 at 9:53

3 Answers 3

7

If using jest you can add the following in file

import { configure } from 'react-testing-library';

configure({
  testIdAttribute: 'data-my-test-id',
});

and include that file in the jest.config.js file in the setupFiles property

setupFiles: [
  '<rootDir>/path-to-your-configuration-file.js',
]
Sign up to request clarification or add additional context in comments.

1 Comment

Im trying to do the above but i get an error when i run my test: `{import {configure} from 'react-testing-library'; SyntaxError: Cannot use import statement outside a module
0

If you're using the @testing-library/react can use as mentioned below and it's works.

import { render, screen, fireEvent, configure } from '@testing-library/react';
configure({testIdAttribute: 'data-test-id'})
const shareButton = screen.getByTestId('test-active');
expect(shareButton.getAttribute('aria-checked')).toBe('false');

1 Comment

For me it looks like the same answer as Gabriel's. You should upvote that answer, and only write a new one, if your solution is unique.
-2

https://testing-library.com/docs/dom-testing-library/api-configuration/#introduction

import {configure} from '@testing-library/dom'

configure({
  testIdAttribute: 'data-my-test-id',
  
})

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.