试着测试一个简单的组件,它呈现一个字符串列表,当单击时,每个项目都会移动到顶部。
const Component = p => {
const [data, setData] = React.useState(p.data)
const moveToTop = from => {
const nextData = [...data]
const target = nextData.splice(from, 1)[0]
nextData.unshift(target)
setData(nextData)
}
console.log(data, 'data')
return (
<ul>
{data.map((d, i) => (
<li
aria-label="li"
key={d}
onClick={() => {
moveToTop(i)
}}
>
{d}
</li>
))}
</ul>
)
}
// ... test ...
test('move element', async () => {
render(<Component data={['a', 'b', 'c']} />)
const liArr = screen.getAllByLabelText('li')
expect(liArr.length).toBe(3)
expect(liArr[0].textContent).toBe('a')
fireEvent.click(liArr[2])
expect(liArr[0].textContent).toBe('c')
})在codesandbox中,日志显示clickEvent设置数据成功,但上次断言失败。我知道react re-render很耗时,但我也注意到@testing-library/react为其render api包装了act。在搜索github问题和堆栈溢出之后,我仍然被困在这个测试用例中。
需要您的帮助,任何文档和样本都会有意义,谢谢!
发布于 2020-07-26 03:31:20
li顺序更改了,但您没有在新结构上断言。在单击事件之后执行另一个screen.getAllByLabelText('li')并对其进行断言。
https://stackoverflow.com/questions/63048586
复制相似问题