How to get the value of the span element with testid using react testing library?
Asked Answered
A

2

12

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.

Amara answered 7/5, 2020 at 9:54 Comment(1)
The right syntax is "data-testid" and not "data-test-id"Folk
H
20

What you need is the text content of the DOM element :

const spanTextContent: string = getByTestId('test-span').textContent;

See : https://developer.mozilla.org/en/docs/Web/API/Node/textContent

Note that textContent will return the text content of the node and all its descendants.

value usually refers to the value attribute of interactive elements like inputs, and you could retrieve it like so :

const inputValue: string = getByTestId('refers-to-input').getAttribute('value');

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input/number#value

https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute

Hilda answered 7/5, 2020 at 19:4 Comment(0)
M
0

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');
...
Marquetry answered 5/11, 2021 at 12:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.