You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用React和Jest为Ant Design Table编写单元测试

解决方案:Ant Design Table + Axios Jest 单元测试

问题分析

你的测试代码无法加载mock数据,核心问题有两个:

  • Mock响应结构错误:组件中response.data是数组并调用了map,但你定义的mockResponse是单个对象,且未包裹在data字段中
  • 数据映射逻辑不匹配:组件里将item.id映射为key,但你的mock数据里用的是key: '1',与组件预期不符

修正后的测试代码

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

// 自动mock axios
jest.mock('axios');

describe('TableData Component', () => {
  it('renders table with mock data correctly', async () => {
    // 构造符合组件预期的mock响应
    const mockApiResponse = {
      data: [
        {
          id: '1', // 对应组件里的item.id映射为key
          name: 'John Brown',
          age: 32,
          address: 'New York No. 1 Lake Park',
          tags: ['nice', 'developer'],
        }
      ]
    };

    // 用mockResolvedValue简化mock异步响应写法
    axios.get.mockResolvedValue(mockApiResponse);

    render(<TableData />);

    // 等待异步数据加载完成并渲染
    await waitFor(() => {
      // 断言Name列的链接文本存在(组件将name渲染为a标签)
      expect(screen.getByRole('link', { name: /john brown/i })).toBeInTheDocument();
      // 断言Age字段内容存在
      expect(screen.getByText('32')).toBeInTheDocument();
      // 断言Tag文本存在(组件会将tag转为大写)
      expect(screen.getByText('NICE')).toBeInTheDocument();
      expect(screen.getByText('DEVELOPER')).toBeInTheDocument();
    });

    // 验证axios.get是否被正确调用
    expect(axios.get).toHaveBeenCalledTimes(1);
    expect(axios.get).toHaveBeenCalledWith('http://localhost:5000/getData');
  });
});

关键说明

  • Mock响应结构对齐:必须和后端返回格式一致,组件依赖response.data的数组结构,所以mock对象要包含data字段且值为数组
  • 数据映射匹配:组件里用item.id作为Table行的key,所以mock数据里要提供id字段,而非直接写key
  • 断言语义化:用getByRole替代getByText更符合DOM语义(Name列是链接元素),同时覆盖组件的渲染细节(比如Tag的大写转换)
  • API调用验证:额外断言axios的调用次数和参数,确保组件正确发起了目标请求

内容的提问来源于stack exchange,提问作者Aravind Ashokkumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 20:28:13