356 lines
13 KiB
TypeScript
356 lines
13 KiB
TypeScript
// @vitest-environment jsdom
|
|
import "@testing-library/jest-dom/vitest";
|
|
import { act, render, screen, waitFor } from "@testing-library/react";
|
|
import {
|
|
buildChatChannelDetailVM,
|
|
type ChatChannelDetailVM,
|
|
type ChatMessageCandidate,
|
|
type ChatMessageVM,
|
|
type ChatResolvedAuthorVM,
|
|
} from "@hivegrid/view-models";
|
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
|
|
import type { ChatChannelDetailPageProps } from "~/components/screens/chat/ChatChannelDetailPage";
|
|
import type { UseChatChannelRealtimeInput } from "~/modules/chat/client/useChatChannelRealtime";
|
|
|
|
const mocks = vi.hoisted(() => ({
|
|
loaderData: undefined as unknown,
|
|
fetcher: {
|
|
data: undefined as unknown,
|
|
state: "idle" as "idle" | "loading",
|
|
load: vi.fn(),
|
|
submit: vi.fn(),
|
|
},
|
|
navigate: vi.fn(),
|
|
revalidate: vi.fn(),
|
|
pageProps: undefined as ChatChannelDetailPageProps | undefined,
|
|
renders: [] as Array<{ chatId: string; draft: string; messageIds: string[] }>,
|
|
realtimeInputs: [] as Array<{ chatId: string; initialMessages: ChatMessageVM[] }>,
|
|
}));
|
|
|
|
vi.mock("react-router", () => ({
|
|
useLoaderData: () => mocks.loaderData,
|
|
useNavigate: () => mocks.navigate,
|
|
useRevalidator: () => ({ revalidate: mocks.revalidate }),
|
|
useFetcher: () => mocks.fetcher,
|
|
}));
|
|
|
|
vi.mock("react-i18next", () => ({
|
|
useTranslation: () => ({ t: (key: string) => key }),
|
|
}));
|
|
|
|
vi.mock("~/utils/data/useRootData", () => ({
|
|
useRootData: () => ({ csrf: "csrf", routing: { apiHost: "api.test", protocol: "https" } }),
|
|
}));
|
|
vi.mock("~/utils/session.server", () => ({ validateCSRFToken: vi.fn() }));
|
|
|
|
vi.mock("~/modules/chat/client/useChatChannelRealtime", () => ({
|
|
useChatChannelRealtime: (input: UseChatChannelRealtimeInput) => {
|
|
const messages = [...input.initialMessages] as ChatMessageVM[];
|
|
mocks.realtimeInputs.push({ chatId: input.chatId, initialMessages: messages });
|
|
return {
|
|
connection: { state: "online", reconnectAttempt: 0, retryAtIso: null },
|
|
messages,
|
|
messageGroups: [],
|
|
typingLabels: [],
|
|
presence: [],
|
|
sendMessage: () => null,
|
|
restoreFailedMessage: () => null,
|
|
retryMessage: () => null,
|
|
discardMessage: () => false,
|
|
updateTyping: () => undefined,
|
|
stopTyping: () => undefined,
|
|
beginMessageVisible: () => undefined,
|
|
endMessageVisible: () => undefined,
|
|
retryConnection: () => undefined,
|
|
};
|
|
},
|
|
}));
|
|
|
|
vi.mock("~/components/screens/chat/ChatChannelDetailPage", () => ({
|
|
ChatChannelDetailPage: (props: ChatChannelDetailPageProps) => {
|
|
mocks.pageProps = props;
|
|
const data = props.vm.status === "ready" ? props.vm.data : null;
|
|
const snapshot = {
|
|
chatId: data?.header.id ?? "unavailable",
|
|
draft: props.draft,
|
|
messageIds: data?.messages.map((message) => message.id) ?? [],
|
|
};
|
|
mocks.renders.push(snapshot);
|
|
return (
|
|
<div>
|
|
<output data-testid="chat-id">{snapshot.chatId}</output>
|
|
<output data-testid="draft">{snapshot.draft}</output>
|
|
<output data-testid="message-count">{snapshot.messageIds.length}</output>
|
|
<output data-testid="message-ids">{snapshot.messageIds.join(",")}</output>
|
|
</div>
|
|
);
|
|
},
|
|
}));
|
|
|
|
vi.mock("~/components/ui/errors/ServerError", () => ({ default: () => null }));
|
|
vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn() }));
|
|
vi.mock("~/modules/chat/routes/chatAccess.server", () => ({ loadChatContext: vi.fn() }));
|
|
vi.mock("~/modules/chat/services/ChatService.server", () => ({
|
|
loadMemberChatChannel: vi.fn(),
|
|
sendMemberChatMessage: vi.fn(),
|
|
}));
|
|
vi.mock("~/modules/chat/services/ChatMessageFeaturesService.server", () => ({
|
|
changeChatMessagePin: vi.fn(),
|
|
changeChatReaction: vi.fn(),
|
|
}));
|
|
vi.mock("~/modules/chat/services/ChatMessageTaskService.server", () => ({ markChatMessageAsTask: vi.fn() }));
|
|
vi.mock("~/utils/integrations/taskAccess.server", () => ({ loadTasksContext: vi.fn(), requireTasksPermission: vi.fn() }));
|
|
|
|
import ChatChannelDetailRoute from "./chat.$id";
|
|
|
|
const currentUser: ChatResolvedAuthorVM = {
|
|
userId: "user_current",
|
|
displayName: "Raffael",
|
|
avatar: { imageUrl: null, fallbackLabel: "RS" },
|
|
isCurrentUser: true,
|
|
};
|
|
|
|
describe("chat channel detail route hydration", () => {
|
|
beforeEach(() => {
|
|
vi.clearAllMocks();
|
|
vi.stubGlobal("localStorage", createMemoryStorage());
|
|
mocks.fetcher.data = undefined;
|
|
mocks.fetcher.state = "idle";
|
|
mocks.pageProps = undefined;
|
|
mocks.renders.length = 0;
|
|
mocks.realtimeInputs.length = 0;
|
|
window.history.replaceState({ idx: 0 }, "");
|
|
});
|
|
afterEach(() => vi.unstubAllGlobals());
|
|
|
|
it("remounts every channel-local state owner before rendering a different chat", async () => {
|
|
const chatA = routeData("chat_a", detailVm("chat_a", [message("chat_a_message", 1)]));
|
|
const chatB = routeData("chat_b", detailVm("chat_b", [message("chat_b_message", 2)]));
|
|
window.localStorage.setItem("chat:draft:chat_a", "Vertraulicher Entwurf aus A");
|
|
mocks.loaderData = chatA;
|
|
|
|
const view = render(<ChatChannelDetailRoute />);
|
|
await waitFor(() => expect(screen.getByTestId("draft")).toHaveTextContent("Vertraulicher Entwurf aus A"));
|
|
|
|
mocks.fetcher.data = routeData("chat_a", detailVm("chat_a", [message("chat_a_older", 0)], { hasOlder: false, olderCursor: null }));
|
|
view.rerender(<ChatChannelDetailRoute />);
|
|
await waitFor(() => expect(screen.getByTestId("message-ids")).toHaveTextContent("chat_a_older"));
|
|
|
|
mocks.loaderData = chatB;
|
|
view.rerender(<ChatChannelDetailRoute />);
|
|
|
|
await waitFor(() => expect(screen.getByTestId("chat-id")).toHaveTextContent("chat_b"));
|
|
const chatBRenders = mocks.renders.filter((entry) => entry.chatId === "chat_b");
|
|
expect(chatBRenders.length).toBeGreaterThan(0);
|
|
expect(chatBRenders.every((entry) => entry.draft !== "Vertraulicher Entwurf aus A")).toBe(true);
|
|
expect(chatBRenders.every((entry) => entry.messageIds.every((id) => id.startsWith("chat_b_")))).toBe(true);
|
|
});
|
|
|
|
it("retains the page seam when a live revalidation shifts the newest fifty-message window", async () => {
|
|
const initialNewest = messageRange(51, 100);
|
|
mocks.loaderData = routeData("chat_long", detailVm("chat_long", initialNewest, { hasOlder: true, olderCursor: "before_51" }));
|
|
const view = render(<ChatChannelDetailRoute />);
|
|
|
|
mocks.fetcher.data = routeData("chat_long", detailVm("chat_long", messageRange(1, 50), { hasOlder: false, olderCursor: null }));
|
|
view.rerender(<ChatChannelDetailRoute />);
|
|
await waitFor(() => expect(screen.getByTestId("message-count")).toHaveTextContent("100"));
|
|
|
|
mocks.fetcher.data = undefined;
|
|
mocks.loaderData = routeData("chat_long", detailVm("chat_long", messageRange(52, 101), { hasOlder: true, olderCursor: "before_52" }), "stream:101");
|
|
view.rerender(<ChatChannelDetailRoute />);
|
|
|
|
await waitFor(() => expect(screen.getByTestId("message-count")).toHaveTextContent("101"));
|
|
const ids = mocks.pageProps?.vm.status === "ready" ? mocks.pageProps.vm.data.messages.map((entry) => entry.id) : [];
|
|
expect(ids).toHaveLength(101);
|
|
expect(ids).toContain("message_051");
|
|
expect(ids[0]).toBe("message_001");
|
|
expect(ids.at(-1)).toBe("message_101");
|
|
});
|
|
|
|
it("uses browser history for back navigation and falls back to the chat index", () => {
|
|
mocks.loaderData = routeData("chat_a", detailVm("chat_a", []));
|
|
window.history.replaceState({ idx: 2 }, "");
|
|
const view = render(<ChatChannelDetailRoute />);
|
|
|
|
mocks.pageProps?.actions.onBack();
|
|
expect(mocks.navigate).toHaveBeenLastCalledWith(-1);
|
|
|
|
mocks.navigate.mockClear();
|
|
window.history.replaceState({ idx: 0 }, "");
|
|
view.rerender(<ChatChannelDetailRoute />);
|
|
mocks.pageProps?.actions.onBack();
|
|
expect(mocks.navigate).toHaveBeenLastCalledWith("/demo/chat");
|
|
});
|
|
|
|
it("shows reaction changes immediately, rolls them back on failure, and retries with the same request id", async () => {
|
|
const candidate = message("message_feature", 1);
|
|
candidate.actions = { ...candidate.actions, canReact: true, canPin: true };
|
|
mocks.loaderData = routeData("chat_a", detailVm("chat_a", [candidate]));
|
|
const view = render(<ChatChannelDetailRoute />);
|
|
|
|
act(() => mocks.pageProps?.actions.onToggleReaction?.("message_feature", "👍", true));
|
|
await waitFor(() => {
|
|
const data = mocks.pageProps?.vm.status === "ready" ? mocks.pageProps.vm.data : null;
|
|
expect(data?.messages[0]?.reactions).toEqual([
|
|
{ emoji: "👍", count: 1, reactedByViewer: true, reactorLabels: ["Raffael"] },
|
|
]);
|
|
});
|
|
const firstFormData = mocks.fetcher.submit.mock.calls[0]?.[0] as FormData;
|
|
const requestId = firstFormData.get("requestId")?.toString() ?? "";
|
|
expect(requestId).not.toBe("");
|
|
|
|
mocks.fetcher.data = { ok: false, requestId, errorKey: "chat.errors.invalidInput" };
|
|
view.rerender(<ChatChannelDetailRoute />);
|
|
await waitFor(() => {
|
|
const data = mocks.pageProps?.vm.status === "ready" ? mocks.pageProps.vm.data : null;
|
|
expect(data?.messages[0]?.reactions).toEqual([]);
|
|
expect(mocks.pageProps?.featureErrorKeys).toEqual({ message_feature: "chat.errors.invalidInput" });
|
|
});
|
|
|
|
act(() => mocks.pageProps?.actions.onRetryFeature?.("message_feature"));
|
|
await waitFor(() => expect(mocks.fetcher.submit).toHaveBeenCalledTimes(2));
|
|
const retryFormData = mocks.fetcher.submit.mock.calls[1]?.[0] as FormData;
|
|
expect(retryFormData.get("requestId")).toBe(requestId);
|
|
});
|
|
|
|
it("debounces member-scoped mention suggestions by 200 ms", async () => {
|
|
vi.useFakeTimers();
|
|
try {
|
|
const baseVm = detailVm("chat_a", []);
|
|
const mentionVm: ChatChannelDetailVM =
|
|
baseVm.status === "ready"
|
|
? { ...baseVm, data: { ...baseVm.data, composer: { ...baseVm.data.composer, canMention: true } } }
|
|
: baseVm;
|
|
mocks.loaderData = routeData("chat_a", mentionVm);
|
|
render(<ChatChannelDetailRoute />);
|
|
|
|
act(() => mocks.pageProps?.actions.onDraftChange("@Ada", "chat:draft:chat_a", 4));
|
|
await act(async () => undefined);
|
|
act(() => vi.advanceTimersByTime(199));
|
|
expect(mocks.fetcher.load).not.toHaveBeenCalled();
|
|
|
|
act(() => vi.advanceTimersByTime(1));
|
|
expect(mocks.fetcher.load).toHaveBeenCalledWith("/demo/chat/chat_a/mentions?q=Ada");
|
|
} finally {
|
|
vi.useRealTimers();
|
|
}
|
|
});
|
|
|
|
});
|
|
|
|
function routeData(chatId: string, vm: ChatChannelDetailVM, eventCursor = "stream:100") {
|
|
return {
|
|
title: `${chatId} | HiveGrid`,
|
|
tenantSlug: "demo",
|
|
currentUserId: currentUser.userId,
|
|
chatId,
|
|
vm,
|
|
eventCursor,
|
|
authors: [currentUser],
|
|
};
|
|
}
|
|
|
|
function detailVm(
|
|
chatId: string,
|
|
messages: readonly ChatMessageCandidate[],
|
|
history: { readonly hasOlder: boolean; readonly olderCursor: string | null } = { hasOlder: false, olderCursor: null }
|
|
): ChatChannelDetailVM {
|
|
return buildChatChannelDetailVM({
|
|
header: {
|
|
id: chatId,
|
|
kind: "group",
|
|
title: chatId,
|
|
subtitle: null,
|
|
avatar: { imageUrl: null, fallbackLabel: "C" },
|
|
project: null,
|
|
memberCount: 2,
|
|
isPrivate: true,
|
|
isArchived: false,
|
|
isAuditMode: false,
|
|
canManage: false,
|
|
settingsHref: null,
|
|
pinnedHref: null,
|
|
searchHref: null,
|
|
},
|
|
messages,
|
|
pinnedMessages: [],
|
|
typingLabels: [],
|
|
history,
|
|
composer: {
|
|
disabledReasonKey: null,
|
|
canSend: true,
|
|
canAttachFiles: false,
|
|
canRecordVoice: false,
|
|
canMention: false,
|
|
canMarkAsTask: false,
|
|
draftStorageKey: `chat:draft:${chatId}`,
|
|
maxBodyLength: 4_000,
|
|
},
|
|
connection: { state: "online", reconnectAttempt: 0, retryAtIso: null },
|
|
});
|
|
}
|
|
|
|
function messageRange(first: number, last: number): ChatMessageCandidate[] {
|
|
return Array.from({ length: last - first + 1 }, (_, offset) => message(`message_${String(first + offset).padStart(3, "0")}`, first + offset));
|
|
}
|
|
|
|
function message(id: string, order: number): ChatMessageCandidate {
|
|
const timestamp = new Date(Date.UTC(2026, 0, 1, 0, order)).toISOString();
|
|
return {
|
|
id,
|
|
clientMessageId: `client_${id}`,
|
|
source: "persisted",
|
|
deliveryState: "sent",
|
|
failureReasonKey: null,
|
|
author: currentUser,
|
|
bodyMarkdown: id,
|
|
bodyFormat: "markdown",
|
|
systemEvent: null,
|
|
createdAtIso: timestamp,
|
|
updatedAtIso: timestamp,
|
|
editedAtIso: null,
|
|
deletedAtIso: null,
|
|
parentMessageId: null,
|
|
mentions: [],
|
|
reactions: [],
|
|
thread: null,
|
|
attachments: [],
|
|
linkPreviews: [],
|
|
readAggregate: {
|
|
readCount: 0,
|
|
recipientCount: 1,
|
|
readerUserIds: [],
|
|
readerLabels: [],
|
|
labelKey: "chat.message.read.aggregate",
|
|
},
|
|
pin: null,
|
|
actions: {
|
|
canReact: false,
|
|
canReply: false,
|
|
canEdit: false,
|
|
canDelete: false,
|
|
canPin: false,
|
|
canMarkAsTask: false,
|
|
},
|
|
};
|
|
}
|
|
|
|
function createMemoryStorage(): Storage {
|
|
const values = new Map<string, string>();
|
|
return {
|
|
get length() {
|
|
return values.size;
|
|
},
|
|
clear: () => values.clear(),
|
|
getItem: (key) => values.get(key) ?? null,
|
|
key: (index) => [...values.keys()][index] ?? null,
|
|
removeItem: (key) => {
|
|
values.delete(key);
|
|
},
|
|
setItem: (key, value) => {
|
|
values.set(key, value);
|
|
},
|
|
};
|
|
}
|