test(e2e): extract shared playwright helpers

This commit is contained in:
2026-07-01 16:31:25 +08:00
parent c477737c0d
commit 1fbdd41da8
11 changed files with 321 additions and 334 deletions
+2
View File
@@ -138,6 +138,8 @@ export async function mockCoreApis(
? insufficientCreditsUnlockVoiceResponse
: paidImageInsufficientCreditsFlow
? insufficientCreditsUnlockImageResponse
: paidImageFlow && paidImageRequested && !paidImageUnlocked
? insufficientCreditsUnlockImageResponse
: {
unlocked: true,
content: "Unlocked message",
+33 -24
View File
@@ -107,6 +107,12 @@ export function createWeeklyLimitChatSendResponse(
audioUrl: "",
messageId: "",
isGuest: true,
canSendMessage: false,
cannotSendReason: "insufficient_credits",
creditBalance: 0,
creditsCharged: 0,
requiredCredits: limit,
shortfallCredits: Math.max(0, limit - usedMessageCount),
timestamp: chatSendResponse.timestamp + usedMessageCount,
image: {
type: null,
@@ -282,37 +288,40 @@ export const insufficientCreditsUnlockImageResponse = {
export const paymentPlansResponse = {
plans: [
{
plan_id: "vip_monthly",
plan_name: "Monthly",
order_type: "vip_monthly",
amount_cents: 999,
original_amount_cents: 1999,
daily_price_cents: 33,
planId: "vip_monthly",
planName: "Monthly",
orderType: "vip_monthly",
amountCents: 999,
originalAmountCents: 1999,
dailyPriceCents: 33,
currency: "USD",
vip_days: 30,
dol_amount: null,
vipDays: 30,
dolAmount: null,
creditBalance: 300,
},
{
plan_id: "vip_quarterly",
plan_name: "Quarterly",
order_type: "vip_quarterly",
amount_cents: 2499,
original_amount_cents: 5999,
daily_price_cents: 28,
planId: "vip_quarterly",
planName: "Quarterly",
orderType: "vip_quarterly",
amountCents: 2499,
originalAmountCents: 5999,
dailyPriceCents: 28,
currency: "USD",
vip_days: 90,
dol_amount: null,
vipDays: 90,
dolAmount: null,
creditBalance: 1000,
},
{
plan_id: "dol_voice_30",
plan_name: "Voice Pack",
order_type: "dol_voice",
amount_cents: 499,
original_amount_cents: null,
daily_price_cents: null,
planId: "dol_voice_30",
planName: "Voice Pack",
orderType: "dol_voice",
amountCents: 499,
originalAmountCents: null,
dailyPriceCents: null,
currency: "USD",
vip_days: null,
dol_amount: 30,
vipDays: null,
dolAmount: 30,
creditBalance: 30,
},
],
};
+178
View File
@@ -0,0 +1,178 @@
import { expect, type BrowserContext, type Page } from "@playwright/test";
export const e2eEmailCredentials = {
email: "chanwillian0@gmail.com",
password: "12345678",
};
export async function clearBrowserState(
context: BrowserContext,
page: Page,
baseURL?: string,
) {
await context.clearCookies();
const client = await context.newCDPSession(page);
const origins = new Set([
new URL(baseURL ?? "http://127.0.0.1:3000").origin,
"http://127.0.0.1:3000",
"http://localhost:3000",
]);
for (const origin of origins) {
await client
.send("Storage.clearDataForOrigin", {
origin,
storageTypes: "all",
})
.catch(() => {});
}
}
export async function enterChatFromSplash(
page: Page,
options: {
expectedUrl?: RegExp;
timeout?: number;
waitUntil?: "commit" | "domcontentloaded" | "load" | "networkidle";
} = {},
) {
const {
expectedUrl = /\/chat$/,
timeout = 10_000,
waitUntil,
} = options;
await page.goto("/splash", { waitUntil });
const skipButton = page.getByRole("button", { name: "Skip" });
await expect(skipButton).toBeVisible({ timeout });
await expect(skipButton).toBeEnabled();
for (let attempt = 0; attempt < 3; attempt += 1) {
await skipButton.click();
try {
await expect(page).toHaveURL(expectedUrl, { timeout: 3_000 });
return;
} catch {
await page.waitForTimeout(500);
}
}
await expect(page).toHaveURL(expectedUrl, { timeout });
}
export async function dismissChatInterruptions(page: Page) {
for (const buttonName of ["Later", "Cancel", "OK"]) {
const button = page.getByRole("button", { name: buttonName }).first();
if (await button.isVisible().catch(() => false)) {
await button.click();
}
}
}
export async function switchToEmailSignIn(page: Page) {
await page.getByRole("button", { name: /Other Sign In Options/i }).click();
await expect(
page.getByRole("dialog", { name: /Other sign-in options/i }),
).toBeVisible();
await page.getByRole("button", { name: "Email Sign In" }).click();
await expect(page.getByPlaceholder("Email")).toHaveValue(
e2eEmailCredentials.email,
);
await expect(page.getByPlaceholder("Password")).toHaveValue(
e2eEmailCredentials.password,
);
}
export async function submitEmailLogin(
page: Page,
options: {
expectedUrl?: RegExp;
waitForRequest?: boolean;
urlTimeout?: number;
} = {},
) {
const {
expectedUrl,
waitForRequest = true,
urlTimeout = 10_000,
} = options;
const loginButton = page.getByRole("button", { name: "Login" });
if (!waitForRequest) {
await Promise.all([
expectedUrl
? page.waitForURL(expectedUrl, { timeout: urlTimeout })
: Promise.resolve(),
loginButton.click(),
]);
return null;
}
const loginRequestPromise = page.waitForRequest("**/api/auth/login");
await loginButton.click();
const loginRequest = await loginRequestPromise;
expect(loginRequest.postDataJSON()).toMatchObject({
email: e2eEmailCredentials.email,
password: e2eEmailCredentials.password,
isTestAccount: true,
});
if (expectedUrl) {
await expect(page).toHaveURL(expectedUrl, { timeout: urlTimeout });
}
return loginRequest;
}
export async function signInWithEmailAndOpenChat(page: Page) {
await page.goto("/auth");
await switchToEmailSignIn(page);
const historyResponsePromise = page
.waitForResponse("**/api/chat/history**", { timeout: 10_000 })
.catch(() => null);
await submitEmailLogin(page, { expectedUrl: /\/chat$/ });
await historyResponsePromise;
await dismissChatInterruptions(page);
}
export async function completeVipPayment(page: Page) {
const createOrderRequestPromise = page.waitForRequest(
"**/api/payment/create-order",
);
const orderStatusRequestPromise = page.waitForRequest(
"**/api/payment/order-status**",
);
await page.getByRole("button", { name: /Pay and Activ/i }).click();
const createOrderRequest = await createOrderRequestPromise;
expect(createOrderRequest.postDataJSON()).toMatchObject({
planId: "vip_monthly",
payChannel: "stripe",
});
await orderStatusRequestPromise;
const paymentSuccessDialog = page.getByRole("alertdialog", {
name: "Payment successful",
});
await expect(paymentSuccessDialog).toBeVisible();
await paymentSuccessDialog.getByRole("button", { name: "OK" }).click();
}
export async function expectInsufficientCreditsDialog(page: Page) {
const insufficientCreditsDialog = page.getByRole("dialog", {
name: "Not enough credits",
});
await expect(insufficientCreditsDialog).toBeVisible();
await expect(insufficientCreditsDialog.getByText("Balance")).toBeVisible();
await expect(insufficientCreditsDialog.getByText("Required")).toBeVisible();
await expect(
insufficientCreditsDialog.getByText("Still needed"),
).toBeVisible();
return insufficientCreditsDialog;
}