Loading...
Loading...
Compare original and translation side by side
// Core imports
import { http, HttpResponse, graphql, ws, delay, passthrough } from 'msw';
import { setupServer } from 'msw/node';
// Basic handler
http.get('/api/users/:id', ({ params }) => {
return HttpResponse.json({ id: params.id, name: 'User' });
});
// Error response
http.get('/api/fail', () => {
return HttpResponse.json({ error: 'Not found' }, { status: 404 });
});
// Delay simulation
http.get('/api/slow', async () => {
await delay(2000);
return HttpResponse.json({ data: 'response' });
});
// Passthrough (NEW in 2.x)
http.get('/api/real', () => passthrough());// 核心导入
import { http, HttpResponse, graphql, ws, delay, passthrough } from 'msw';
import { setupServer } from 'msw/node';
// 基础处理器
http.get('/api/users/:id', ({ params }) => {
return HttpResponse.json({ id: params.id, name: 'User' });
});
// 错误响应
http.get('/api/fail', () => {
return HttpResponse.json({ error: 'Not found' }, { status: 404 });
});
// 延迟模拟
http.get('/api/slow', async () => {
await delay(2000);
return HttpResponse.json({ data: 'response' });
});
// 请求透传(2.x 新增功能)
http.get('/api/real', () => passthrough());// vitest.setup.ts
import { beforeAll, afterEach, afterAll } from 'vitest';
import { server } from './src/mocks/server';
beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));
afterEach(() => server.resetHandlers());
afterAll(() => server.close());// vitest.setup.ts
import { beforeAll, afterEach, afterAll } from 'vitest';
import { server } from './src/mocks/server';
beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));
afterEach(() => server.resetHandlers());
afterAll(() => server.close());import { http, HttpResponse } from 'msw';
import { server } from '../mocks/server';
test('shows error on API failure', async () => {
server.use(
http.get('/api/users/:id', () => {
return HttpResponse.json({ error: 'Not found' }, { status: 404 });
})
);
render(<UserProfile id="123" />);
expect(await screen.findByText(/not found/i)).toBeInTheDocument();
});import { http, HttpResponse } from 'msw';
import { server } from '../mocks/server';
test('当API失败时显示错误', async () => {
server.use(
http.get('/api/users/:id', () => {
return HttpResponse.json({ error: 'Not found' }, { status: 404 });
})
);
render(<UserProfile id="123" />);
expect(await screen.findByText(/not found/i)).toBeInTheDocument();
});// ❌ NEVER mock fetch directly
jest.spyOn(global, 'fetch').mockResolvedValue(...)
// ❌ NEVER mock axios module
jest.mock('axios')
// ❌ NEVER test implementation details
expect(fetch).toHaveBeenCalledWith('/api/...')
// ✅ ALWAYS use MSW
server.use(http.get('/api/...', () => HttpResponse.json({...})))
// ✅ ALWAYS test user-visible behavior
expect(await screen.findByText('Success')).toBeInTheDocument()// ❌ 绝不要直接mock fetch
jest.spyOn(global, 'fetch').mockResolvedValue(...)
// ❌ 绝不要mock axios模块
jest.mock('axios')
// ❌ 绝不要测试实现细节
expect(fetch).toHaveBeenCalledWith('/api/...')
// ✅ 始终使用MSW
server.use(http.get('/api/...', () => HttpResponse.json({...})))
// ✅ 始终测试用户可见的行为
expect(await screen.findByText('Success')).toBeInTheDocument()| Decision | Recommendation |
|---|---|
| Handler location | |
| Default behavior | Return success |
| Override scope | Per-test with |
| Unhandled requests | Error (catch missing mocks) |
| GraphQL | Use |
| WebSocket | Use |
| 决策项 | 推荐方案 |
|---|---|
| 处理器位置 | |
| 默认行为 | 返回成功响应 |
| 覆盖范围 | 通过 |
| 未处理请求 | 抛出错误(捕获缺失的模拟) |
| GraphQL | 使用 |
| WebSocket | 使用 |
| Resource | Description |
|---|---|
| references/msw-2x-api.md | Complete MSW 2.x API reference |
| examples/handler-patterns.md | CRUD, auth, error, and upload examples |
| checklists/msw-setup-checklist.md | Setup and review checklists |
| scripts/handlers-template.ts | Starter template for new handlers |
| 资源 | 描述 |
|---|---|
| references/msw-2x-api.md | 完整的MSW 2.x API参考文档 |
| examples/handler-patterns.md | CRUD、认证、错误和上传等场景示例 |
| checklists/msw-setup-checklist.md | 安装和检查清单 |
| scripts/handlers-template.ts | 新处理器的起始模板 |
unit-testingintegration-testingvcr-http-recordingunit-testingintegration-testingvcr-http-recording