upload-image-input.test.tsx 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import { render, screen } from "@testing-library/react";
  2. import userEvent from "@testing-library/user-event";
  3. import { afterEach, describe, expect, it, vi } from "vitest";
  4. import { UploadImageInput } from "#/components/upload-image-input";
  5. describe("UploadImageInput", () => {
  6. const user = userEvent.setup();
  7. const onUploadMock = vi.fn();
  8. afterEach(() => {
  9. vi.clearAllMocks();
  10. });
  11. it("should render an input", () => {
  12. render(<UploadImageInput onUpload={onUploadMock} />);
  13. expect(screen.getByTestId("upload-image-input")).toBeInTheDocument();
  14. });
  15. it("should call onUpload when a file is selected", async () => {
  16. render(<UploadImageInput onUpload={onUploadMock} />);
  17. const file = new File(["(⌐□_□)"], "chucknorris.png", { type: "image/png" });
  18. const input = screen.getByTestId("upload-image-input");
  19. await user.upload(input, file);
  20. expect(onUploadMock).toHaveBeenNthCalledWith(1, [file]);
  21. });
  22. it("should call onUpload when multiple files are selected", async () => {
  23. render(<UploadImageInput onUpload={onUploadMock} />);
  24. const files = [
  25. new File(["(⌐□_□)"], "chucknorris.png", { type: "image/png" }),
  26. new File(["(⌐□_□)"], "chucknorris2.png", { type: "image/png" }),
  27. ];
  28. const input = screen.getByTestId("upload-image-input");
  29. await user.upload(input, files);
  30. expect(onUploadMock).toHaveBeenNthCalledWith(1, files);
  31. });
  32. it("should not upload any file that is not an image", async () => {
  33. render(<UploadImageInput onUpload={onUploadMock} />);
  34. const file = new File(["(⌐□_□)"], "chucknorris.txt", {
  35. type: "text/plain",
  36. });
  37. const input = screen.getByTestId("upload-image-input");
  38. await user.upload(input, file);
  39. expect(onUploadMock).not.toHaveBeenCalled();
  40. });
  41. it("should render custom labels", () => {
  42. const { rerender } = render(<UploadImageInput onUpload={onUploadMock} />);
  43. expect(screen.getByTestId("default-label")).toBeInTheDocument();
  44. function CustomLabel() {
  45. return <span>Custom label</span>;
  46. }
  47. rerender(
  48. <UploadImageInput onUpload={onUploadMock} label={<CustomLabel />} />,
  49. );
  50. expect(screen.getByText("Custom label")).toBeInTheDocument();
  51. expect(screen.queryByTestId("default-label")).not.toBeInTheDocument();
  52. });
  53. });