Try to test a simple component which renders a list of string and each item will move to top when clicked.
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')
})
In codesandbox,log shows that clickEvent set data successfully, but last assert failed.
I know that react re-render costs time but i also notice that @testing-library/react has wrapped act for its render api. After search github issues and stackoverflow, i still got stuck in this test case.
Need your help, any doc and samples will make sense, thanks!