react-testing-library – how to simulate file upload to a element?

I found a bit hacky solution and I’m not sure if it match the best practises in testing but I will share it with you it might help

describe("Upload files", () => {
  let file;

  beforeEach(() => {
    file = new File(["(⌐□_□)"], "chucknorris.png", { type: "image/png" });
  });

  test("cover photo upload", async () => {
    // render the component
    const { getByTestId } = render(<YourComponent />);

    // get the upload button
    let uploader = getByTestId("photo-uploader");

    // simulate ulpoad event and wait until finish
    await waitFor(() =>
      fireEvent.change(uploader, {
        target: { files: [file] },
      })
    );
    // get the same uploader from the dom
    let image = document.getElementById("photo-uploader");
    // check if the file is there
    expect(image.files[0].name).toBe("chucknorris.png");
    expect(image.files.length).toBe(1);
  });
});

Leave a Comment

tech