lom*_*ine 7 javascript reactjs jestjs react-testing-library
我正在学习有关反应测试的教程。本教程有一个像这样的简单组件来显示测试异步操作:
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
Run Code Online (Sandbox Code Playgroud)
而测试文件是这样的:
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')
});
Run Code Online (Sandbox Code Playgroud)
终端表示waitForElement
已弃用and to use
waitFor`。
我如何waitFor
在这个测试文件中使用?
如果您正在等待外观,您可以像这样使用它:
it('increments counter after 0.5s', async() => {
const { getByTestId, getByText } = render(<TestAsync />);
fireEvent.click(getByTestId('button-up'));
await waitFor(() => {
expect(getByText('1')).toBeInTheDocument();
});
});
Run Code Online (Sandbox Code Playgroud)
.toHaveTextContent('1')
当您getByText('1')
用来抓取该元素时,检查有点“奇怪” ,因此我将其替换为.toBeInTheDocument()
.
归档时间: |
|
查看次数: |
7577 次 |
最近记录: |