gpt4 book ai didi

javascript - React 测试库如何使用 waitFor

转载 作者:行者123 更新时间:2023-12-03 21:44:05 26 4
gpt4 key购买 nike

我关注 a tutorial关于 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在这个测试文件中?

最佳答案

如果您是 waiting for appearance ,你可以像这样使用它:

it('increments counter after 0.5s', async() => {
const { getByTestId, getByText } = render(<TestAsync />);

fireEvent.click(getByTestId('button-up'));

await waitFor(() => {
expect(getByText('1')).toBeInTheDocument();
});
});
检查 .toHaveTextContent('1')使用 getByText('1') 时有点“奇怪”捕获那个元素,所以我用 .toBeInTheDocument() 替换它.

关于javascript - React 测试库如何使用 waitFor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65725591/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com