Reputation: 1303
In my React project, sometimes a dynamically generated UUID needs to be added to the a data-testid
value to ensure uniqueness amongst duplicate components in the DOM.
I have a test situation where I can grab the element I want. Now I want to get the dynamically generated data-testid from it. I've tried this but it doesn't work:
const questionDropdown = queryAllByText('Free Text')[0];
console.log(questionDropdown.getAttribute('data-testid'));
Any suggestions how to get it?
Upvotes: 1
Views: 6748
Reputation: 1303
I finally figured out how to do it!
So, I have a Semantic-UI Dropdown with a dynamically generated data-testid
. The trick to getting the element is simply to use Regex, like this:
const questionTypeDropdown = getByTestId(/conditional-task-question-type/);
Upvotes: 0
Reputation: 1303
I'm revisiting this. I believe that the answer from adesuriey
works great if you're dealing with conventional text, say in an Input element. But in the Semantic UI Dropdown it does not appear to work.
I think the problem lies with finding the correct ancestor element. I've tried many things but with no success.
Upvotes: -1
Reputation: 2620
I think it's a dataset so you can get it like this:
console.log(questionDropdown.dataset.testid);
If you have an expected result you can test it with testing-library/jest-dom
:
expect(questionDropdown).toHaveAttribute("data-testid", "test-id");
Doc: https://github.com/testing-library/jest-dom#tohaveattribute
Upvotes: 3