The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Move tags API integration tests to Playwright.
Kiran K9a5eecd4277a
diff --git a/apps/web/global-setup.ts b/apps/web/global-setup.tsindex 3d051cc003..8fb7724d27 100644--- a/apps/web/global-setup.ts+++ b/apps/web/global-setup.ts@@ -1,7 +1,11 @@-import "dotenv-flow/config";-+import { config as loadEnv } from "dotenv-flow";import type { FullConfig } from "@playwright/test";+import { setupTestWorkspace } from "./playwright/api/setup-test-workspace";++loadEnv();-async function globalSetup(_config: FullConfig) {}+async function globalSetup(_config: FullConfig) {+ await setupTestWorkspace();+}export default globalSetup;diff --git a/apps/web/playwright.config.ts b/apps/web/playwright.config.tsindex 37dc310e5f..c4d8f0269f 100644--- a/apps/web/playwright.config.ts+++ b/apps/web/playwright.config.ts@@ -11,7 +11,8 @@ export default defineConfig({fullyParallel: false,forbidOnly: !!process.env.CI,retries: 1,- workers: process.env.CI ? 1 : undefined,+ // Local .env often sets CI=true for other tooling; only pin to 1 worker on Actions.+ workers: process.env.GITHUB_ACTIONS ? 1 : undefined,reporter: process.env.CI? [["list"], ["html", { outputFolder: "playwright-report" }]]: [["html", { open: "always" }]],@@ -24,6 +25,15 @@ export default defineConfig({screenshot: "only-on-failure",},projects: [+ // API tests (Bearer token seeded in globalSetup)+ {+ name: "api",+ testDir: "./playwright/api",+ fullyParallel: true,+ use: {+ baseURL: workspaceBaseURL,+ },+ },// Partner tests{name: "partner-setup",diff --git a/apps/web/playwright/README.md b/apps/web/playwright/README.mdindex 9d2fd72311..c8ce929d3f 100644--- a/apps/web/playwright/README.md+++ b/apps/web/playwright/README.md@@ -30,6 +30,14 @@The seeded test user (`E2E_PARTNER_EMAIL`) must exist in your local database — run `tsx apps/web/playwright/seed.ts` to create it. Signup tests generate a fresh user each run via MailHog email verification.+## API tests++API specs under `playwright/api` use a Bearer token. `globalSetup` upserts a dedicated user, workspace, and token into `playwright/.auth/api.json` before any project runs. No MailHog or browser auth required.++```sh+pnpm --filter web test:e2e --project=api+```+## Running testsMake sure the dev server is running first (`pnpm dev`), then:diff --git a/apps/web/playwright/api/fixtures.ts b/apps/web/playwright/api/fixtures.tsnew file mode 100644index 0000000000..f0af625fbd--- /dev/null+++ b/apps/web/playwright/api/fixtures.ts@@ -0,0 +1,59 @@+import { test as base, type APIRequestContext } from "@playwright/test";+import { readFileSync } from "fs";+import path from "path";++const authFile = path.join(__dirname, "../.auth/api.json");++type ApiResponse<T> = {+ status: number;+ data: T;+};++type ApiClient = {+ get: <T>(url: string) => Promise<ApiResponse<T>>;+ post: <T>(url: string, data?: unknown) => Promise<ApiResponse<T>>;+ delete: <T>(url: string) => Promise<ApiResponse<T>>;+};++function loadApiAuth(): { token: string } {+ return JSON.parse(readFileSync(authFile, "utf-8")) as { token: string };+}++function createApiClient(request: APIRequestContext): ApiClient {+ async function parse<T>(+ responsePromise: ReturnType<APIRequestContext["fetch"]>,+ ): Promise<ApiResponse<T>> {+ const response = await responsePromise;+ return {+ status: response.status(),+ data: (await response.json()) as T,+ };+ }++ return {+ get: <T>(url: string) => parse<T>(request.get(url)),+ post: <T>(url: string, data?: unknown) =>+ parse<T>(request.post(url, { data })),+ delete: <T>(url: string) => parse<T>(request.delete(url)),+ };+}++export const test = base.extend<{ api: ApiClient }>({+ // Authenticated API request context (token from globalSetup → .auth/api.json).+ request: async ({ playwright, baseURL }, use) => {+ const { token } = loadApiAuth();+ const context = await playwright.request.newContext({+ baseURL,+ extraHTTPHeaders: {+ Authorization: `Bearer ${token}`,+ "Content-Type": "application/json",+ },+ });+ await use(context);+ await context.dispose();+ },++ api: async ({ request }, use) => {+ await use(createApiClient(request));+ },+});diff --git a/apps/web/playwright/api/setup-test-workspace.ts b/apps/web/playwright/api/setup-test-workspace.tsnew file mode 100644index 0000000000..3cb230918d--- /dev/null+++ b/apps/web/playwright/api/setup-test-workspace.ts@@ -0,0 +1,151 @@+import { createId } from "@/lib/api/create-id";+import { hashToken } from "@/lib/auth/hash-token";+import { prisma } from "@/lib/prisma";+import { nanoid } from "@dub/utils";+import { config as loadEnv } from "dotenv-flow";+import { mkdir, writeFile } from "fs/promises";+import path from "path";++loadEnv();++export const TEST_WORKSPACE = {+ user: {+ email: "[email protected]",+ name: "Playwright API",+ },+ workspace: {+ slug: "playwright-api",+ name: "Playwright API",+ },+ token: {+ name: "Playwright API",+ },+} as const;++const authFile = path.join(__dirname, "../.auth/api.json");+const apiBaseURL = "http://localhost:8888";++// Upserts a dedicated Playwright API user, workspace, membership, and+// RestrictedToken. Safe to run repeatedly from globalSetup.+export async function setupTestWorkspace() {+ const user = await prisma.user.upsert({+ where: {+ email: TEST_WORKSPACE.user.email,+ },+ update: {+ name: TEST_WORKSPACE.user.name,+ emailVerified: new Date(),+ defaultWorkspace: TEST_WORKSPACE.workspace.slug,+ },+ create: {+ id: createId({ prefix: "user_" }),+ email: TEST_WORKSPACE.user.email,+ name: TEST_WORKSPACE.user.name,+ emailVerified: new Date(),+ defaultWorkspace: TEST_WORKSPACE.workspace.slug,+ },+ });++ const workspace = await prisma.project.upsert({+ where: {+ slug: TEST_WORKSPACE.workspace.slug,+ },+ update: {+ name: TEST_WORKSPACE.workspace.name,+ plan: "enterprise",+ tagsLimit: 1000,+ usageLimit: 1_000_000,+ linksLimit: 1_000_000,+ domainsLimit: 100,+ usersLimit: 100,+ foldersLimit: 100,+ aiLimit: 1000,+ },+ create: {+ id: createId({ prefix: "ws_" }),+ name: TEST_WORKSPACE.workspace.name,+ slug: TEST_WORKSPACE.workspace.slug,+ billingCycleStart: new Date().getDate(),+ plan: "enterprise",+ tagsLimit: 1000,+ usageLimit: 1_000_000,+ linksLimit: 1_000_000,+ domainsLimit: 100,+ usersLimit: 100,+ foldersLimit: 100,+ aiLimit: 1000,+ },+ });++ const projectUser = await prisma.projectUsers.upsert({+ where: {+ userId_projectId: {+ userId: user.id,+ projectId: workspace.id,+ },+ },+ update: {+ role: "owner",+ },+ create: {+ userId: user.id,+ projectId: workspace.id,+ role: "owner",+ },+ });++ await prisma.notificationPreference.upsert({+ where: {+ projectUserId: projectUser.id,+ },+ update: {},+ create: {+ projectUserId: projectUser.id,+ },+ });++ const token = `dub_${nanoid(24)}`;+ const hashedKey = await hashToken(token);+ const partialKey = `${token.slice(0, 3)}...${token.slice(-4)}`;++ // Drop any prior tokens with this name (including orphaned rows from bad seeds)+ await prisma.restrictedToken.deleteMany({+ where: {+ name: TEST_WORKSPACE.token.name,+ },+ });++ await prisma.restrictedToken.create({+ data: {+ name: TEST_WORKSPACE.token.name,+ hashedKey,+ partialKey,+ userId: user.id,+ projectId: workspace.id,+ scopes: "apis.all",+ },+ });++ await mkdir(path.dirname(authFile), { recursive: true });+ await writeFile(+ authFile,+ JSON.stringify(+ {+ token,+ workspaceId: workspace.id,+ baseURL: apiBaseURL,+ userId: user.id,+ workspaceSlug: workspace.slug,+ },+ null,+ 2,+ ),+ );++ return {+ token,+ userId: user.id,+ workspaceId: workspace.id,+ workspaceSlug: workspace.slug,+ };+}diff --git a/apps/web/playwright/api/tags.spec.ts b/apps/web/playwright/api/tags.spec.tsnew file mode 100644index 0000000000..05aebd2b04--- /dev/null+++ b/apps/web/playwright/api/tags.spec.ts@@ -0,0 +1,137 @@+import { expect } from "@playwright/test";+import type { Tag } from "@prisma/client";+import { randomName } from "../utils";+import { test } from "./fixtures";++test.describe.configure({+ mode: "parallel",+});++test("POST /tags", async ({ api }) => {+ let tagId: string | undefined;++ try {+ const newTag = {+ name: randomName("tag"),+ color: "red",+ };++ const { status, data: tag } = await api.post<Tag>("/api/tags", newTag);+ tagId = tag.id;++ expect(status).toEqual(201);+ expect(tag).toStrictEqual({+ id: expect.any(String),+ ...newTag,+ });+ } finally {+ if (tagId) await api.delete(`/api/tags/${tagId}`);+ }+});++const errorCases = [+ {+ name: "POST /tags – invalid color",+ body: {+ tag: "news",+ color: "invalid",+ },+ expected: {+ status: 422,+ data: {+ error: {+ code: "unprocessable_entity",+ message:+ "invalid_value: color: Invalid color. Must be one of: red, yellow, green, blue, purple, brown, gray, pink", // TODO: update this to use RESOURCE_COLORS+ doc_url:+ "https://dub.co/docs/api-reference/errors#unprocessable-entity",+ },+ },+ },+ },+ {+ name: "POST /tags – without name",+ body: {+ color: "red",+ },+ expected: {+ status: 422,+ data: {+ error: {+ code: "unprocessable_entity",+ message: "custom: name: Name is required.",+ doc_url:+ "https://dub.co/docs/api-reference/errors#unprocessable-entity",+ },+ },+ },+ },+];++for (const { name, body, expected } of errorCases) {+ test(name, async ({ api }) => {+ const response = await api.post("/api/tags", body);+ expect(response).toEqual(expected);+ });+}++test("POST /tags – existing name", async ({ api }) => {+ let tagId: string | undefined;+ const tagName = randomName("tag");++ try {+ const { data: created } = await api.post<Tag>("/api/tags", {+ tag: tagName,+ color: "red",+ });+ tagId = created.id;++ // Create the same tag again+ const { status, data: error } = await api.post("/api/tags", {+ tag: tagName,+ color: "red",+ });++ expect(status).toBe(409);+ expect(error).toEqual({+ error: {+ code: "conflict",+ message: "A tag with that name already exists.",+ doc_url: "https://dub.co/docs/api-reference/errors#conflict",+ },+ });+ } finally {+ if (tagId) await api.delete(`/api/tags/${tagId}`);+ }+});++test("GET /tags", async ({ api }) => {+ let tagId: string | undefined;++ try {+ const newTag = {+ tag: randomName("tag"),+ color: "red",+ };++ const { data: tagCreated } = await api.post<Tag>("/api/tags", newTag);+ tagId = tagCreated.id;++ const { status, data: tags } = await api.get<Tag[]>(+ "/api/tags?sortBy=createdAt&sortOrder=desc",+ );++ expect(status).toEqual(200);+ expect(tags).toEqual(+ expect.arrayContaining([+ {+ id: tagCreated.id,+ name: tagCreated.name,+ color: tagCreated.color,+ },+ ]),+ );+ } finally {+ if (tagId) await api.delete(`/api/tags/${tagId}`);+ }+});diff --git a/apps/web/playwright/utils.ts b/apps/web/playwright/utils.tsnew file mode 100644index 0000000000..fce84f5380--- /dev/null+++ b/apps/web/playwright/utils.ts@@ -0,0 +1,5 @@+import { nanoid } from "@dub/utils";++export function randomName(prefix = "e2e", length = 5) {+ return `${prefix}-${nanoid(length)}`;+}diff --git a/apps/web/tests/tags/create-tag-error.test.ts b/apps/web/tests/tags/create-tag-error.test.tsdeleted file mode 100644index 7e7ba332d2..0000000000--- a/apps/web/tests/tags/create-tag-error.test.ts+++ /dev/null@@ -1,87 +0,0 @@-import { Tag } from "@prisma/client";-import { expect, test } from "vitest";-import { IntegrationHarness } from "../utils/integration";--const cases = [- {- name: "create tag with invalid color",- body: {- tag: "news",- color: "invalid",- },- expected: {- status: 422,- data: {- error: {- code: "unprocessable_entity",- message:- "invalid_value: color: Invalid color. Must be one of: red, yellow, green, blue, purple, brown, gray, pink", // TODO: update this to use RESOURCE_COLORS- doc_url:- "https://dub.co/docs/api-reference/errors#unprocessable-entity",- },- },- },- },- {- name: "create tag without name",- body: {- color: "red",- },- expected: {- status: 422,- data: {- error: {- code: "unprocessable_entity",- message: "custom: name: Name is required.",- doc_url:- "https://dub.co/docs/api-reference/errors#unprocessable-entity",- },- },- },- },-];--cases.forEach(({ name, body, expected }) => {- test(name, async (ctx) => {- const h = new IntegrationHarness(ctx);- const { http } = await h.init();-- const response = await http.post<Tag>({- path: "/tags",- body,- });-- expect(response).toEqual(expected);- });-});--test("create tag with existing name", async (ctx) => {- const h = new IntegrationHarness(ctx);- const { http } = await h.init();-- await http.post({- path: "/tags",- body: {- tag: "news",- color: "red",- },- });-- // Create the same tag again- const { status, data: error } = await http.post<Tag>({- path: "/tags",- body: {- tag: "news",- color: "red",- },- });-- expect(status).toBe(409);- expect(error).toEqual({- error: {- code: "conflict",- message: "A tag with that name already exists.",- doc_url: "https://dub.co/docs/api-reference/errors#conflict",- },- });-});diff --git a/apps/web/tests/tags/create-tag.test.ts b/apps/web/tests/tags/create-tag.test.tsdeleted file mode 100644index 28d49bd772..0000000000--- a/apps/web/tests/tags/create-tag.test.ts+++ /dev/null@@ -1,29 +0,0 @@-import { Tag } from "@prisma/client";-import { expect, onTestFinished, test } from "vitest";-import { randomTagName } from "../utils/helpers";-import { IntegrationHarness } from "../utils/integration";--test("POST /tags", async (ctx) => {- const h = new IntegrationHarness(ctx);- const { http } = await h.init();-- onTestFinished(async () => {- await h.deleteTag(tag.id);- });-- const newTag = {- name: randomTagName(),- color: "red",- };-- const { status, data: tag } = await http.post<Tag>({- path: "/tags",- body: newTag,- });-- expect(status).toEqual(201);- expect(tag).toStrictEqual({- id: expect.any(String),- ...newTag,- });-});diff --git a/apps/web/tests/tags/list-tags.test.ts b/apps/web/tests/tags/list-tags.test.tsdeleted file mode 100644index a1068801b1..0000000000--- a/apps/web/tests/tags/list-tags.test.ts+++ /dev/null@@ -1,38 +0,0 @@-import { Tag } from "@prisma/client";-import { expect, onTestFinished, test } from "vitest";-import { randomTagName } from "../utils/helpers";-import { IntegrationHarness } from "../utils/integration";--test("GET /tags", async (ctx) => {- const h = new IntegrationHarness(ctx);- const { http } = await h.init();-- onTestFinished(async () => {- await h.deleteTag(tagCreated.id);- });-- const newTag = {- tag: randomTagName(),- color: "red",- };-- const { data: tagCreated } = await http.post<Tag>({- path: "/tags",- body: newTag,- });-- const { status, data: tags } = await http.get<Tag[]>({- path: "/tags?sortBy=createdAt&sortOrder=desc",- });-- expect(status).toEqual(200);- expect(tags).toEqual(- expect.arrayContaining([- {- id: tagCreated.id,- name: tagCreated.name,- color: tagCreated.color,- },- ]),- );-});