'How to get the value of the span element with testid using react testing library?
I want to get the value of the span element using react testing library.
What i am trying to do?
I have a span element like below displaying some value
render = () => {
const count = 2;
return (
<span data-test-id="test-span">
{count}
</span>
)
}
Now within my test i access the element like below,
const span_element = getByTestId('test-span');
But i am not sure how to retrieve its value.
I tried using span_element.value but says 'property value doesnt exist on HTMLElement"
How can i fix this. could someone help me with this. thanks.
Solution 1:[1]
You could try this approach:
Component.js
...
render = () => {
const count = 2;
return (
<span id="test-span">
{count}
</span>
)
}
...
Component.test.js
import { screen } from "@testing-library/react";
...
// get HTML DOM element
const spanElement = await screen.queryByTestId('test-span');
// OR
// const spanElement = await screen.querySelector('test-span');
// get value from HTML DOM element
const spanElementValue = spanElement.getAttribute('value');
...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Vitalii Andrusishyn |
