如何使用React Testing Library的waitFor实现异步组件测试
解决方案
首先将测试函数改为异步函数,在waitFor回调中编写延迟后的断言逻辑即可,修改后的完整测试代码如下:
import { render, screen, waitFor } from "@testing-library/react"; import App from "./App"; // 测试函数添加async关键字,支持await语法 test('验证"Log out"文本最终会出现', async () => { render(<App />); const LoginButton = screen.getByText(/Log/) // 验证初始状态 expect(LoginButton).toHaveTextContent(/Log In/i); // 等待断言满足 await waitFor(() => { expect(LoginButton).toHaveTextContent(/Log Out/i); }) });
关键说明
waitFor方法本身会返回Promise,必须配合await使用,因此需要给外层测试函数添加async修饰符- 默认情况下
waitFor的超时阈值是5000ms,完全覆盖你当前1秒延迟的场景。如果需要自定义超时时间,可以传入第二个配置参数,写法为await waitFor(回调函数, { timeout: 1500 }),即可将超时阈值调整为1500ms - 更稳定的定位方式可以直接使用你给按钮设置的
data-testid,写法为const LoginButton = screen.getByTestId('login-button'),不受文本内容修改的影响
内容的提问来源于stack exchange,提问作者Chasbeen
相关产品推荐
相关产品推荐

