test(e2e): cover chat send token refresh retry

This commit is contained in:
2026-07-02 12:53:42 +08:00
parent 51987882eb
commit d8a28bb438
8 changed files with 153 additions and 12 deletions
+25 -1
View File
@@ -18,12 +18,15 @@ import {
paidVoiceHistoryResponse, paidVoiceHistoryResponse,
paidPaymentOrderStatusResponse, paidPaymentOrderStatusResponse,
paymentPlansResponse, paymentPlansResponse,
refreshedEmailLoginResponse,
refreshedGuestLoginResponse,
userEntitlementsResponse, userEntitlementsResponse,
vipStatusResponse, vipStatusResponse,
} from "./test-data"; } from "./test-data";
interface MockCoreApisOptions { interface MockCoreApisOptions {
chatLimitTriggerAt?: number; chatLimitTriggerAt?: number;
chatSendTokenRefreshFlow?: boolean;
paidImageFlow?: boolean; paidImageFlow?: boolean;
paidImageInsufficientCreditsFlow?: boolean; paidImageInsufficientCreditsFlow?: boolean;
paidVoiceInsufficientCreditsFlow?: boolean; paidVoiceInsufficientCreditsFlow?: boolean;
@@ -35,16 +38,22 @@ export async function mockCoreApis(
): Promise<void> { ): Promise<void> {
const { const {
chatLimitTriggerAt, chatLimitTriggerAt,
chatSendTokenRefreshFlow = false,
paidImageFlow = false, paidImageFlow = false,
paidImageInsufficientCreditsFlow = false, paidImageInsufficientCreditsFlow = false,
paidVoiceInsufficientCreditsFlow = false, paidVoiceInsufficientCreditsFlow = false,
} = options; } = options;
let sendCount = 0; let sendCount = 0;
let hasExpiredChatSend = false;
let paidImageRequested = false; let paidImageRequested = false;
let paidImageUnlocked = false; let paidImageUnlocked = false;
await page.route("**/api/auth/guest", async (route) => { await page.route("**/api/auth/guest", async (route) => {
await route.fulfill({ json: apiEnvelope(guestLoginResponse) }); const response =
chatSendTokenRefreshFlow && hasExpiredChatSend
? refreshedGuestLoginResponse
: guestLoginResponse;
await route.fulfill({ json: apiEnvelope(response) });
}); });
await page.route("**/api/auth/login", async (route) => { await page.route("**/api/auth/login", async (route) => {
@@ -55,6 +64,10 @@ export async function mockCoreApis(
await route.fulfill({ json: apiEnvelope(emailLoginResponse) }); await route.fulfill({ json: apiEnvelope(emailLoginResponse) });
}); });
await page.route("**/api/auth/refresh", async (route) => {
await route.fulfill({ json: apiEnvelope(refreshedEmailLoginResponse) });
});
await page.route("**/api/auth/logout", async (route) => { await page.route("**/api/auth/logout", async (route) => {
await route.fulfill({ json: apiEnvelope(null) }); await route.fulfill({ json: apiEnvelope(null) });
}); });
@@ -88,6 +101,17 @@ export async function mockCoreApis(
const message = const message =
typeof requestBody?.message === "string" ? requestBody.message : ""; typeof requestBody?.message === "string" ? requestBody.message : "";
if (chatSendTokenRefreshFlow && !hasExpiredChatSend) {
hasExpiredChatSend = true;
await route.fulfill({
status: 401,
json: {
message: "expired",
},
});
return;
}
const response = const response =
paidImageFlow && message.includes("给我发图片") paidImageFlow && message.includes("给我发图片")
? paidImageChatSendResponse ? paidImageChatSendResponse
+10
View File
@@ -43,12 +43,22 @@ export const guestLoginResponse = {
user: e2eUser, user: e2eUser,
}; };
export const refreshedGuestLoginResponse = {
...guestLoginResponse,
token: "e2e-refreshed-guest-token",
};
export const emailLoginResponse = { export const emailLoginResponse = {
token: "e2e-email-token", token: "e2e-email-token",
refreshToken: "e2e-email-refresh-token", refreshToken: "e2e-email-refresh-token",
user: e2eEmailUser, user: e2eEmailUser,
}; };
export const refreshedEmailLoginResponse = {
token: "e2e-refreshed-email-token",
refreshToken: "e2e-refreshed-email-refresh-token",
};
export const userEntitlementsResponse = { export const userEntitlementsResponse = {
userId: e2eEmailUser.id, userId: e2eEmailUser.id,
isGuest: false, isGuest: false,
+44 -4
View File
@@ -72,10 +72,32 @@ export async function dismissChatInterruptions(page: Page) {
} }
export async function switchToEmailSignIn(page: Page) { export async function switchToEmailSignIn(page: Page) {
await page.getByRole("button", { name: /Other Sign In Options/i }).click(); const otherOptionsButton = page.getByRole("button", {
await expect( name: /Other Sign In Options/i,
page.getByRole("dialog", { name: /Other sign-in options/i }), });
).toBeVisible(); const otherOptionsDialog = page.getByRole("dialog", {
name: /Other sign-in options/i,
});
await expect(otherOptionsButton).toBeVisible({ timeout: 10_000 });
await expect(otherOptionsButton).toBeEnabled();
for (let attempt = 0; attempt < 3; attempt += 1) {
await otherOptionsButton.click();
try {
await expect(otherOptionsDialog).toBeVisible({ timeout: 2_000 });
break;
} catch (error) {
if (attempt === 2) throw error;
await otherOptionsButton.evaluate((button) =>
(button as HTMLButtonElement).click(),
);
if (await otherOptionsDialog.isVisible().catch(() => false)) {
break;
}
await page.waitForTimeout(500);
}
}
await page.getByRole("button", { name: "Email Sign In" }).click(); await page.getByRole("button", { name: "Email Sign In" }).click();
await expect(page.getByPlaceholder("Email")).toHaveValue( await expect(page.getByPlaceholder("Email")).toHaveValue(
@@ -176,3 +198,21 @@ export async function expectInsufficientCreditsDialog(page: Page) {
return insufficientCreditsDialog; return insufficientCreditsDialog;
} }
export async function expectVipChatSubscriptionUrl(page: Page) {
await expect(page).toHaveURL(/\/subscription\?/);
const url = new URL(page.url());
expect(url.pathname).toBe("/subscription");
expect(url.searchParams.get("type")).toBe("vip");
expect(url.searchParams.get("returnTo")).toBe("chat");
}
export function expectAuthRedirectToVipChatSubscription(page: Page) {
const redirect = new URL(page.url()).searchParams.get("redirect");
expect(redirect).not.toBeNull();
const redirectUrl = new URL(redirect ?? "", "http://e2e.local");
expect(redirectUrl.pathname).toBe("/subscription");
expect(redirectUrl.searchParams.get("type")).toBe("vip");
expect(redirectUrl.searchParams.get("returnTo")).toBe("chat");
}
+4 -4
View File
@@ -6,6 +6,8 @@ import {
completeVipPayment, completeVipPayment,
dismissChatInterruptions, dismissChatInterruptions,
enterChatFromSplash, enterChatFromSplash,
expectAuthRedirectToVipChatSubscription,
expectVipChatSubscriptionUrl,
submitEmailLogin, submitEmailLogin,
switchToEmailSignIn, switchToEmailSignIn,
} from "../../fixtures/test-helpers"; } from "../../fixtures/test-helpers";
@@ -88,13 +90,11 @@ test("guest hits the chat quantity limit and can continue to login and subscript
await topUpButton.click(); await topUpButton.click();
await expect(page).toHaveURL(/\/auth\?redirect=/); await expect(page).toHaveURL(/\/auth\?redirect=/);
expect(new URL(page.url()).searchParams.get("redirect")).toBe( expectAuthRedirectToVipChatSubscription(page);
"/subscription?type=vip&returnTo=chat",
);
await switchToEmailSignIn(page); await switchToEmailSignIn(page);
await submitEmailLogin(page); await submitEmailLogin(page);
await expect(page).toHaveURL(/\/subscription\?type=vip&returnTo=chat$/); await expectVipChatSubscriptionUrl(page);
await completeVipPayment(page); await completeVipPayment(page);
@@ -0,0 +1,64 @@
import { expect, test, type Request } from "@playwright/test";
import { mockCoreApis } from "../../fixtures/api-mocks";
import {
clearBrowserState,
signInWithEmailAndOpenChat,
} from "../../fixtures/test-helpers";
test.beforeEach(async ({ baseURL, context, page }) => {
await clearBrowserState(context, page, baseURL);
await mockCoreApis(page, {
chatSendTokenRefreshFlow: true,
});
});
test("chat send refreshes an expired token, retries the request, and renders the reply", async ({
page,
}) => {
const chatSendRequests: Request[] = [];
page.on("request", (request) => {
if (new URL(request.url()).pathname === "/api/chat/send") {
chatSendRequests.push(request);
}
});
await signInWithEmailAndOpenChat(page);
const message = "token refresh retry test";
const messageInput = page.getByRole("textbox", { name: "Message" });
await expect(messageInput).toBeVisible({ timeout: 10_000 });
await expect(messageInput).toBeEnabled();
await messageInput.fill(message);
const refreshRequestPromise = page.waitForRequest("**/api/auth/refresh");
const retriedSendResponsePromise = page.waitForResponse(
(response) =>
new URL(response.url()).pathname === "/api/chat/send" &&
response.status() === 200,
);
await messageInput.press("Enter");
const refreshRequest = await refreshRequestPromise;
expect(refreshRequest.method()).toBe("POST");
expect(refreshRequest.headers().authorization).toBeUndefined();
expect(refreshRequest.postDataJSON()).toMatchObject({
refreshToken: "e2e-email-refresh-token",
});
await retriedSendResponsePromise;
await expect.poll(() => chatSendRequests.length).toBe(2);
expect(chatSendRequests[0]?.postDataJSON()).toMatchObject({ message });
expect(chatSendRequests[0]?.headers().authorization).toBe(
"Bearer e2e-email-token",
);
expect(chatSendRequests[1]?.postDataJSON()).toMatchObject({ message });
expect(chatSendRequests[1]?.headers().authorization).toBe(
"Bearer e2e-refreshed-email-token",
);
await expect(page.getByText(message)).toBeVisible();
await expect(page.getByText("Hello from the E2E boyfriend.")).toBeVisible();
});
@@ -6,6 +6,7 @@ import {
clearBrowserState, clearBrowserState,
dismissChatInterruptions, dismissChatInterruptions,
expectInsufficientCreditsDialog, expectInsufficientCreditsDialog,
expectVipChatSubscriptionUrl,
signInWithEmailAndOpenChat, signInWithEmailAndOpenChat,
} from "../../fixtures/test-helpers"; } from "../../fixtures/test-helpers";
@@ -53,5 +54,5 @@ test("user sees insufficient credits when unlocking a paid image from fullscreen
.getByRole("button", { name: "Top up now" }) .getByRole("button", { name: "Top up now" })
.click(); .click();
await expect(page).toHaveURL(/\/subscription\?type=vip&returnTo=chat$/); await expectVipChatSubscriptionUrl(page);
}); });
+2 -1
View File
@@ -8,6 +8,7 @@ import {
dismissChatInterruptions, dismissChatInterruptions,
enterChatFromSplash, enterChatFromSplash,
expectInsufficientCreditsDialog, expectInsufficientCreditsDialog,
expectVipChatSubscriptionUrl,
submitEmailLogin, submitEmailLogin,
switchToEmailSignIn, switchToEmailSignIn,
} from "../../fixtures/test-helpers"; } from "../../fixtures/test-helpers";
@@ -77,7 +78,7 @@ test("guest can unlock a paid image after email login and subscription payment",
.getByRole("button", { name: "Top up now" }) .getByRole("button", { name: "Top up now" })
.click(); .click();
await expect(page).toHaveURL(/\/subscription\?type=vip&returnTo=chat$/); await expectVipChatSubscriptionUrl(page);
await completeVipPayment(page); await completeVipPayment(page);
await expect(page).toHaveURL(new RegExp(`/chat/image/${paidImageMessageId}$`)); await expect(page).toHaveURL(new RegExp(`/chat/image/${paidImageMessageId}$`));
@@ -5,6 +5,7 @@ import { paidVoiceMessageId } from "../../fixtures/test-data";
import { import {
clearBrowserState, clearBrowserState,
expectInsufficientCreditsDialog, expectInsufficientCreditsDialog,
expectVipChatSubscriptionUrl,
signInWithEmailAndOpenChat, signInWithEmailAndOpenChat,
} from "../../fixtures/test-helpers"; } from "../../fixtures/test-helpers";
@@ -44,5 +45,5 @@ test("user sees insufficient credits when unlocking a paid voice message and can
.getByRole("button", { name: "Top up now" }) .getByRole("button", { name: "Top up now" })
.click(); .click();
await expect(page).toHaveURL(/\/subscription\?type=vip&returnTo=chat$/); await expectVipChatSubscriptionUrl(page);
}); });