test(stores): add state machine coverage

This commit is contained in:
2026-06-25 13:28:08 +08:00
parent 0bff65dd32
commit 6081f2896a
8 changed files with 1081 additions and 2 deletions
@@ -0,0 +1,223 @@
import { describe, expect, it } from "vitest";
import { createActor, fromCallback, fromPromise, waitFor } from "xstate";
import {
ChatSendResponse,
UnlockPrivateResponse,
type UiMessage,
} from "@/data/dto/chat";
import { chatMachine } from "@/stores/chat/chat-machine";
interface LoadHistoryOutput {
messages: UiMessage[];
hasMore: boolean;
newOffset: number;
localOverwritten: boolean;
localCount: number;
networkCount: number;
}
interface LoadMoreHistoryOutput {
messages: UiMessage[];
hasMore: boolean;
newOffset: number;
}
interface SendMessageHttpOutput {
response: ChatSendResponse;
reply: UiMessage | null;
}
interface UnlockPrivateOutput {
messageId: string;
response: UnlockPrivateResponse;
}
function makeChatSendResponse(): ChatSendResponse {
return ChatSendResponse.from({
reply: "",
audioUrl: "",
messageId: "msg-1",
isGuest: false,
timestamp: Date.now(),
image: { type: null, url: null },
lockDetail: {
locked: false,
showContent: true,
showUpgrade: false,
reason: null,
hint: null,
detail: null,
},
});
}
function createTestChatMachine(
options: {
historyMessages?: UiMessage[];
unlockedContent?: string;
} = {},
) {
return chatMachine.provide({
actors: {
loadHistory: fromPromise<LoadHistoryOutput>(async () => ({
messages: options.historyMessages ?? [],
hasMore: false,
newOffset: 0,
localOverwritten: true,
localCount: 0,
networkCount: 0,
})),
loadMoreHistory: fromPromise<LoadMoreHistoryOutput, { offset: number }>(
async () => ({
messages: [],
hasMore: false,
newOffset: 0,
}),
),
sendMessageHttp: fromPromise<
SendMessageHttpOutput,
{ content: string }
>(async () => ({
response: makeChatSendResponse(),
reply: null,
})),
sendMessageWs: fromPromise<void, { content: string }>(async () => {}),
unlockPrivateMessage: fromPromise<
UnlockPrivateOutput,
{ messageId: string }
>(async ({ input }) => ({
messageId: input.messageId,
response: UnlockPrivateResponse.from({
unlocked: true,
content: options.unlockedContent ?? "unlocked",
showUpgrade: false,
paywallTriggered: false,
privateFreeLimit: 0,
privateUsedToday: 0,
reason: "ok",
}),
})),
chatWebSocket: fromCallback(({ sendBack }) => {
sendBack({
type: "ChatWebSocketConnected",
userId: "user-1",
});
return () => undefined;
}),
},
});
}
describe("chatMachine transitions", () => {
it("keeps guest logout disabled while allowing upgrade to non-VIP login", async () => {
const actor = createActor(createTestChatMachine()).start();
actor.send({ type: "ChatGuestLogin" });
await waitFor(actor, (snapshot) =>
snapshot.matches({ guestSession: "ready" }),
);
actor.send({ type: "ChatLogout" });
expect(actor.getSnapshot().matches({ guestSession: "ready" })).toBe(true);
actor.send({ type: "ChatNonVipLogin", token: "token" });
await waitFor(actor, (snapshot) =>
snapshot.matches({ nonVipUserSession: "ready" }),
);
actor.send({ type: "ChatLogout" });
expect(actor.getSnapshot().matches("idle")).toBe(true);
actor.stop();
});
it("enters VIP ready only after history and websocket are ready", async () => {
const actor = createActor(createTestChatMachine()).start();
actor.send({ type: "ChatVipLogin", token: "token" });
await waitFor(actor, (snapshot) =>
snapshot.matches({ vipUserSession: "ready" }),
);
const snapshot = actor.getSnapshot();
expect(snapshot.context.historyLoaded).toBe(true);
expect(snapshot.context.wsConnected).toBe(true);
actor.send({ type: "ChatNonVipLogin", token: "token" });
await waitFor(actor, (nextSnapshot) =>
nextSnapshot.matches({ nonVipUserSession: "ready" }),
);
expect(actor.getSnapshot().context.wsConnected).toBe(false);
actor.stop();
});
it("ignores guest login while an authenticated user session is active", async () => {
const actor = createActor(createTestChatMachine()).start();
actor.send({ type: "ChatNonVipLogin", token: "token" });
await waitFor(actor, (snapshot) =>
snapshot.matches({ nonVipUserSession: "ready" }),
);
actor.send({ type: "ChatGuestLogin" });
expect(actor.getSnapshot().matches({ nonVipUserSession: "ready" })).toBe(
true,
);
actor.send({ type: "ChatVipLogin", token: "token" });
await waitFor(actor, (snapshot) =>
snapshot.matches({ vipUserSession: "ready" }),
);
actor.send({ type: "ChatGuestLogin" });
expect(actor.getSnapshot().matches({ vipUserSession: "ready" })).toBe(true);
actor.stop();
});
it("unlocks a locked private message and clears unlocking state", async () => {
const actor = createActor(
createTestChatMachine({
historyMessages: [
{
id: "private-1",
content: "",
isFromAI: true,
date: "2026-06-25",
locked: true,
lockReason: "private_message",
isPrivate: true,
lockedPrivate: true,
privateMessageHint: "A private message is waiting.",
},
],
unlockedContent: "Here is the unlocked private message.",
}),
).start();
actor.send({ type: "ChatNonVipLogin", token: "token" });
await waitFor(actor, (snapshot) =>
snapshot.matches({ nonVipUserSession: "ready" }),
);
actor.send({ type: "ChatUnlockPrivateMessage", messageId: "private-1" });
await waitFor(
actor,
(snapshot) =>
snapshot.context.messages[0]?.content ===
"Here is the unlocked private message.",
);
const [message] = actor.getSnapshot().context.messages;
expect(message.content).toBe("Here is the unlocked private message.");
expect(message.locked).toBe(false);
expect(message.lockedPrivate).toBe(false);
expect(message.privateMessageHint).toBeNull();
expect(actor.getSnapshot().context.unlockingPrivateMessageId).toBeNull();
actor.stop();
});
});