我正在跟随一个React测试的教程。该教程有一个简单的组件,如下,演示如何测试异步操作:
import React from 'react'
const TestAsync = () => {
const [counter, setCounter] = React.useState(0)
const delayCount = () => (
setTimeout(() => {
setCounter(counter + 1)
}, 500)
)
return (
<>
<h1 data-testid="counter">{ counter }</h1>
<button data-testid="button-up" onClick={delayCount}> Up</button>
<button data-testid="button-down" onClick={() => setCounter(counter - 1)}>Down</button>
</>
)
}
export default TestAsync
测试文件就像这样:
import React from 'react';
import { render, cleanup, fireEvent, waitForElement } from '@testing-library/react';
import TestAsync from './TestAsync'
afterEach(cleanup);
it('increments counter after 0.5s', async () => {
const { getByTestId, getByText } = render(<TestAsync />);
fireEvent.click(getByTestId('button-up'))
const counter = await waitForElement(() => getByText('1'))
expect(counter).toHaveTextContent('1')
});
终端显示 waitForElement
已被弃用,应改用 waitFor
代替。
在这个测试文件中,我该如何使用 waitFor
?
act
函数包装这个断言?根据文档,我不明白何时应该使用act
,何时应该使用waitFor
。 - Rob Bauer