204 lines
9.0 KiB
JavaScript
204 lines
9.0 KiB
JavaScript
/**
|
||
* На десктопе форма объявления закрывается только крестиком: клик по фону
|
||
* не должен терять заполненные поля. На мобильном клик по фону закрывает.
|
||
* Там же на десктопе фото можно перетащить в форму (drag & drop).
|
||
* Номер — только с согласием на показ (по умолчанию «только чат»);
|
||
* после согласия он подставляется из профиля, если в объявлении его нет.
|
||
*/
|
||
import { render, screen, fireEvent } from "@testing-library/react";
|
||
import CreateUpdatePost from "./CreateUpdatePost";
|
||
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/usePostMutation", () => ({
|
||
usePostMutation: () => ({ save: jest.fn(), loading: false, error: null }),
|
||
}));
|
||
// Сжатие через canvas в jsdom не работает и тут не проверяется
|
||
jest.mock("../utils/compressImage", () => ({ compressImage: jest.fn() }));
|
||
jest.mock("../context/AuthContext", () => ({ useAuthContext: jest.fn() }));
|
||
|
||
// CRA сбрасывает реализации моков перед каждым тестом — задаём их здесь
|
||
beforeEach(() => {
|
||
compressImage.mockImplementation((file) => Promise.resolve(file));
|
||
useAuthContext.mockReturnValue({ user: null });
|
||
URL.createObjectURL = jest.fn(() => "blob:preview");
|
||
URL.revokeObjectURL = jest.fn();
|
||
});
|
||
|
||
const ADD_PHOTO = /Добавить фото|Add photo/;
|
||
|
||
function fileDrag(files) {
|
||
return { dataTransfer: { files, types: ["Files"], dropEffect: "none" } };
|
||
}
|
||
|
||
function renderForm() {
|
||
const onClose = jest.fn();
|
||
const { container } = render(<CreateUpdatePost onClose={onClose} />);
|
||
// У фона и крестика нет роли/подписи — ищем по классу, как их видит пользователь
|
||
// eslint-disable-next-line testing-library/no-container, testing-library/no-node-access
|
||
return { onClose, backdrop: container.querySelector(".f-modal-bg") };
|
||
}
|
||
|
||
test("на десктопе клик по фону не закрывает форму", () => {
|
||
useIsDesktop.mockReturnValue(true);
|
||
const { onClose, backdrop } = renderForm();
|
||
|
||
fireEvent.click(backdrop);
|
||
|
||
expect(onClose).not.toHaveBeenCalled();
|
||
});
|
||
|
||
test("на десктопе форма закрывается крестиком", () => {
|
||
useIsDesktop.mockReturnValue(true);
|
||
const { onClose, backdrop } = renderForm();
|
||
|
||
// eslint-disable-next-line testing-library/no-node-access
|
||
fireEvent.click(backdrop.querySelector(".f-close-btn"));
|
||
|
||
expect(onClose).toHaveBeenCalledTimes(1);
|
||
});
|
||
|
||
test("на мобильном клик по фону закрывает форму", () => {
|
||
useIsDesktop.mockReturnValue(false);
|
||
const { onClose, backdrop } = renderForm();
|
||
|
||
fireEvent.click(backdrop);
|
||
|
||
expect(onClose).toHaveBeenCalledTimes(1);
|
||
});
|
||
|
||
test("клик внутри окна не закрывает форму", () => {
|
||
useIsDesktop.mockReturnValue(false);
|
||
const { onClose } = renderForm();
|
||
|
||
fireEvent.click(screen.getByText(/Новое объявление|New ad/));
|
||
|
||
expect(onClose).not.toHaveBeenCalled();
|
||
});
|
||
|
||
test("на десктопе перетащенное фото добавляется в форму", async () => {
|
||
useIsDesktop.mockReturnValue(true);
|
||
renderForm();
|
||
const photo = new File(["x"], "cat.jpg", { type: "image/jpeg" });
|
||
|
||
fireEvent.drop(screen.getByText(ADD_PHOTO), fileDrag([photo]));
|
||
|
||
// После добавления первого фото кнопка становится «Добавить ещё»
|
||
expect(await screen.findByText(/Добавить ещё|Add more/)).toBeTruthy();
|
||
expect(compressImage).toHaveBeenCalledWith(photo);
|
||
});
|
||
|
||
test("на десктопе файл над зоной подсвечивает её подсказкой", () => {
|
||
useIsDesktop.mockReturnValue(true);
|
||
renderForm();
|
||
|
||
fireEvent.dragEnter(screen.getByText(ADD_PHOTO), fileDrag([]));
|
||
|
||
expect(screen.getByText(/Отпустите, чтобы добавить фото|Drop to add photos/)).toBeTruthy();
|
||
});
|
||
|
||
test("перетащенный файл неподходящего типа не добавляется", async () => {
|
||
useIsDesktop.mockReturnValue(true);
|
||
renderForm();
|
||
const gif = new File(["x"], "anim.gif", { type: "image/gif" });
|
||
|
||
fireEvent.drop(screen.getByText(ADD_PHOTO), fileDrag([gif]));
|
||
|
||
expect(await screen.findByText(/Только изображения|Images only/)).toBeTruthy();
|
||
expect(compressImage).not.toHaveBeenCalled();
|
||
});
|
||
|
||
test("на мобильном перетаскивание фото выключено", () => {
|
||
useIsDesktop.mockReturnValue(false);
|
||
renderForm();
|
||
const photo = new File(["x"], "cat.jpg", { type: "image/jpeg" });
|
||
|
||
fireEvent.drop(screen.getByText(ADD_PHOTO), fileDrag([photo]));
|
||
|
||
expect(compressImage).not.toHaveBeenCalled();
|
||
expect(screen.queryByText(/или перетащите фото сюда|or drag photos here/)).toBeNull();
|
||
});
|
||
|
||
const PROFILE_PHONE = "+7 (999) 111-22-33";
|
||
const PHONE_PLACEHOLDER = "+7 (___) ___-__-__";
|
||
const CONSENT = /Показывать мой номер|Show my phone number/;
|
||
|
||
/** Рендерит форму и переходит на второй шаг, где находятся согласие и «Телефон». */
|
||
function openPhoneStep(props = {}) {
|
||
useIsDesktop.mockReturnValue(true);
|
||
render(<CreateUpdatePost onClose={jest.fn()} {...props} />);
|
||
if (!props.initialData) {
|
||
fireEvent.change(screen.getByPlaceholderText(/Кошелёк|wallet/i), { target: { value: "Ключи" } });
|
||
fireEvent.change(screen.getByPlaceholderText(/опишите|describe/i), { target: { value: "Связка ключей" } });
|
||
}
|
||
fireEvent.click(screen.getByText(/^(Далее|Next)/));
|
||
}
|
||
|
||
const phoneField = () => screen.queryByPlaceholderText(PHONE_PLACEHOLDER);
|
||
|
||
test("новое объявление: по умолчанию «только чат» — номер не запрашивается", () => {
|
||
useAuthContext.mockReturnValue({ user: { phone: "79991112233" } });
|
||
openPhoneStep();
|
||
|
||
expect(screen.getByLabelText(CONSENT).checked).toBe(false);
|
||
expect(phoneField()).toBeNull();
|
||
expect(screen.getByText(/номер телефона не публикуется|phone number is not published/)).toBeTruthy();
|
||
});
|
||
|
||
test("новое объявление: после согласия телефон подставляется из профиля", () => {
|
||
useAuthContext.mockReturnValue({ user: { phone: "79991112233" } });
|
||
openPhoneStep();
|
||
|
||
fireEvent.click(screen.getByLabelText(CONSENT));
|
||
|
||
expect(phoneField().value).toBe(PROFILE_PHONE);
|
||
});
|
||
|
||
test("согласие без номера не даёт опубликовать", () => {
|
||
useAuthContext.mockReturnValue({ user: { phone: "" } });
|
||
openPhoneStep();
|
||
|
||
fireEvent.click(screen.getByLabelText(CONSENT));
|
||
fireEvent.click(screen.getByText(/Разместить объявление|Publish/));
|
||
|
||
expect(phoneField().value).toBe("");
|
||
expect(screen.getByText(/Введите номер телефона|Enter a phone number/)).toBeTruthy();
|
||
});
|
||
|
||
const POST = { id: 1, type: "LOSS", title: "Ключи", description: "Связка ключей", category: "KEYS" };
|
||
|
||
test("редактирование: телефон объявления не заменяется телефоном профиля", () => {
|
||
useAuthContext.mockReturnValue({ user: { phone: PROFILE_PHONE } });
|
||
openPhoneStep({ initialData: { ...POST, phoneVisible: true, phone: "+7 (900) 000-00-00" } });
|
||
|
||
expect(screen.getByLabelText(CONSENT).checked).toBe(true);
|
||
expect(phoneField().value).toBe("+7 (900) 000-00-00");
|
||
});
|
||
|
||
test("редактирование объявления «только чат»: согласие не включается само", () => {
|
||
useAuthContext.mockReturnValue({ user: { phone: PROFILE_PHONE } });
|
||
openPhoneStep({ initialData: { ...POST, phoneVisible: false, phone: null } });
|
||
|
||
expect(screen.getByLabelText(CONSENT).checked).toBe(false);
|
||
expect(phoneField()).toBeNull();
|
||
});
|
||
|
||
test("админ не может включить показ номера за автора", () => {
|
||
useAuthContext.mockReturnValue({ user: { phone: PROFILE_PHONE } });
|
||
openPhoneStep({ initialData: { ...POST, phoneVisible: false, phone: null }, adminMode: true });
|
||
|
||
expect(screen.queryByLabelText(CONSENT)).toBeNull();
|
||
expect(phoneField()).toBeNull();
|
||
});
|
||
|
||
test("админ правит номер объявления с согласием: свой телефон не подставляется", () => {
|
||
useAuthContext.mockReturnValue({ user: { phone: PROFILE_PHONE } });
|
||
openPhoneStep({ initialData: { ...POST, phoneVisible: true, phone: "" }, adminMode: true });
|
||
|
||
expect(screen.queryByLabelText(CONSENT)).toBeNull();
|
||
expect(phoneField().value).toBe("");
|
||
});
|