[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