React 测试库 - 在测试组件之前等待状态更新
我正在第一次渲染时测试组合框,组合框的初始值未定义。然后使用查询参数和 useEffect 组件找到相关选项并为其设置值状态。
const Component = () => {
[value, setValue] = useState(undefined);
useEffect(() => {
setValue("hello")
}, [])
return(
<Combobox value={value}/>
)
}
it("should render with value as hello", () => {
const {getByText} = render(<Component/>)
const text = getByText("hello")
})
该测试套件抛出此错误:
TestingLibraryElementError: Unable to find an element with the text: Photobug. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.
在反应测试库中进行测试时。我无法检索预期的文本值,这是因为它显示了第一次渲染时渲染的内容。这本来就没什么,因为价值是未定义的。
我尝试过异步方法的组合。 Aync 等待模式、await waitFor(() => )、findByText 等都无济于事。
I am testing a combobox on first render the initial value of the combobox is undefined. Then using query parameters and a useEffect the the component find the relevant option and sets the value state to it.
const Component = () => {
[value, setValue] = useState(undefined);
useEffect(() => {
setValue("hello")
}, [])
return(
<Combobox value={value}/>
)
}
it("should render with value as hello", () => {
const {getByText} = render(<Component/>)
const text = getByText("hello")
})
That test suite throws this error:
TestingLibraryElementError: Unable to find an element with the text: Photobug. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.
When testing in react testing library. I cannot retrieve the expected text value this is because it shows what has been rendered on first render. Which would have been nothing because value is undefined.
I have tried a combination of async methods. Aync await pattern, await waitFor(() => ), findByText etc all to no avail.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看起来在您的测试中您需要等待组件完全渲染。您可以使用React测试库提供的 waitFor 方法。
我尝试使用输入框重现您的问题。
组件:
测试用例:
在您的情况下,您必须将角色指定为组合框。
Looks like in your test you need to wait till your component is fully rendered. You can use waitFor method provided by react testing library.
I tried to reproduce your issue with an input box.
Component:
Test case :
In your case, you have to give role as combobox.