The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Move customers API integration tests to Playwright.
Kiran Kb987236c4a9c
diff --git a/apps/web/playwright/api/customers-pagination.spec.ts b/apps/web/playwright/api/customers-pagination.spec.tsnew file mode 100644index 0000000000..12b5e0115a--- /dev/null+++ b/apps/web/playwright/api/customers-pagination.spec.ts@@ -0,0 +1,282 @@+import { createId } from "@/lib/api/create-id";+import { prisma } from "@/lib/prisma";+import type { Customer } from "@/lib/types";+import { nanoid } from "@dub/utils";+import { expect } from "@playwright/test";+import {+ expectNoOverlap,+ expectSortedByCreatedAt,+ expectSortedById,+} from "../utils";+import { test } from "./fixtures";++const PAGE_SIZE = 5;+const SEED_COUNT = 25;++test.describe.configure({+ mode: "parallel",+});++test("GET /customers – rejects both startingAfter and endingBefore", async ({+ api,+}) => {+ const { status, data: error } = await api.get(+ `/api/customers?${new URLSearchParams({+ pageSize: String(PAGE_SIZE),+ startingAfter: "id",+ endingBefore: "id",+ })}`,+ );++ expect(status).toEqual(422);+ expect(error).toStrictEqual({+ error: {+ code: "unprocessable_entity",+ message:+ "You cannot use both startingAfter and endingBefore at the same time.",+ doc_url: "https://dub.co/docs/api-reference/errors#unprocessable-entity",+ },+ });+});++test("GET /customers – rejects page > MAX_OFFSET_PAGE", async ({ api }) => {+ const { status, data: error } = await api.get(+ `/api/customers?${new URLSearchParams({+ page: "1001",+ pageSize: "10",+ })}`,+ );++ expect(status).toEqual(422);+ expect(error).toStrictEqual({+ error: {+ code: "unprocessable_entity",+ message:+ "Page is too big (cannot be more than 1000), recommend using cursor-based pagination instead.",+ doc_url: "https://dub.co/docs/api-reference/errors#unprocessable-entity",+ },+ });+});++test("GET /customers – invalid cursor ID (startingAfter / endingBefore)", async ({+ api,+}) => {+ const invalidCursorError = {+ error: {+ code: "unprocessable_entity",+ message: "Invalid cursor: the provided ID does not exist.",+ doc_url: "https://dub.co/docs/api-reference/errors#unprocessable-entity",+ },+ };++ const { status: statusAfter, data: errorAfter } = await api.get(+ `/api/customers?${new URLSearchParams({+ pageSize: String(PAGE_SIZE),+ startingAfter: "cus_invalid_id_12345",+ })}`,+ );++ expect(statusAfter).toEqual(422);+ expect(errorAfter).toStrictEqual(invalidCursorError);++ const { status: statusBefore, data: errorBefore } = await api.get(+ `/api/customers?${new URLSearchParams({+ pageSize: String(PAGE_SIZE),+ endingBefore: "cus_invalid_id_12345",+ })}`,+ );++ expect(statusBefore).toEqual(422);+ expect(errorBefore).toStrictEqual(invalidCursorError);+});++test.describe("with seeded customers", () => {+ // Shared Prisma seed for this describe; serial so beforeAll runs once per worker group.+ test.describe.configure({ mode: "serial" });++ let seededIds: string[] = [];+ let baseline: Customer[] = [];+ let baselineIds: string[] = [];+ // Cursor pagination orders by id (see buildPaginationQuery), not createdAt.+ let idsByIdDesc: string[] = [];+ let customerIdsParam = "";++ const sortQuery = {+ sortBy: "createdAt",+ sortOrder: "desc",+ };++ test.beforeAll(async ({ api, workspace }) => {+ const batch = nanoid(8);+ const now = Date.now();++ const rows = Array.from({ length: SEED_COUNT }, (_, i) => ({+ id: createId({ prefix: "cus_" }),+ name: `pw-page-${batch}-${i}`,+ email: `pw-page-${batch}-${i}@dub-internal-test.com`,+ externalId: `ext_pw_page_${batch}_${i}`,+ country: "US",+ projectId: workspace.id,+ createdAt: new Date(now - i * 1000),+ }));++ await prisma.customer.createMany({ data: rows });+ seededIds = rows.map((r) => r.id);+ customerIdsParam = seededIds.join(",");+ idsByIdDesc = [...seededIds].sort((a, b) => (a < b ? 1 : a > b ? -1 : 0));++ const { status, data } = await api.get<Customer[]>(+ `/api/customers?${new URLSearchParams({+ ...sortQuery,+ pageSize: String(SEED_COUNT),+ customerIds: customerIdsParam,+ })}`,+ );++ expect(status).toEqual(200);+ expect(data).toHaveLength(SEED_COUNT);++ baseline = data;+ baselineIds = baseline.map((c) => c.id);+ expectSortedByCreatedAt(baseline);+ });++ test.afterAll(async () => {+ if (seededIds.length === 0) return;+ await prisma.customer.deleteMany({+ where: { id: { in: seededIds } },+ });+ });++ test("GET /customers – offset pagination", async ({ api }) => {+ const page1 = await api.get<Customer[]>(+ `/api/customers?${new URLSearchParams({+ ...sortQuery,+ page: "1",+ pageSize: String(PAGE_SIZE),+ customerIds: customerIdsParam,+ })}`,+ );+ const page2 = await api.get<Customer[]>(+ `/api/customers?${new URLSearchParams({+ ...sortQuery,+ page: "2",+ pageSize: String(PAGE_SIZE),+ customerIds: customerIdsParam,+ })}`,+ );++ expect(page1.status).toEqual(200);+ expect(page2.status).toEqual(200);++ expect(page1.data.map((c) => c.id)).toEqual(+ baselineIds.slice(0, PAGE_SIZE),+ );+ expect(page2.data.map((c) => c.id)).toEqual(+ baselineIds.slice(PAGE_SIZE, PAGE_SIZE * 2),+ );+ expectNoOverlap(page1.data, page2.data);+ });++ test("GET /customers – cursor forward (startingAfter)", async ({ api }) => {+ const firstPageIds = idsByIdDesc.slice(0, PAGE_SIZE);+ const cursor = firstPageIds[PAGE_SIZE - 1];+ const expectedIds = idsByIdDesc.slice(PAGE_SIZE, PAGE_SIZE * 2);++ const { status, data } = await api.get<Customer[]>(+ `/api/customers?${new URLSearchParams({+ ...sortQuery,+ pageSize: String(PAGE_SIZE),+ startingAfter: cursor,+ customerIds: customerIdsParam,+ })}`,+ );++ expect(status).toEqual(200);+ expect(data.map((c) => c.id)).toEqual(expectedIds);+ expect(data.every((c) => c.id < cursor)).toBe(true);+ expectSortedById(data, "desc");+ expectNoOverlap(+ firstPageIds.map((id) => ({ id })),+ data,+ );+ });++ test("GET /customers – cursor backward (endingBefore)", async ({ api }) => {+ const cursor = idsByIdDesc[PAGE_SIZE];+ const expectedIds = idsByIdDesc.slice(0, PAGE_SIZE);++ const { status, data } = await api.get<Customer[]>(+ `/api/customers?${new URLSearchParams({+ ...sortQuery,+ pageSize: String(PAGE_SIZE),+ endingBefore: cursor,+ customerIds: customerIdsParam,+ })}`,+ );++ expect(status).toEqual(200);+ expect(data.map((c) => c.id)).toEqual(expectedIds);+ expect(data.every((c) => c.id > cursor)).toBe(true);+ expectSortedById(data, "desc");+ });++ test("GET /customers – rejects mixing page with startingAfter / endingBefore", async ({+ api,+ }) => {+ const mixedPaginationError = {+ error: {+ code: "unprocessable_entity",+ message:+ "You cannot use both page and startingAfter/endingBefore at the same time. Please use one pagination method.",+ doc_url:+ "https://dub.co/docs/api-reference/errors#unprocessable-entity",+ },+ };++ const { status: statusAfter, data: errorAfter } = await api.get(+ `/api/customers?${new URLSearchParams({+ page: "2",+ pageSize: String(PAGE_SIZE),+ startingAfter: baseline[PAGE_SIZE - 1].id,+ })}`,+ );++ expect(statusAfter).toEqual(422);+ expect(errorAfter).toStrictEqual(mixedPaginationError);++ const { status: statusBefore, data: errorBefore } = await api.get(+ `/api/customers?${new URLSearchParams({+ page: "2",+ pageSize: String(PAGE_SIZE),+ endingBefore: baseline[PAGE_SIZE].id,+ })}`,+ );++ expect(statusBefore).toEqual(422);+ expect(errorBefore).toStrictEqual(mixedPaginationError);+ });++ test("GET /customers – rejects cursor pagination with unsupported sort field", async ({+ api,+ }) => {+ const { status, data: error } = await api.get(+ `/api/customers?${new URLSearchParams({+ pageSize: String(PAGE_SIZE),+ startingAfter: baseline[0].id,+ sortBy: "saleAmount",+ })}`,+ );++ expect(status).toEqual(422);+ expect(error).toStrictEqual({+ error: {+ code: "unprocessable_entity",+ message:+ "Cursor-based pagination only supports sorting by `createdAt`. Use offset-based pagination (page/pageSize) for other sort fields.",+ doc_url:+ "https://dub.co/docs/api-reference/errors#unprocessable-entity",+ },+ });+ });+});diff --git a/apps/web/playwright/api/customers.spec.ts b/apps/web/playwright/api/customers.spec.tsnew file mode 100644index 0000000000..fdbd5ce66d--- /dev/null+++ b/apps/web/playwright/api/customers.spec.ts@@ -0,0 +1,166 @@+import type { Customer } from "@/lib/types";+import { CustomerEnrichedSchema } from "@/lib/zod/schemas/customers";+import { expect } from "@playwright/test";+import { randomCustomer } from "../utils";+import { test, type ApiClient } from "./fixtures";++const expectedCustomerShape = {+ id: expect.any(String),+ name: expect.any(String),+ email: expect.any(String),+ avatar: null,+ externalId: expect.any(String),+ stripeCustomerId: null,+ country: "US",+ saleAmount: 0,+ sales: 0,+ createdAt: expect.any(String),+ firstSaleAt: null,+ subscriptionCanceledAt: null,+};++async function createCustomer(+ api: ApiClient,+ overrides: Record<string, unknown> = {},+) {+ const body = {+ ...randomCustomer(),+ ...overrides,+ };++ return api.post<Customer>("/api/customers", body);+}++async function deleteCustomer(api: ApiClient, id: string | undefined) {+ if (!id) return;+ await api.delete(`/api/customers/${id}`);+}++test.describe.configure({+ mode: "parallel",+});++test("POST /customers", async ({ api }) => {+ let customerId: string | undefined;+ const body = randomCustomer();++ try {+ const { status, data } = await api.post<Customer>("/api/customers", body);+ customerId = data.id;++ expect(status).toEqual(201);+ expect(data).toStrictEqual({+ ...expectedCustomerShape,+ ...body,+ avatar: null,+ });+ } finally {+ await deleteCustomer(api, customerId);+ }+});++test("GET /customers/{id}", async ({ api }) => {+ let customerId: string | undefined;++ try {+ const { data: created } = await createCustomer(api);+ customerId = created.id;++ const { status, data } = await api.get<Customer>(+ `/api/customers/${customerId}`,+ );++ expect(status).toEqual(200);+ expect(data).toStrictEqual(created);+ } finally {+ await deleteCustomer(api, customerId);+ }+});++test("GET /customers – by email", async ({ api }) => {+ let customerId: string | undefined;++ try {+ const { data: created } = await createCustomer(api);+ customerId = created.id;++ const { status, data: customers } = await api.get<Customer[]>(+ `/api/customers?email=${encodeURIComponent(created.email!)}`,+ );++ expect(status).toEqual(200);+ expect(customers.length).toBeGreaterThanOrEqual(1);+ expect(customers[0]).toStrictEqual(created);+ } finally {+ await deleteCustomer(api, customerId);+ }+});++test("PATCH /customers/{id}", async ({ api }) => {+ let customerId: string | undefined;++ try {+ const { data: created } = await createCustomer(api);+ customerId = created.id;++ const toUpdate = {+ name: "Updated",+ avatar: "https://api.dub.co/og/avatar/1234567890",+ };++ const { status, data } = await api.patch<Customer>(+ `/api/customers/${customerId}`,+ toUpdate,+ );++ expect(status).toEqual(200);+ expect(data).toStrictEqual({+ ...created,+ ...toUpdate,+ });+ } finally {+ await deleteCustomer(api, customerId);+ }+});++test("GET /customers – by externalId with includeExpandedFields", async ({+ api,+}) => {+ let customerId: string | undefined;++ try {+ const { data: created } = await createCustomer(api);+ customerId = created.id;++ const { status, data: customers } = await api.get<Customer[]>(+ `/api/customers?externalId=${encodeURIComponent(created.externalId)}&includeExpandedFields=true`,+ );++ expect(status).toEqual(200);+ expect(customers.length).toBeGreaterThanOrEqual(1);+ expect(+ CustomerEnrichedSchema.parse({+ ...customers[0],+ createdAt: new Date(customers[0].createdAt),+ }),+ ).toBeTruthy();+ } finally {+ await deleteCustomer(api, customerId);+ }+});++test("DELETE /customers/{id}", async ({ api }) => {+ const { data: created } = await createCustomer(api);++ const { status, data } = await api.delete<{ id: string }>(+ `/api/customers/${created.id}`,+ );++ expect(status).toEqual(200);+ expect(data).toStrictEqual({+ id: created.id,+ });++ const { status: getStatus } = await api.get(`/api/customers/${created.id}`);+ expect(getStatus).toEqual(404);+});diff --git a/apps/web/playwright/utils.ts b/apps/web/playwright/utils.tsindex fce84f5380..8f499f92dc 100644--- a/apps/web/playwright/utils.ts+++ b/apps/web/playwright/utils.ts@@ -1,5 +1,53 @@+import { generateRandomName } from "@/lib/names";import { nanoid } from "@dub/utils";+import { expect } from "@playwright/test";export function randomName(prefix = "e2e", length = 5) {return `${prefix}-${nanoid(length)}`;}++export function randomCustomer({+ emailDomain = "dub-internal-test.com",+}: {+ emailDomain?: string;+} = {}) {+ const id = nanoid(12);+ const name = generateRandomName();++ return {+ externalId: `ext_pw_${id}`,+ name,+ email: `pw.${id}@${emailDomain}`,+ avatar: null as string | null,+ country: "US",+ };+}++export function expectSortedById(+ items: { id: string }[],+ order: "asc" | "desc",+) {+ for (let i = 0; i < items.length - 1; i++) {+ const cmp = items[i].id.localeCompare(items[i + 1].id);+ if (order === "desc") {+ expect(cmp).toBeGreaterThanOrEqual(0);+ } else {+ expect(cmp).toBeLessThanOrEqual(0);+ }+ }+}++export function expectSortedByCreatedAt<T extends { createdAt: string | Date }>(+ items: T[],+) {+ for (let i = 0; i < items.length - 1; i++) {+ const a = new Date(items[i].createdAt).getTime();+ const b = new Date(items[i + 1].createdAt).getTime();+ expect(a).toBeGreaterThanOrEqual(b);+ }+}++export function expectNoOverlap<T extends { id: string }>(a: T[], b: T[]) {+ const overlap = a.map((x) => x.id).filter((id) => b.some((y) => y.id === id));+ expect(overlap).toHaveLength(0);+}diff --git a/apps/web/tests/customers/index.test.ts b/apps/web/tests/customers/index.test.tsdeleted file mode 100644index 673fc2c344..0000000000--- a/apps/web/tests/customers/index.test.ts+++ /dev/null@@ -1,78 +0,0 @@-import { Customer } from "@/lib/types";-import { CustomerEnrichedSchema } from "@/lib/zod/schemas/customers";-import { describe, expect, test } from "vitest";-import { IntegrationHarness } from "../utils/integration";--const expectedCustomer = {- id: "cus_n5LF7wS3Z1vfwjZCyy5QDC7Q",- externalId: "cus_OmLauTvvWCtJsFN1yJb0oevj",- email: "[email protected]",- stripeCustomerId: null,- country: "US",- name: expect.any(String),- avatar: expect.any(String),- saleAmount: 0,- sales: 0,- createdAt: expect.any(String),- firstSaleAt: null,- subscriptionCanceledAt: null,-};--describe.sequential("/customers/**", async () => {- const h = new IntegrationHarness();- const { http } = await h.init();-- const customerId = expectedCustomer.id;-- test("GET /customers/{id}", async () => {- const { status, data: retrievedCustomer } = await http.get<Customer>({- path: `/customers/${customerId}`,- });-- expect(status).toEqual(200);- expect(retrievedCustomer).toStrictEqual(expectedCustomer);- });-- test("GET /customers", async () => {- const { status, data: customers } = await http.get<Customer[]>({- path: `/customers?email=${expectedCustomer.email}`,- });-- expect(status).toEqual(200);- expect(customers.length).toBeGreaterThanOrEqual(1);- expect(customers[0]).toStrictEqual(expectedCustomer);- });-- test("PATCH /customers/{id}", async () => {- const toUpdate = {- name: "Updated",- avatar: "https://api.dub.co/og/avatar/1234567890",- };-- const { status, data: customer } = await http.patch<Customer>({- path: `/customers/${customerId}`,- body: toUpdate,- });-- expect(status).toEqual(200);- expect(customer).toStrictEqual({- ...expectedCustomer,- ...toUpdate,- });- });-- test("GET /customers by externalId with includeExpandedFields", async () => {- const { status, data: customers } = await http.get<Customer[]>({- path: `/customers?externalId=${expectedCustomer.externalId}&includeExpandedFields=true`,- });-- expect(status).toEqual(200);- expect(customers.length).toBeGreaterThanOrEqual(1);- expect(- CustomerEnrichedSchema.parse({- ...customers[0],- createdAt: new Date(customers[0].createdAt),- }),- ).toBeTruthy();- });-});diff --git a/apps/web/tests/customers/pagination.test.ts b/apps/web/tests/customers/pagination.test.tsdeleted file mode 100644index 15a869c44c..0000000000--- a/apps/web/tests/customers/pagination.test.ts+++ /dev/null@@ -1,197 +0,0 @@-import { Customer } from "@/lib/types";-import { beforeAll, describe, expect, test } from "vitest";-import {- expectNoOverlap,- expectSortedByCreatedAt,- expectSortedById,-} from "../utils/helpers";-import { IntegrationHarness } from "../utils/integration";--describe.concurrent("/customers/** - pagination", async () => {- const h = new IntegrationHarness();- let http: IntegrationHarness["http"];- let baseline: Customer[];- let baselineIds: string[];-- const commonQuery = {- pageSize: "5",- sortBy: "createdAt",- sortOrder: "desc",- };-- beforeAll(async () => {- ({ http } = await h.init());-- const { status, data } = await http.get<Customer[]>({- path: "/customers",- query: { ...commonQuery, pageSize: "25" },- });-- expect(status).toEqual(200);-- baseline = data;- baselineIds = baseline.map((c) => c.id);-- expectSortedByCreatedAt(baseline);- });-- test("Offset pagination works", async () => {- const page1 = await http.get<Customer[]>({- path: "/customers",- query: { ...commonQuery, page: "1" },- });- const page2 = await http.get<Customer[]>({- path: "/customers",- query: { ...commonQuery, page: "2" },- });-- expect(page1.status).toEqual(200);- expect(page2.status).toEqual(200);-- expect(page1.data.map((c) => c.id)).toEqual(baselineIds.slice(0, 5));- expect(page2.data.map((c) => c.id)).toEqual(baselineIds.slice(5, 10));-- expectNoOverlap(page1.data, page2.data);- });-- test("Cursor forward (startingAfter)", async () => {- const firstPage = baseline.slice(0, 5);- const lastId = firstPage[4].id;-- const { status, data } = await http.get<Customer[]>({- path: "/customers",- query: { pageSize: "5", startingAfter: lastId },- });-- expect(status).toEqual(200);- expect(data).toHaveLength(5);- expectSortedById(data, "desc");- });-- test("Cursor backward (endingBefore)", async () => {- const beforeId = baseline[5].id;-- const { status, data } = await http.get<Customer[]>({- path: "/customers",- query: { pageSize: "5", endingBefore: beforeId },- });-- expect(status).toEqual(200);- expect(data).toHaveLength(5);- expectSortedById(data, "desc");- });-- test("Rejects both startingAfter and endingBefore", async () => {- const { status, data: error } = await http.get({- path: "/customers",- query: { pageSize: "5", startingAfter: "id", endingBefore: "id" },- });-- expect(status).toEqual(422);- expect(error).toStrictEqual({- error: {- code: "unprocessable_entity",- message:- "You cannot use both startingAfter and endingBefore at the same time.",- doc_url:- "https://dub.co/docs/api-reference/errors#unprocessable-entity",- },- });- });-- test("Rejects page > MAX_OFFSET_PAGE", async () => {- const { status, data: error } = await http.get({- path: "/customers",- query: { page: "1001", pageSize: "10" },- });-- expect(status).toEqual(422);- expect(error).toStrictEqual({- error: {- code: "unprocessable_entity",- message:- "Page is too big (cannot be more than 1000), recommend using cursor-based pagination instead.",- doc_url:- "https://dub.co/docs/api-reference/errors#unprocessable-entity",- },- });- });-- test("Invalid cursor ID (startingAfter / endingBefore) returns error", async () => {- const invalidCursorError = {- error: {- code: "unprocessable_entity",- message: "Invalid cursor: the provided ID does not exist.",- doc_url:- "https://dub.co/docs/api-reference/errors#unprocessable-entity",- },- };-- const { status: statusAfter, data: errorAfter } = await http.get({- path: "/customers",- query: { pageSize: "5", startingAfter: "cus_invalid_id_12345" },- });-- expect(statusAfter).toEqual(422);- expect(errorAfter).toStrictEqual(invalidCursorError);-- const { status: statusBefore, data: errorBefore } = await http.get({- path: "/customers",- query: { pageSize: "5", endingBefore: "cus_invalid_id_12345" },- });-- expect(statusBefore).toEqual(422);- expect(errorBefore).toStrictEqual(invalidCursorError);- });-- test("Rejects mixing page with startingAfter / endingBefore", async () => {- const mixedPaginationError = {- error: {- code: "unprocessable_entity",- message:- "You cannot use both page and startingAfter/endingBefore at the same time. Please use one pagination method.",- doc_url:- "https://dub.co/docs/api-reference/errors#unprocessable-entity",- },- };-- const firstPage = baseline.slice(0, 5);- const { status: statusAfter, data: errorAfter } = await http.get({- path: "/customers",- query: { page: "2", pageSize: "5", startingAfter: firstPage[4].id },- });-- expect(statusAfter).toEqual(422);- expect(errorAfter).toStrictEqual(mixedPaginationError);-- const { status: statusBefore, data: errorBefore } = await http.get({- path: "/customers",- query: { page: "2", pageSize: "5", endingBefore: baseline[5].id },- });-- expect(statusBefore).toEqual(422);- expect(errorBefore).toStrictEqual(mixedPaginationError);- });-- test("Rejects cursor pagination with unsupported sort field", async () => {- const { status, data: error } = await http.get({- path: "/customers",- query: {- pageSize: "5",- startingAfter: baseline[0].id,- sortBy: "saleAmount",- },- });-- expect(status).toEqual(422);- expect(error).toStrictEqual({- error: {- code: "unprocessable_entity",- message:- "Cursor-based pagination only supports sorting by `createdAt`. Use offset-based pagination (page/pageSize) for other sort fields.",- doc_url:- "https://dub.co/docs/api-reference/errors#unprocessable-entity",- },- });- });-});