iT邦幫忙

2024 iThome 鐵人賽

DAY 12
0
Modern Web

React 學得動嗎系列 第 12

[Day 12] React 寫測試的實用指南

  • 分享至 

  • xImage
  •  

大家好,今天是我們 React 學習的第十二天,想和大家聊聊如何為 React 應用程式撰寫測試。其實,寫測試沒有想像中困難,反而能讓你的程式碼更穩定可靠。

為什麼要寫測試?
撰寫測試可以確保你的程式碼如預期運作,減少潛在的錯誤。它能幫助你在開發過程中及早發現問題,提升程式碼品質,讓後續的維護和更新更輕鬆。

React 測試的工具箱
在 React 的開發中,常用的測試工具有:

  1. Jest: 一個方便好用的 JavaScript 測試框架。
  2. React Testing Library: 專為測試 React 組件設計的工具。

這兩個工具搭配使用,可以滿足大部分的測試需求。

單元測試 vs 整合測試

  • 單元測試:專注於測試單一的組件或函數,確保它們獨立運作正常。
  • 整合測試:測試多個組件如何互相協作,確保整體功能如預期。

實際範例

1. 單元測試:測試一個簡單的組件

假設我們有一個簡單的問候組件:

// Greeting.tsx
import React from 'react';

interface GreetingProps {
  name: string;
}

const Greeting: React.FC<GreetingProps> = ({ name }) => {
  return <h1>哈囉,{name}!</h1>;
};

export default Greeting;

我們可以這樣測試它:

// Greeting.test.tsx
import React from 'react';
import { render, screen } from '@testing-library/react';
import Greeting from './Greeting';

test('顯示正確的問候語', () => {
  render(<Greeting name="小明" />);
  const greetingElement = screen.getByText(/哈囉,小明!/i);
  expect(greetingElement).toBeInTheDocument();
});

https://ithelp.ithome.com.tw/upload/images/20240926/20140358WC3caEDmxY.png

這個測試確保 Greeting 組件能正確顯示傳入的名字。

2. 整合測試:測試表單提交

再來看一個稍微複雜的例子:一個登入表單。

// LoginForm.tsx
import React, { useState } from 'react';

interface LoginFormProps {
  onSubmit: (username: string, password: string) => void;
}

const LoginForm: React.FC<LoginFormProps> = ({ onSubmit }) => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onSubmit(username, password);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        value={username}
        onChange={(e) => setUsername(e.target.value)}
        placeholder="使用者名稱"
      />
      <input
        type="password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
        placeholder="密碼"
      />
      <button type="submit">登入</button>
    </form>
  );
};

export default LoginForm;

我們可以這樣測試它:

// LoginForm.test.tsx
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import LoginForm from './LoginForm';

test('提交表單時,應以正確的值呼叫 onSubmit', () => {
  const mockOnSubmit = jest.fn();
  render(<LoginForm onSubmit={mockOnSubmit} />);

  // 填寫表單
  fireEvent.change(screen.getByPlaceholderText(/使用者名稱/i), {
    target: { value: 'testuser' },
  });
  fireEvent.change(screen.getByPlaceholderText(/密碼/i), {
    target: { value: 'testpass' },
  });

  // 提交表單
  fireEvent.click(screen.getByText(/登入/i));

  // 檢查 onSubmit 是否被正確呼叫
  expect(mockOnSubmit).toHaveBeenCalledWith('testuser', 'testpass');
});

https://ithelp.ithome.com.tw/upload/images/20240926/20140358MrYSlWd9Wr.png

這個測試模擬使用者填寫並提交表單的過程,確保表單組件能正確處理輸入並呼叫 onSubmit 函數。

測試的最佳實踐

  • 測試行為,而非實現細節:關注組件應該做什麼,而不是它如何實現。
  • 使用明確的測試名稱:測試名稱應清楚描述測試內容。
  • 避免過度約束:測試應允許實現細節的變化,只要行為保持不變。
  • 保持測試簡潔:每個測試應該只關注一件事。
  • 模擬外部依賴:使用 Jest 的 mock 功能模擬 API 呼叫等外部資源。

結論

今天我們探討了如何為 React 組件撰寫測試。測試不僅不是負擔,還是確保程式碼品質的重要工具。良好的測試能讓你更有信心地進行程式碼重構和開發新功能。

想更深入了解 React 測試,可以參考 React 官方文件的測試章節


上一篇
[Day 11] React 錯誤處理和除錯
下一篇
[Day 13] React 狀態管理介紹:Redux、MobX 和Zustand
系列文
React 學得動嗎13
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言