如何用react-testing-library和jest测试useEffect发请求存状态的React组件
问题分析
- MSW mock响应结构与组件取值逻辑不匹配:组件默认
crew状态值为straw-hat-pirates,取值逻辑为getCrews.data[crew],但你配置的MSW返回结构是{data: {crew: [数据数组]}},getCrews.data下对应的键是crew而非straw-hat-pirates,最终取值得到undefined,赋值给totalData后调用map方法直接抛出类型错误。 - 测试代码错误对
render方法使用await:@testing-library/react 提供的render是同步方法,不需要加await修饰。 - 组件渲染逻辑健壮性不足:未判断
totalData是否为数组就直接调用map,只要值非数组就会触发报错。 - 额外检查项:需要确认MSW配置的请求地址和组件内axios调用的地址完全一致,否则mock不会生效,也会导致接口返回异常。
修复实现
1. 修正MSW响应结构
调整mock返回的字段和组件预期匹配:
const server = setupServer(rest.get('你的组件实际请求的http地址', (req, res, ctx) => { const totalData = [ { name: "doffy", price: 100, image: "image url" }, { name: "lamingo", price: 500, image: "image url" } ]; return res( ctx.status(200), ctx.json({ // 把键改成组件默认的crew值:straw-hat-pirates data: { 'straw-hat-pirates': totalData } }) ) }))
2. 修正测试用例代码
移除render前的await:
test('fetches the data from the API and correctly renders it', async () => { render(<OnePiece />) const items = await screen.findAllByAltText('product-image'); expect(items).toHaveLength(2); })
3. 可选:优化组件健壮性
修改渲染逻辑,避免非数组场景报错:
<ProductsWrapper> {/* 新增可选链判断,也可以补充空状态展示逻辑 */} {totalData?.map((product, index) => <ProductCard key={index} name={product.name} price={product.price} imageUrl={product.image} /> )} </ProductsWrapper>
内容的提问来源于stack exchange,提问作者dumblessar
相关产品推荐
相关产品推荐

