这两个答案的组合,加上对请求的处理对我有用。在此示例中,您没有提供执行 POST 请求的 URL,但 Ant Design 的 Dragger 组件提供了此选项。
我只想分享我对这个问题的解决方案 + 我在使用 action 属性时发现的一个额外问题,只是为了节省您的时间。
为了测试 Dragger,我这样做了:
test("Dragger functionality", async () => {
const flushPromises = () => new Promise(setImmediate);
const file = new File(["{test: 1}"], "test.json", {type: 'application/json'})
const input = screen.getByTestId("uploader");
// I added the data-testid property to the Dragger element, with the value "uploader"
await act(async () => {
fireEvent.change(input, {target: {files: [file]}});
});
await flushPromises();
});
userEvent.upload 方法对我没有用。我一直在使用userEvent 进行所有其他测试,但在这种情况下我无法让它工作。
额外:如果你像我一样使用 Dragger
<Dragger multiple={true} accept={".json"} onChange={onChange} action={"/test"} data-testid={"uploader"}>
使用onChange 和action 属性,您可能不会调用onChange。
要使其工作,您必须处理发出的 POST 请求,在本例中为 /test。因此,完整的测试将是:
import { act, fireEvent, render, screen } from "@testing-library/react";
import { setupServer } from "msw/node";
import { rest } from "msw";
import React from "react";
import { Upload } from "antd";
const { Dragger } = Upload;
const onChangeMock = jest.fn();
const server = setupServer(rest.post("/test", (req, res, ctx) => {
return res(ctx.json({response: "200 OK"}));
}));
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
test("Dragger functionality", async () => {
const flushPromises = () => new Promise(setImmediate);
render (
<Dragger multiple={true} accept={".json"} onChange={onChangeMock} action={"/test"} data-testid={"uploader"}>
<p className="ant-upload-drag-icon">
<InboxOutlined />
</p>
<p className="ant-upload-text">{"description"}</p>
<p className="ant-upload-hint">{"hint"}</p>
</Dragger>
);
const file = new File(["{test: 1}"], "test.json", {type: 'application/json'})
const input = screen.getByTestId("uploader");
// I added the data-testid property to the Dragger element, with the value "uploader"
await act(async () => {
fireEvent.change(input, {target: {files: [file]}});
});
await flushPromises();
expect(onChangeMock).toBeCalled();
});
希望这对某人有用。