”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > RICKS用于React测试库,以使您的单位测试更好

RICKS用于React测试库,以使您的单位测试更好

发布于2025-02-07
浏览:411

[2

有效的反应组件测试至关重要。 React测试库(RTL)简化了此过程,强调用户交互测试。 本文介绍了五种高级RTL技术,用于编写更有效和可维护的单元测试。 ricks for React Testing Library to make your unit tests better

1。 优先级

screen
避免直接从

破坏查询。使用屏幕对象始终提高可读性和清晰度。

好处:

增强测试可读性。

明确显示与渲染的屏幕元素的交互。

例子:
  • 而不是:
const { getByText } = render(); 期待(getByText(/单击me/i))。

使用:

使成为(); 期待(screet.getByText(/单击me/i))。

此方法在较大的测试套件上保持一致性。

const { getByText } = render();
expect(getByText(/click me/i)).toBeInTheDocument();
For components rendering elements asynchronously (e.g., after API calls), utilize

findBy

queries instead of
render();
expect(screen.getByText(/click me/i)).toBeInTheDocument();

好处:


由于定时问题消除了片状测试。 为异步组件创建更强大的测试。

例子: // component asynchronally获取并显示一个用户名 渲染(); const用户名=等待屏幕。 期待(用户名).tobeinthedocument();

waitfor 可以实现相似的结果,但是的组合

    render(); 等待waitfor(()=> { 期待(screet.getByText(/john doe/i))。tobeinthedocument(); });
  • 3。

定位特定容器中的元素时,在实用程序中预防了模棱两可的匹配。

// Component asynchronously fetches and displays a username
render();
const userName = await screen.findByText(/john doe/i);
expect(userName).toBeInTheDocument();

预防意外元素选择。 改进测试精度。 例子:

render();
await waitFor(() => {
  expect(screen.getByText(/john doe/i)).toBeInTheDocument();
});

4。 userevent 用于现实的互动 while

fireevent

userevent 好处:

更准确的事件仿真。

    处理文本输入等复杂交互。
  • 例子:

从'@testing-library/user-event'导入USEREVENT'; 渲染(); const emailInput = screen.getByLabelText(/email/i); const passwordInput = screen.getByLabelText(/password/i); const submistButton = screen.getByrole('button',{name: /simp /i}); 等待userevent.type(emailInput,'[email protected]'); 等待userevent.type(passwordinput,'password123'); 等待userevent.click(cumbsbutton); 期待(screet.getByText(/welcome/i))。 此方法确保测试准确反映了现实世界的用户行为。

render(
  
Personal Information
); const nameLabel = within(screen.getByRole('group')).getByLabelText(/Name/i); expect(nameLabel).toBeInTheDocument();
debug()[2

好处:

快速识别缺失的元素或测试失败。 简化了调试。

例子:

render(); screen.debug(); //记录DOM结构

    [2
  • 专注于用户交互:
  • 测试用户看到和交互的,而不是内部组件状态。
组合匹配器:

使用。tohaveTextContent()清理:

当RTL处理清理时,在
import userEvent from '@testing-library/user-event';

render();
const emailInput = screen.getByLabelText(/email/i);
const passwordInput = screen.getByLabelText(/password/i);
const submitButton = screen.getByRole('button', { name: /submit/i });

await userEvent.type(emailInput, '[email protected]');
await userEvent.type(passwordInput, 'password123');
await userEvent.click(submitButton);

expect(screen.getByText(/welcome/i)).toBeInTheDocument();

结论:

[&& && rtl优先考虑以用户为中心的测试。 通过应用这些技术,您将创建更清洁,更可靠和可维护的测试,从而改善整体开发工作流程。 拥抱这些策略以增强您的反应测试实践。

最新教程 更多>

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3