[2
有效的反应组件测试至关重要。 React测试库(RTL)简化了此过程,强调用户交互测试。 本文介绍了五种高级RTL技术,用于编写更有效和可维护的单元测试。
1。 优先级
screen对象始终提高可读性和清晰度。
增强测试可读性。
例子:
使用:
使成为(); 期待(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 ofrender();
expect(screen.getByText(/click me/i)).toBeInTheDocument();
好处:
为异步组件创建更强大的测试。
例子:
// component asynchronally获取并显示一个用户名
渲染(
waitfor 可以实现相似的结果,但是的组合
定位特定容器中的元素时,在实用程序中预防了模棱两可的匹配。
// 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();
});
用于现实的互动
while userevent 好处:
更准确的事件仿真。
从'@testing-library/user-event'导入USEREVENT';
渲染(
render(
);
const nameLabel = within(screen.getByRole('group')).getByLabelText(/Name/i);
expect(nameLabel).toBeInTheDocument();
debug()[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();
结论:免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3