React 测试库 - 在测试组件之前等待状态更新

myc*_*OOM 14 javascript reactjs react-testing-library react-hooks react-state

我正在第一次渲染时测试组合框,组合框的初始值未定义。然后使用查询参数和 useEffect 组件找到相关选项并为其设置值状态。


const Component = () => {

[value, setValue] = useState(undefined);

useEffect(() => {

setValue("hello")

}, [])


return(
<Combobox value={value}/>
)

}

Run Code Online (Sandbox Code Playgroud)
it("should render with value as hello", () => {

const {getByText} = render(<Component/>)

const text = getByText("hello")

})

Run Code Online (Sandbox Code Playgroud)

该测试套件抛出此错误:

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.
Run Code Online (Sandbox Code Playgroud)

在反应测试库中测试时。我无法检索预期的文本值,这是因为它显示了第一次渲染时渲染的内容。这本来就没什么,因为价值是未定义的。

我尝试过异步方法的组合。Aync 等待模式、await waitFor(() => )、findByText 等都无济于事。

Ank*_*ena 15

看起来在您的测试中您需要等待组件完全渲染。您可以使用react测试库提供的waitFor方法。

我尝试使用输入框重现您的问题。

成分:

import { useState, useEffect } from "react";

export const Component = () => {

  const[value, setValue] = useState('');
  
  useEffect(() => {
  
  setValue("hello")
  
  }, [])
  
  
  return(
  <input value={value}/>
  )
  
  }
Run Code Online (Sandbox Code Playgroud)

测试用例 :

it("should render with value as hello", async () => {
    const {getByRole} = render(<Component/>)
    await waitFor(() => expect(getByRole('textbox')).toHaveValue('hello'))
    })

Run Code Online (Sandbox Code Playgroud)

就您而言,您必须将角色指定为组合框。

    await waitFor(() => expect(getByRole('combobox')).toHaveValue('hello'))

Run Code Online (Sandbox Code Playgroud)