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

如何为react-data-table-component的props传入函数编写Jest测试用例?

测试react-data-table-component行点击函数的用例编写指南

核心测试目标

验证表格行被点击时,openDetailPopup函数是否正确调用router.push,并传入符合预期的路径与查询参数。

步骤1:依赖与Mock准备

确保已安装jest、@testing-library/react、@testing-library/jest-dom。由于代码使用Next.js路由,需提前mocknext/router:

// 测试文件顶部添加路由mock
jest.mock('next/router', () => ({
  useRouter: () => ({
    push: jest.fn(),
  }),
}));

步骤2:完整测试用例代码

import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import { useRouter } from 'next/router';
import { Component } from './your-component-path'; // 替换为组件实际路径

// 模拟测试用的Trip数据
const mockTrip = {
  tripId: 'test-trip-001',
  // 补充Trip类型所需其他字段
};

// 模拟组件内的entryPath变量
jest.mock('./your-component-path', () => ({
  ...jest.requireActual('./your-component-path'),
  entryPath: '/test-entry-page', // 替换为实际值或测试用值
}));

describe('数据表格行点击测试', () => {
  it('点击行应触发router.push并传入正确参数', () => {
    const router = useRouter();
    
    // 渲染组件,若组件需传入data属性则补充传递
    render(<Component data={[mockTrip]} />);
    
    // 获取表格行,跳过表头行(索引0)取第一行数据行
    const tableRows = screen.getAllByRole('row');
    const targetRow = tableRows[1];
    
    // 触发行点击事件
    fireEvent.click(targetRow);
    
    // 断言路由跳转参数正确
    expect(router.push).toHaveBeenCalledWith({
      pathname: '/current-trip-detail',
      query: { tripId: mockTrip.tripId, entryPath: '/test-entry-page' },
    });
  });
});

关键要点说明

  • 路由Mock:通过mockuseRouter避免依赖真实路由环境,同时捕获push方法的调用情况。
  • 测试数据传递:确保组件渲染时传入有效测试数据,否则表格不会生成数据行。若数据是组件内部通过API获取,需同步mock对应API请求。
  • 行元素定位:用getAllByRole('row')获取表格行,表头行默认是第一个元素;也可给数据行添加data-testid实现更精准定位。
  • 变量模拟:若entryPath是组件外部导入或内部定义的变量,需通过jest.mock模拟其值,保证测试参数准确性。

内容的提问来源于stack exchange,提问作者Rahul M.V

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 05:35:40