March 11, 2025

Enzyme vs React Testing Library (RTL)


Enzyme vs React Testing Library (RTL) 差異比較

1. 設計理念

特性EnzymeReact Testing Library (RTL)
測試方式偏向測試 內部實作 (Implementation details)偏向測試 使用者行為 (User interactions)
測試目標可測試元件的 內部狀態、方法、props主要關注 畫面輸出 (DOM) 和使用者行為
渲染方式shallow (淺渲染) 和 mount (完整渲染)render() 直接掛載到 DOM
與 React 的相容性需要額外適配新版本 React官方維護,與 React 版本同步

2. API 和測試方式對比

(1) 元件渲染方式

Enzyme

import { shallow, mount } from 'enzyme';
import MyComponent from './MyComponent';

test('Enzyme 測試', () => {
  const wrapper = shallow(<MyComponent />);
  expect(wrapper.find('button').text()).toBe('Click me');
});

React Testing Library

import { render, screen } from '@testing-library/react';
import MyComponent from './MyComponent';

test('RTL 測試', () => {
  render(<MyComponent />);
  expect(screen.getByRole('button')).toHaveTextContent('Click me');
});

(2) 事件模擬

Enzyme

test('按鈕點擊', () => {
  const wrapper = shallow(<MyComponent />);
  wrapper.find('button').simulate('click');
  expect(wrapper.find('.count').text()).toBe('1');
});

React Testing Library

import userEvent from '@testing-library/user-event';

test('按鈕點擊', async () => {
  render(<MyComponent />);
  const button = screen.getByRole('button');
  await userEvent.click(button);
  expect(screen.getByText('1')).toBeInTheDocument();
});

3. Enzyme vs RTL 適用場景

適用情境EnzymeReact Testing Library
測試內部邏輯 (state, props, methods)✅ 適合❌ 不適合
測試 UI 和互動 (DOM 渲染、按鈕點擊)❌ 不推薦✅ 更適合
React Hooks 相容性❌ 需要額外適配✅ 天然支援
React 18 支援🚧 (官方不再更新)✅ 完全相容
學習曲線📉 易上手📈 需要適應

4. 結論

如果你的專案是新的,建議直接使用 React Testing Library,因為 Enzyme 已經不再更新,未來可能會有相容性問題。