我有一个反应组件,用户可以在其中选择 xlsx 文件,然后解析它并在表格中显示数据。 我想为其创建一个简单的端到端测试:
我对此有三个问题
import { act, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import MyImportFile from ".";
import path from "node:path";
import { openAsBlob } from "node:fs";
describe("MyImportFile", () => {
test("does the upload work?", async () => {
const user = userEvent.setup();
render(<MyImportFile />);
expect(screen.getByText(/person_forename/i)).toBeInTheDocument();
const input = screen.getByLabelText(/Import XLSX/i);
expect(input).toBeInTheDocument();
console.log("__dirname", __dirname);
const xlsx_file_path = path.join(__dirname, "people_10_min.xlsx");
// const xlsx_file_path_abs = path.resolve(xlsx_file_path);
let blob = undefined;
try {
blob = await openAsBlob(xlsx_file_path, {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
});
} catch (error) {
console.log(error);
}
console.log("blob", blob);
// https://reactjs.org/link/wrap-tests-with-act
await act(async () => {
/* fire events that update state */
await user.upload(input, blob);
});
//const data_content = await vi.waitFor(() => screen.getByText(/Friedmann/i));
//expect(data_content).toBeInTheDocument();
});
});
我在codesandbox创建了一个或多或少的最小示例
并希望能学到很多东西:-)
我还发布了与此相关的问题
已解决 - 使用 vite-plugin-arraybuffer: 用于文件加载。
然后我就可以
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import MyImportFile from ".";
import xlsx_file from "../../../dev_tests/people_10.xlsx?arraybuffer";
describe("MyImportFile", () => {
test("does the upload work?", async () => {
const user = userEvent.setup();
render(
<MyImportFile />
);
expect(screen.getByText(/person_forename/i)).toBeInTheDocument();
const input = screen.getByLabelText(/Import XLSX/i);
expect(input).toBeInTheDocument();
await user.upload(input, xlsx_file);
const data_content = await screen.getByText(/^Friedmann/i)
expect(data_content).toBeInTheDocument();
});
});
他们的关键是删除步骤之间的所有 Blob 和文件。 因为基于承诺的
blob.arrayBuffer()
没有正确解决..
(我错过了或者没有正确地等待这个..)
因此 fflate 得到一个空数组:导致 Error: invalid zip data
经过一段很长的旅程才到达那里 - 我测试了很多东西
import { Blob } from "node:buffer";
才能让 Blob 创建为我工作Error: invalid zip data
.arrayBuffer()
没有解决。