Files
nahodka-front/src/components/chat/AntiFraud.test.jsx
SlimusMinus 3dd174afa5 Add verification questions, claim flow and scam warnings
- post form: up to 3 verification questions (loss and found) and a
  "how not to get scammed" note; sent as verificationQuestions JSON
- feed card: "I found it" / "It's mine" instead of "Write" for posts with
  questions; phone shows "after check" until the author approves
- chat draft shows ClaimForm; VerificationPanel lets the author approve or
  reject answers and locks the claimant's input until approval, then offers
  the author's phone
- messages: claim answers card, verification system line, fraudSignal
  warnings for the recipient; ChatSafetyNotice with new-account mark
- tests, README

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-11 01:04:55 +03:00

101 lines
4.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* Антифрод в чате: предупреждения о предоплате и кодах, ответы на контрольные
* вопросы находки, решение автора, плашка безопасности и «новый аккаунт».
*/
import { render, screen, fireEvent } from "@testing-library/react";
import i18n from "../../i18n";
import MessageBubble from "./MessageBubble";
import ClaimForm from "./ClaimForm";
import VerificationPanel from "./VerificationPanel";
import ChatSafetyNotice, { isNewAccount } from "./ChatSafetyNotice";
jest.mock("../../api/phoneApi", () => ({ revealPhone: jest.fn() }));
const t = i18n.t.bind(i18n);
beforeAll(() => i18n.changeLanguage("ru"));
beforeEach(() => localStorage.clear());
const msg = (extra) => ({ id: 1, senderId: 2, content: "Переведите 500 ₽ за доставку", createdAt: "2026-11-10T10:00:00", ...extra });
test("предупреждение о предоплате видит получатель, а не отправитель", () => {
const { rerender } = render(<MessageBubble message={msg({ fraudSignal: "PREPAYMENT" })} isMine={false} />);
expect(screen.getByRole("alert").textContent).toMatch(/предоплаты/);
rerender(<MessageBubble message={msg({ fraudSignal: "PREPAYMENT" })} isMine />);
expect(screen.queryByRole("alert")).toBeNull();
});
test("ответы на вопросы показываются карточкой вопрос — ответ", () => {
render(<MessageBubble isMine={false} message={msg({
kind: "CLAIM",
content: "Ответы на вопросы автора находки: ...",
claimAnswers: [{ question: "Что на брелке?", answer: "Сова" }],
})} />);
expect(screen.getByText("Ответы на вопросы")).toBeTruthy();
expect(screen.getByText("1. Что на брелке?")).toBeTruthy();
expect(screen.getByText("Сова")).toBeTruthy();
});
test("решение автора — служебная строка", () => {
render(<MessageBubble isMine={false} message={msg({
kind: "VERIFICATION", verificationStatus: "APPROVED", content: "Автор находки подтвердил ответы",
})} />);
expect(screen.getByRole("status").className).toContain("chat-system--approved");
});
test("форма ответов отправляется, только когда отвечены все вопросы", () => {
const onSubmit = jest.fn();
render(<ClaimForm questions={["Что на брелке?", "Цвет чехла?"]} onSubmit={onSubmit} sending={false} t={t} />);
const [first, second] = screen.getAllByPlaceholderText("Ваш ответ");
const submit = screen.getByText("Отправить ответы");
fireEvent.change(first, { target: { value: " Сова " } });
expect(submit.disabled).toBe(true);
fireEvent.change(second, { target: { value: "Синий" } });
fireEvent.click(submit);
expect(onSubmit).toHaveBeenCalledWith(["Сова", "Синий"]);
});
test("автор подтверждает или отклоняет ответы", () => {
const onDecide = jest.fn();
render(<VerificationPanel status="PENDING" isClaimant={false} onDecide={onDecide} deciding={false} t={t} />);
fireEvent.click(screen.getByText("Отклонить"));
fireEvent.click(screen.getByText("Подтвердить"));
expect(onDecide.mock.calls).toEqual([[false], [true]]);
});
test("заявитель ждёт решения, после подтверждения может открыть номер", () => {
const { rerender } = render(<VerificationPanel status="PENDING" isClaimant t={t} />);
expect(screen.getByText(/проверяет ваши ответы/)).toBeTruthy();
rerender(<VerificationPanel status="APPROVED" isClaimant postId={7} phoneVisible t={t} />);
expect(screen.getByText("Показать номер автора")).toBeTruthy();
});
test("в обычном чате панели проверки нет", () => {
const { container } = render(<VerificationPanel status={null} isClaimant={false} t={t} />);
expect(container.innerHTML).toBe("");
});
test("плашку безопасности можно скрыть в чате, отметку о новом аккаунте — нет", () => {
const recent = new Date(Date.now() - 2 * 24 * 3600 * 1000).toISOString();
render(<ChatSafetyNotice chatId={5} otherUserCreatedAt={recent} t={t} />);
fireEvent.click(screen.getByText("Скрыть"));
expect(screen.queryByText("Осторожно, мошенники")).toBeNull();
expect(screen.getByText(/Новый аккаунт/)).toBeTruthy();
});
test("новый аккаунт — моложе недели", () => {
const now = Date.parse("2026-11-10T00:00:00Z");
expect(isNewAccount("2026-11-05T00:00:00Z", now)).toBe(true);
expect(isNewAccount("2026-10-01T00:00:00Z", now)).toBe(false);
expect(isNewAccount(null, now)).toBe(false);
});