The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Billing test improvements (#3932)
Pedro Ladeiraed52027f5e49
diff --git a/apps/web/playwright/workspaces/billing-mocks.ts b/apps/web/playwright/workspaces/billing-mocks.tsindex 0458125237..9954cdec12 100644--- a/apps/web/playwright/workspaces/billing-mocks.ts+++ b/apps/web/playwright/workspaces/billing-mocks.ts@@ -3,12 +3,25 @@ import "dotenv-flow/config";import { prisma } from "@dub/prisma";import type { Prisma } from "@dub/prisma/client";import {- BUSINESS_PLAN,DUB_TRIAL_PERIOD_DAYS,getWorkspaceLimitsForStripeSubscriptionStatus,+ PLANS,} from "@dub/utils";import type { Page, Request } from "@playwright/test";+function getTrialingLimitsForPlan(planId: string) {+ const planDetails = PLANS.find(+ (p) => p.name.toLowerCase() === planId.toLowerCase(),+ );+ if (!planDetails) {+ throw new Error(`applyMockTrialToWorkspace: unknown plan "${planId}"`);+ }+ return getWorkspaceLimitsForStripeSubscriptionStatus({+ planLimits: planDetails.limits,+ subscriptionStatus: "trialing",+ });+}+const MOCK_CHECKOUT_SESSION_ID = "cs_test_e2e_mock_session";/** Synthetic path used in the browser before Hosted Checkout is mocked (see redirectToCheckout stub). */@@ -74,9 +87,11 @@ const mockTrialWorkspaceColumns = {domainsLimit: true,aiLimit: true,tagsLimit: true,+ partnerTagsLimit: true,foldersLimit: true,groupsLimit: true,networkInvitesLimit: true,+ partnersLimit: true,usersLimit: true,paymentFailedAt: true,} as const;@@ -115,23 +130,25 @@ export async function restoreWorkspaceBillingTrialSnapshot(domainsLimit: snapshot.domainsLimit,aiLimit: snapshot.aiLimit,tagsLimit: snapshot.tagsLimit,+ partnerTagsLimit: snapshot.partnerTagsLimit,foldersLimit: snapshot.foldersLimit,groupsLimit: snapshot.groupsLimit,networkInvitesLimit: snapshot.networkInvitesLimit,+ partnersLimit: snapshot.partnersLimit,usersLimit: snapshot.usersLimit,paymentFailedAt: snapshot.paymentFailedAt,},});}-/**- * Writes trialing Business state directly to the DB (mock path — no Stripe API or webhooks).- */-export async function applyMockTrialToWorkspace(slug: string) {- const limits = getWorkspaceLimitsForStripeSubscriptionStatus({- planLimits: BUSINESS_PLAN.limits,- subscriptionStatus: "trialing",- });+/** Writes trialing state to the DB (mock path — no Stripe). Defaults to business. */+export async function applyMockTrialToWorkspace(+ slug: string,+ options?: { plan?: string; period?: "monthly" | "yearly" },+) {+ const plan = (options?.plan ?? "business").toLowerCase();+ const period = options?.period ?? "monthly";+ const limits = getTrialingLimitsForPlan(plan);const trialEndsAt = new Date();trialEndsAt.setDate(trialEndsAt.getDate() + DUB_TRIAL_PERIOD_DAYS);@@ -139,11 +156,11 @@ export async function applyMockTrialToWorkspace(slug: string) {await prisma.project.update({where: { slug },data: {- plan: "business",+ plan,subscriptionCanceledAt: null,billingCycleEndsAt: null,planTier: 1,- planPeriod: "monthly",+ planPeriod: period,trialEndsAt,billingCycleStart: new Date().getDate(),stripeId: `cus_e2e_mock_${slug}`,@@ -153,15 +170,25 @@ export async function applyMockTrialToWorkspace(slug: string) {domainsLimit: limits.domains,aiLimit: limits.ai,tagsLimit: limits.tags,+ partnerTagsLimit: limits.partnerTags,foldersLimit: limits.folders,groupsLimit: limits.groups,networkInvitesLimit: limits.networkInvites,+ partnersLimit: limits.partners,usersLimit: limits.users,paymentFailedAt: null,},});}+/** Mirrors activate-paid-plan success: trial ended, subscription treated as active in UI. */+export async function applyMockActivatedPaidPlan(slug: string) {+ await prisma.project.update({+ where: { slug },+ data: { trialEndsAt: null },+ });+}+/*** Use after a mocked `POST .../billing/upgrade` during onboarding when the app would call* `redirectToCheckout`. Real Stripe.js over HTTP logs warnings and can block redirects when@@ -244,8 +271,11 @@ export async function installBillingCheckoutMocks(await route.continue();return;}- await applyMockTrialToWorkspace(slug);const { onboarding, plan, period } = pendingCheckout;+ await applyMockTrialToWorkspace(slug, {+ plan,+ period: period as "monthly" | "yearly",+ });// Same path/query shape as stripe.checkout.sessions.create success_url in// app/api/workspaces/[idOrSlug]/billing/upgrade/route.ts — origin from baseURL// keeps Playwright on the app host (cookies), unlike APP_DOMAIN in local dev.diff --git a/apps/web/playwright/workspaces/billing-trial.spec.ts b/apps/web/playwright/workspaces/billing-trial.spec.tsindex cac657d0d8..d676405ac0 100644--- a/apps/web/playwright/workspaces/billing-trial.spec.ts+++ b/apps/web/playwright/workspaces/billing-trial.spec.ts@@ -1,6 +1,7 @@import { DUB_TRIAL_PERIOD_DAYS } from "@dub/utils";import { expect, test } from "@playwright/test";import {+ applyMockActivatedPaidPlan,applyMockTrialToWorkspace,captureWorkspaceBillingTrialSnapshot,installBillingCheckoutMocks,@@ -13,85 +14,85 @@ function matchesDashboardOrigin(url: URL, baseURL: string) {return url.hostname === base.hostname && url.port === base.port;}-test.skip("Billing trial checkout", () => {+test.describe("Billing trial checkout", () => {test("select Pro, success redirect, trial state and UI", async ({page,baseURL,+ request,}) => {const dashboardOrigin = baseURL ?? "http://app.localhost:8888";- // Discover the workspace created during onboarding- const res = await page.request.get("/api/workspaces");+ const res = await request.get("/api/workspaces");expect(res.ok()).toBeTruthy();const workspaces = (await res.json()) as { plan: string; slug: string }[];- // find the free workspace (from onboarding-dub-links.spec.ts)- const freeWorkspace = workspaces.find((w) => w.plan === "free");- if (!freeWorkspace) {- throw new Error("No free workspace found");+ const workspace =+ workspaces.find((w) => w.plan === "free") ?? workspaces[0];+ if (!workspace) {+ throw new Error("No workspace found");}- const slug = freeWorkspace.slug;-- await installBillingCheckoutMocks(page, {- slug,- baseURL: dashboardOrigin,- });-- await page.goto(`/${slug}/settings/billing/upgrade`);- await expect(- page.getByRole("heading", { name: "Plans", exact: true }),- ).toBeVisible({ timeout: 30_000 });-- // CTA: billing may show "Upgrade" or checkout trial copy from UpgradePlanButton.- const upgradeButton = page.getByRole("button", { name: "Upgrade" }).or(- page.getByRole("button", {- name: new RegExp(`Start ${DUB_TRIAL_PERIOD_DAYS}-day trial`),- }),- );-- await expect(upgradeButton.first()).toBeVisible();- await upgradeButton.first().click();-- await page.waitForURL(- (u) => {- const url = new URL(u);- return (- matchesDashboardOrigin(url, dashboardOrigin) &&- url.searchParams.get("upgraded") === "true"- );- },- { timeout: 30_000, waitUntil: "domcontentloaded" },- );-- await expect- .poll(- async () => {- const res = await page.request.get(`/api/workspaces/${slug}`);- if (!res.ok()) return null;- const body = (await res.json()) as { trialEndsAt?: string | null };- return body.trialEndsAt ?? null;+ const { slug } = workspace;+ expect(workspace.plan).toBe("free");++ const snapshot = await captureWorkspaceBillingTrialSnapshot(slug);+ await installBillingCheckoutMocks(page, { slug, baseURL: dashboardOrigin });++ try {+ await page.goto(`/${slug}/settings/billing/upgrade`);+ await expect(+ page.getByRole("heading", { name: "Plans", exact: true }),+ ).toBeVisible({ timeout: 30_000 });++ const proCard = page.getByRole("heading", { name: "Pro", exact: true });+ await proCard+ .locator("xpath=ancestor::div[contains(@class,'flex-col')][1]")+ .getByRole("button", {+ name: new RegExp(`Start ${DUB_TRIAL_PERIOD_DAYS}-day trial`, "i"),+ })+ .click();++ await page.waitForURL(+ (u) => {+ const url = new URL(u);+ return (+ matchesDashboardOrigin(url, dashboardOrigin) &&+ url.searchParams.get("upgraded") === "true" &&+ url.searchParams.get("plan") === "pro"+ );},- {- timeout: 90_000,- intervals: [500, 1000, 2000],- },- )- .not.toBeNull();-- await expect(- page.getByRole("heading", {- name: /Dub Pro looks good on you/i,- }),- ).toBeVisible({ timeout: 15_000 });-- await page.getByRole("button", { name: "View dashboard" }).click();-- await expect(page.getByText("Free trial", { exact: true })).toBeVisible({- timeout: 15_000,- });+ { timeout: 30_000, waitUntil: "domcontentloaded" },+ );++ await expect+ .poll(+ async () => {+ const wsRes = await request.get(`/api/workspaces/${slug}`);+ if (!wsRes.ok()) return null;+ const body = (await wsRes.json()) as {+ plan?: string;+ trialEndsAt?: string | null;+ };+ if (body.plan !== "pro" || !body.trialEndsAt) return null;+ return body.trialEndsAt;+ },+ { timeout: 90_000, intervals: [500, 1000, 2000] },+ )+ .not.toBeNull();++ await expect(+ page.getByRole("heading", { name: /Dub Pro looks good on you/i }),+ ).toBeVisible({ timeout: 15_000 });++ await page.getByRole("button", { name: "View dashboard" }).click();+ await expect(page.getByText("Free trial", { exact: true })).toBeVisible({+ timeout: 15_000,+ });+ } finally {+ await restoreWorkspaceBillingTrialSnapshot(slug, snapshot);+ }});});-test.skip("Free trial user navigation", () => {+test.describe("Free trial user navigation", () => {let slug: string;let workspaceId: string;let preMockTrialWorkspace: BillingMockTrialWorkspaceSnapshot | undefined;@@ -99,7 +100,15 @@ test.skip("Free trial user navigation", () => {test.beforeAll(async ({ request }) => {const res = await request.get("/api/workspaces");expect(res.ok()).toBeTruthy();- const [workspace] = (await res.json()) as { id: string; slug: string }[];+ const workspaces = (await res.json()) as {+ id: string;+ slug: string;+ plan: string;+ }[];+ // Same workspace as checkout test (API returns createdAt asc — links onboarding is first).+ const workspace =+ workspaces.find((w) => w.plan === "free") ?? workspaces[0];+ if (!workspace) throw new Error("No workspace found");slug = workspace.slug;workspaceId = workspace.id;@@ -113,9 +122,7 @@ test.skip("Free trial user navigation", () => {}});- test("billing settings page shows trial banner and CTAs", async ({- page,- }) => {+ test("billing settings page shows trial banner and CTAs", async ({ page }) => {await page.goto(`/${slug}/settings/billing`);await expect(page.getByText(/Trial ends on/)).toBeVisible({@@ -127,7 +134,7 @@ test.skip("Free trial user navigation", () => {await expect(page.getByRole("link", { name: "View plans" })).toBeVisible();});- test("upgrade page shows Activate plan for current Pro plan", async ({+ test("upgrade page shows Activate plan for current Business plan", async ({page,}) => {await page.goto(`/${slug}/settings/billing/upgrade`);@@ -135,8 +142,15 @@ test.skip("Free trial user navigation", () => {await expect(page.getByRole("heading", { name: "Plans", exact: true }),).toBeVisible({ timeout: 30_000 });++ const businessCard = page.getByRole("heading", {+ name: "Business",+ exact: true,+ });await expect(- page.getByRole("button", { name: "Activate plan" }),+ businessCard+ .locator("xpath=ancestor::div[contains(@class,'flex-col')][1]")+ .getByRole("button", { name: "Activate plan" }),).toBeVisible();});@@ -149,6 +163,7 @@ test.skip("Free trial user navigation", () => {`/api/workspaces/${workspaceId}/billing/activate-paid-plan`,async (route) => {if (route.request().method() !== "POST") return route.continue();+ await applyMockActivatedPaidPlan(slug);await route.fulfill({status: 200,contentType: "application/json",@@ -159,22 +174,29 @@ test.skip("Free trial user navigation", () => {await page.goto(`/${slug}/settings/billing`);- // Open the confirmation modalawait page.getByRole("button", { name: "Start paid plan" }).click();+ const confirmModal = page.getByRole("dialog").filter({+ has: page.getByRole("heading", { name: "Plan start confirmation" }),+ });+ await expect(confirmModal).toBeVisible();await expect(- page.getByRole("heading", { name: "Plan start confirmation" }),- ).toBeVisible();- await expect(- page.getByText("You'll be charged today and your trial will end."),+ confirmModal.getByText(+ "You'll be charged today and your trial will end.",+ ),).toBeVisible();-- // Confirm — triggers the mocked activate-paid-plan POST.- // Two "Start paid plan" buttons exist: the page-level CTA and the modal confirm.- await page.getByRole("button", { name: "Start paid plan" }).last().click();-- // Upgraded modal appears when ?upgraded=true lands in the URL+ await confirmModal+ .getByRole("button", { name: "Start paid plan" })+ .click();++ await page.waitForURL((u) => {+ const url = new URL(u);+ return (+ url.searchParams.get("upgraded") === "true" &&+ url.searchParams.get("plan") === "business"+ );+ });await expect(- page.getByRole("heading", { name: /Dub Pro looks good on you/i }),+ page.getByRole("heading", { name: /Dub Business looks good on you/i }),).toBeVisible({ timeout: 15_000 });});});