我有一个表,给定downloadRequested
,它将使用提供的tableRef并返回表中的sortedData。尝试添加单元测试以确保在<CSVLink>
上呈现downloadRequested = true
时,我一直遇到以下错误:
TypeError: Cannot read property 'getResolvedState' of null
我应该嘲笑裁判吗?还是我需要以某种方式提供它?我如何解决这个问题?
代码:
import React, { useRef } from "react";
import { CSVLink } from "react-csv";
function MyTable(props) {
const tableRef = useRef(null);
const getColumns = () => {
return [{ Header: "Name", accessor: "name" }, { Header: "Id", accessor: "id" }];
};
const getCsvData = () => {
const keys = ["name", "id"];
return tableRef.current.getResolvedState().sortedData.map(row => getCsvDataFromTable(keys, row));
};
return (
<>
{props.downloadRequested && (
<CSVLink data={getCsvData()} target="_blank" filename={`myTable.csv`} data-testid="csvLink">
<div
data-testid="csvLinkDiv"
ref={e => {
if (e) {
e.click();
}
}}
/>
</CSVLink>
)}
<Table columns={getColumns(props)} filterable forwardedRef={tableRef} {...props} />
</>
);
}
export default MyTable;
测试套件:
import React from "react";
import { render } from "@testing-library/react";
import MyTable from "./MyTable";
describe("MyTable", () => {
const sampleData = [{ id: "123", name: "John Doe" }, { id: "456", name: "Doe John" }];
it("Should render MyTable with CSV Link correctly", () => {
const { queryByTestId } = render(<MyTable data={sampleData} downloadRequested={true} />);
expect(queryByTestId("csvLink")).toBeTruthy();
});
});
答案 0 :(得分:0)
好吧,我知道了。我的问题源于一个事实,即CSV-Link需要在运行时具有数据,而这种设置方式直到后来才得到。无论如何,正在发生的事情是在初始化表之前调用了getCsvData(),因此ref始终为null。我使用的一种解决方法是先使用downloadRequested = false呈现它,然后将其重新呈现(现在有一个表),其值为true。