如何用React Testing Library测试基于Promise.all的多请求场景?
测试基于Promise.all的多请求React组件
核心结论
不需要配置多个服务器,单个setupServer实例就能处理多个不同URL的请求,只需为每个请求URL配置对应的响应处理器即可。
测试步骤与示例
1. 依赖准备
确保安装必要的测试依赖:
npm install -D msw @testing-library/react @testing-library/jest-dom
2. 完整测试用例
以下是针对你的Commissions组件的测试实现:
import { render, screen, waitFor } from '@testing-library/react'; import { setupServer } from 'msw/node'; import { rest } from 'msw'; import Commissions from './Commissions'; // 配置单个服务器,处理四个请求URL const server = setupServer( // 模拟用户数据接口响应 rest.get('http://...', (req, res, ctx) => { return res(ctx.json([{ id: 1, date: '2024-01-01' }, { id: 2, date: '2024-01-02' }])); }), // 模拟现金存入手续费接口响应 rest.get('https://...', (req, res, ctx) => { return res(ctx.json({ fee: 0.03 })); }), // 模拟自然人现金取出手续费接口响应 rest.get('https://...', (req, res, ctx) => { return res(ctx.json({ fee: 0.05 })); }), // 模拟法人现金取出手续费接口响应 rest.get('https://...', (req, res, ctx) => { return res(ctx.json({ fee: 0.07 })); }) ); // 测试生命周期钩子 beforeAll(() => server.listen()); afterEach(() => server.resetHandlers()); afterAll(() => server.close()); test('初始显示加载状态,直到所有请求完成', async () => { render(<Commissions />); // 验证初始加载状态 expect(screen.getByText('Loading...')).toBeInTheDocument(); // 等待加载状态消失 await waitFor(() => { expect(screen.queryByText('Loading...')).not.toBeInTheDocument(); }); }); test('所有请求成功后渲染用户数据表格', async () => { render(<Commissions />); // 等待表头渲染完成 await screen.findByText('User Id:'); // 验证表格行数(表头1行 + 2条数据行) expect(screen.getAllByRole('row')).toHaveLength(3); }); test('任意请求失败时显示错误提示', async () => { // 临时替换用户数据接口,返回500错误 server.use( rest.get('http://...', (req, res, ctx) => { return res(ctx.status(500), ctx.json({ message: '服务器内部错误' })); }) ); render(<Commissions />); // 等待错误信息出现 const errorElement = await screen.findByText(/An error happened:/); expect(errorElement).toHaveTextContent('An error happened: 服务器内部错误'); });
关键注意事项
- URL精确匹配:确保
setupServer中配置的URL与组件内请求的URL完全一致(包括协议、域名、路径)。 - Promise.all错误特性:只要有一个请求失败,
Promise.all就会触发catch逻辑,测试时可通过替换单个请求处理器模拟错误场景。 - 异步状态等待:使用
waitFor或findBy*系列查询方法,等待组件异步状态更新后再执行断言,避免测试过早失败。 - 测试隔离:通过
server.resetHandlers()在每个测试后重置请求处理器,保证测试用例之间互不干扰。
内容的提问来源于stack exchange,提问作者Azu
相关产品推荐
相关产品推荐

