som*_*491 12 javascript reactjs react-testing-library
我想使用反应测试库获取 span 元素的值。
我想做什么?
我有一个如下所示的 span 元素,显示一些值
render = () => {
const count = 2;
return (
<span data-test-id="test-span">
{count}
</span>
)
}
Run Code Online (Sandbox Code Playgroud)
现在在我的测试中我访问如下元素,
const span_element = getByTestId('test-span');
Run Code Online (Sandbox Code Playgroud)
但我不知道如何检索它的价值。
我尝试使用 span_element.value 但说“HTMLElement 上不存在属性值”
我怎样才能解决这个问题。有人可以帮我解决这个问题吗?谢谢。
Flo*_*Flo 19
您需要的是 DOM 元素的文本内容:
const spanTextContent: string = getByTestId('test-span').textContent;
Run Code Online (Sandbox Code Playgroud)
请参阅:https ://developer.mozilla.org/en/docs/Web/API/Node/textContent
请注意,将返回该节点及其所有后代textContent的文本内容。
value通常指的是交互元素(如输入)的 value 属性,您可以像这样检索它:
const inputValue: string = getByTestId('refers-to-input').getAttribute('value');
Run Code Online (Sandbox Code Playgroud)
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input/number#value
https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute