/** * Фото профиля на десктопе можно перетащить в окно (drag & drop). * Аватар один: перетащенный файл заменяет текущее фото. */ import { render, screen, fireEvent, waitFor } from "@testing-library/react"; import ProfileModal from "./ProfileModal"; import { useIsDesktop } from "../../hooks/useIsDesktop"; import { compressImage } from "../../utils/compressImage"; import { useAuthContext } from "../../context/AuthContext"; import "../../i18n"; jest.mock("../../hooks/useIsDesktop", () => ({ useIsDesktop: jest.fn() })); jest.mock("../../hooks/useUpdateProfile", () => ({ useUpdateProfile: () => ({ updateProfile: jest.fn(), loading: false, error: null }), })); // Сжатие через canvas в jsdom не работает и тут не проверяется jest.mock("../../utils/compressImage", () => ({ compressImage: jest.fn() })); jest.mock("../../context/AuthContext", () => ({ useAuthContext: jest.fn() })); const PROFILE = { login: "ivan", firstName: "Иван", lastName: "Петров", phone: "", email: "ivan@example.com" }; // CRA сбрасывает реализации моков перед каждым тестом — задаём их здесь beforeEach(() => { compressImage.mockImplementation((file) => Promise.resolve(file)); useAuthContext.mockReturnValue({ user: { id: 1 }, updateUser: jest.fn(), logout: jest.fn() }); let n = 0; URL.createObjectURL = jest.fn(() => `blob:preview-${++n}`); URL.revokeObjectURL = jest.fn(); }); const photo = (name = "me.jpg") => new File(["x"], name, { type: "image/jpeg" }); const fileDrag = (files) => ({ dataTransfer: { files, types: ["Files"], dropEffect: "none" } }); const photoLabel = () => screen.getByText(/Фото профиля|Profile photo/); test("на десктопе перетащенное фото становится фото профиля", async () => { useIsDesktop.mockReturnValue(true); render(); fireEvent.drop(photoLabel(), fileDrag([photo()])); expect((await screen.findByAltText("profile")).getAttribute("src")).toBe("blob:preview-1"); }); test("на десктопе перетаскивание заменяет текущее фото", async () => { useIsDesktop.mockReturnValue(true); render(); fireEvent.dragEnter(photoLabel(), fileDrag([])); expect(screen.getByText(/Отпустите, чтобы заменить фото|Drop to replace the photo/)).toBeTruthy(); fireEvent.drop(photoLabel(), fileDrag([photo()])); // Старое фото сразу на экране — ждём, пока превью сменится на новое await waitFor(() => expect(screen.getByAltText("profile").getAttribute("src")).toBe("blob:preview-1")); expect(screen.getAllByAltText("profile")).toHaveLength(1); }); test("из нескольких перетащенных файлов берётся только первый", async () => { useIsDesktop.mockReturnValue(true); render(); const first = photo("first.jpg"); fireEvent.drop(photoLabel(), fileDrag([first, photo("second.jpg")])); await screen.findByAltText("profile"); expect(compressImage).toHaveBeenCalledTimes(1); expect(compressImage).toHaveBeenCalledWith(first); }); test("на мобильном перетаскивание фото выключено", () => { useIsDesktop.mockReturnValue(false); render(); fireEvent.drop(photoLabel(), fileDrag([photo()])); expect(compressImage).not.toHaveBeenCalled(); expect(screen.queryByText(/или перетащите фото сюда|or drag a photo here/)).toBeNull(); });