簡介
與常規 SPA 測試相比,測試微前端面臨額外的挑戰:每個 MFE 需要測試隔離(獨立)和整合(在 Shell 應用程式中)。本文為這兩種場景建構了測試策略。
1. 微前端的測試級別
┌─────────────────────────────────────┐
│ E2E Tests (Playwright/Cypress) │ Full app, all MFEs loaded
│ Critical user flows across MFEs │
├─────────────────────────────────────┤
│ Integration Tests │ MFE loaded in Shell
│ Cross-MFE communication, routing │
├─────────────────────────────────────┤
│ Visual Regression Tests │ Screenshot comparison
│ Chromatic / Percy / Playwright │
├─────────────────────────────────────┤
│ Component Tests (RTL) │ Individual components
│ Each MFE tested in isolation │
├─────────────────────────────────────┤
│ Unit Tests (Jest/Vitest) │ Hooks, utils, business logic
│ Pure functions, state management │
└─────────────────────────────────────┘
2.元件測試(React測試庫)
// ProductCard.test.tsx
import { render, screen, fireEvent } from '@testing-library/react';
import { ProductCard } from './ProductCard';
describe('ProductCard', () => {
const product = {
id: '1', name: 'Laptop', price: 999, image: '/laptop.jpg'
};
it('renders product info', () => {
render(<ProductCard product={product} />);
expect(screen.getByText('Laptop')).toBeInTheDocument();
expect(screen.getByText('$999')).toBeInTheDocument();
});
it('dispatches add-to-cart event', () => {
const spy = jest.fn();
window.addEventListener('cart:item-added', spy);
render(<ProductCard product={product} />);
fireEvent.click(screen.getByRole('button', { name: /add to cart/i }));
expect(spy).toHaveBeenCalled();
window.removeEventListener('cart:item-added', spy);
});
});
3.視覺迴歸測試
3.1 故事書+半音階
// Button.stories.tsx
export const AllVariants = () => (
<div>
<Button variant="primary">Primary</Button>
<Button variant="secondary">Secondary</Button>
<Button variant="danger">Danger</Button>
<Button disabled>Disabled</Button>
</div>
);
彩色工作流程:
1. Push code → CI runs Storybook build
2. Chromatic captures screenshots
3. Compare with baseline
4. Visual diff review → Approve/Reject
3.2 劇作家視覺
test('product list matches snapshot', async ({ page }) => {
await page.goto('/products');
await expect(page).toHaveScreenshot('product-list.png', {
maxDiffPixelRatio: 0.01,
});
});
4. 整合測試(Shell 中的 MFE)
// Test Product MFE loaded in Shell context
describe('Product MFE Integration', () => {
it('loads product list in shell', async ({ page }) => {
await page.goto('/products');
// Verify MFE loaded successfully
await expect(page.getByTestId('product-list')).toBeVisible();
// Verify routing works
await page.click('[data-testid="product-card"]');
await expect(page).toHaveURL(/\/products\/\d+/);
});
it('add to cart updates cart badge in shell header', async ({ page }) => {
await page.goto('/products');
// Click add to cart (Product MFE)
await page.click('[data-testid="add-to-cart"]');
// Verify cart badge updated (Shell Header)
await expect(page.getByTestId('cart-badge')).toHaveText('1');
});
});
5. 每個 MFE 的測試策略
| 測試類型 | 當 | 工具 | CI階段 |
|---|---|---|---|
| 單位 | 每次提交 | 開玩笑/維斯特 | 預先合併 |
| 組件 | 每次提交 | 左轉 | 預合併 |
| 視覺 | 每一次公關 | 半音 | 公關審查 |
| 整合 | 每日/每周 | 剧作家 | 合并后 |
| 端到端 | 每日 | 劇作家 | 分期 |
6. 最佳實踐
✅ Test MFE standalone (without Shell) → fast feedback
✅ Test MFE in Shell → integration correctness
✅ Visual regression cho Design System → catch UI drift
✅ Test cross-MFE events → verify contracts
✅ Mock API calls in component tests → deterministic
❌ Don't test implementation details
❌ Don't test remote MFE code from another MFE's test suite
❌ Don't rely on E2E for all coverage → too slow
總結
- 組件測試:每個 MFE 測試均使用 RTL 獨立進行
- 視覺回歸:故事書 + Chromatic catch UI 更改
- 整合測試:Shell 中的 MFE、跨 MFE 通信
- E2E:僅關鍵流程,在分段上運行
- 測試 MFE 之間的事件(合約)
下一篇文章: 第 22 課:契約測試 — Pact 和 API 相容性