如何为作为 props 传递给“react-data-table-component”的函数编写测试用例?

问题描述 投票:0回答:1
import React from "react";
import DataTable from 'react-data-table-component'

export const Component = () =>{

  const openDetailPopup = (row: Trip) => {
    router.push({
      pathname: '/current-trip-detail',
      query: { tripId: row.tripId, entryPath },
    })
  }


<DataTable
       .....
        onRowClicked={(row) => openDetailPopup(row)}
        customStyles={customStyles}
        data-testid='current_trips_table'
      />
    </div>
}

jest 中的测试用例,react-testing 库。我需要 openDetailPopup 的覆盖范围 反应数据表组件 - https://www.npmjs.com/package/react-data-table-component

reactjs typescript jestjs react-testing-library react-data-table-component
1个回答
0
投票

测试示例:

index.tsx

import React from 'react';
import DataTable from 'react-data-table-component';

const dataMock = (colProps?: any) => {
  return {
    columns: [{ name: 'Test', selector: (row: { name: string }[]) => row.some.name, ...colProps }],
    data: [
      {
        id: 1,
        some: { name: 'Apple' },
        disabled: false,
        selected: false,
        completed: false,
        isSpecial: false,
        defaultExpanded: false,
      },
      {
        id: 2,
        some: { name: 'Zuchinni' },
        disabled: false,
        selected: false,
        completed: false,
        isSpecial: false,
        defaultExpanded: false,
      },
    ],
  };
};
const data = dataMock();

export const MyComponent = () => {
  const openDetailPopup = (record: any) => {
    console.log('🚀 ~ openDetailPopup ~ record:', record);
  };

  return <DataTable onRowClicked={(row) => openDetailPopup(row)} columns={data.columns} data={data.data} />;
};

index.test.tsx

import React from 'react';
import { MyComponent } from '.';
import { fireEvent, render } from '@testing-library/react';
import { STOP_PROP_TAG } from 'react-data-table-component';

describe('75309959', () => {
  test('should pass', () => {
    const { container } = render(<MyComponent />);
    const div = container.querySelector(`div[data-tag="${STOP_PROP_TAG}"]`) as HTMLElement;
    fireEvent.click(div);
  });
});

测试结果:


  console.log
    🚀 ~ openDetailPopup ~ record: {
      id: 1,
      some: { name: 'Apple' },
      disabled: false,
      selected: false,
      completed: false,
      isSpecial: false,
      defaultExpanded: false
    }

      at log (stackoverflow/75309959/index.tsx:33:13)

 PASS  stackoverflow/75309959/index.test.tsx
  75309959
    √ should pass (64 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.133 s
Ran all test suites related to changed files.

封装版本:

"@testing-library/react": "^14.1.2",
"@testing-library/jest-dom": "^6.1.4",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"react": "^18.2.0",
"react-data-table-component": "^7.6.2",
© www.soinside.com 2019 - 2024. All rights reserved.