Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Migrate POST /partners coverage from Vitest to Playwright API tests.

Kiran K9b03f3c1bcf7
diff --git a/.agents/skills/playwright-api-tests/SKILL.md b/.agents/skills/playwright-api-tests/SKILL.md
index d7922c01bb..63f6005cc5 100644
--- a/.agents/skills/playwright-api-tests/SKILL.md
+++ b/.agents/skills/playwright-api-tests/SKILL.md
@@ -95,28 +95,32 @@ test("POST /things", async ({ api }) => {
## Required conventions
-| Rule | Detail |
-| ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
-| Import `test` from `../fixtures` | Provides `api` and `workspace` |
-| `test.describe.configure({ mode: "parallel" })` | At top of every API spec file |
-| Cleanup in `finally` | Create → assert → always delete created rows |
-| Unique names/ids | Use `randomName` / `randomCustomer` from `../../utils` — never fixed colliding names across parallel workers |
-| Assert status + body | Prefer `toStrictEqual` / `toEqual` on full shapes; use `expect.any(String)` for ids/timestamps |
-| Error responses | Match `{ error: { code, message, doc_url } }` exactly |
-| Typed generics | `api.get<T>`, `api.post<T>`, etc. |
-| Workspace fixture | Use `{ workspace }` for id/slug from seed (`workspaces/workspaces.spec.ts`) — do not hardcode slug |
-
-### Fixtures (`api` / `workspace`)
+| Rule | Detail |
+| ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
+| Import `test` from `../fixtures` | Provides `api`, `workspace`, and `program` |
+| `test.describe.configure({ mode: "parallel" })` | At top of every API spec file |
+| Cleanup in `finally` | Create → assert → always delete created rows |
+| Unique names/ids | Use `randomName` / `randomCustomer` / `randomPartnerEmail` from `../../utils` — never fixed colliding names |
+| Assert status + body | Prefer `toStrictEqual` / `toEqual` on full shapes; use `expect.any(String)` for ids/timestamps |
+| Default shape once | Happy-path POST owns the full default resource (and nested) shape. Variant tests assert only what they change |
+| HTTP contract only | Assert status + JSON. Do not poll/sleep for `waitUntil`, R2, or other background jobs — CI has no `STORAGE_*` |
+| Error responses | Match `{ error: { code, message, doc_url } }` exactly |
+| Typed generics | `api.get<T>`, `api.post<T>`, etc. |
+| Seeded fixtures | `{ workspace }`, `{ program }` (`id`, `defaultGroupId`), `TEST_WORKSPACE` — not Vitest `E2E_*` constants |
+
+### Fixtures (`api` / `workspace` / `program`)
- `api.get/post/patch/delete(url, data?)` → `{ status, data }` (JSON parsed).
- Paths are app-relative (`/api/...`); `baseURL` is `http://localhost:8888`.
-- `workspace.id` / `workspace.slug` come from `.auth/api.json`.
+- `workspace.id` / `workspace.slug` and `program.id` / `program.defaultGroupId` come from `.auth/api.json`.
+- Seeded program domain/url: `TEST_WORKSPACE.program` in `setup-test-workspace.ts`.
### Helpers
- Shared randomizers / sort assertions: `apps/web/playwright/utils.ts`.
- Local `createX` / `deleteX` helpers in the spec file when the same setup repeats.
-- Prisma direct seed is allowed for bulk fixtures (see `customers/customers-pagination.spec.ts`); still clean up in `finally` / after hooks.
+- Once `createX` exists, use it for setup **and** follow-up creates (pass overrides for identity fields that must stay stable, e.g. `email`). Happy-path tests may still inline `api.post` so the asserted body is local.
+- Prisma direct seed is allowed for bulk fixtures (see `customers/customers-pagination.spec.ts`); still clean up in `finally` / after hooks. No DELETE route → Prisma/`conn` cleanup is fine (`partners/partners.spec.ts`).
### Error / table-driven cases
@@ -148,6 +152,15 @@ for (const { name, body, expected } of errorCases) {
Optional: validate richer payloads with Zod (`.parse(...)`) like `workspaces/workspaces.spec.ts` / enriched customer fields.
+## Migrating Vitest API tests
+
+When converting `apps/web/tests/<resource>/*.test.ts`:
+
+1. Add or extend `playwright/api/<resource>/<resource>.spec.ts` — do not leave a parallel Vitest HTTP spec.
+2. Map `IntegrationHarness` / `http.post({ path })` → `api` fixture (`/api/...` paths).
+3. Replace `E2E_*` / `E2E_PARTNER_GROUP` with `{ workspace }`, `{ program }`, and `TEST_WORKSPACE`.
+4. Delete the Vitest file after the Playwright spec covers its cases.
+
## Do not
- Call `setupTestWorkspace` from specs (only `globalSetup`).
@@ -155,6 +168,8 @@ Optional: validate richer payloads with Zod (`.parse(...)`) like `workspaces/wor
- Commit secrets or change the fixed Playwright token unless intentionally rotating local/CI test auth.
- Skip cleanup (parallel API project will leak / flake).
- Run `pnpm build` after adding tests.
+- Poll or `setTimeout` for R2/storage/`waitUntil` side effects (no `STORAGE_*` in CI). Assert the immediate JSON body instead (e.g. foreign `image` URLs stay `null` on create).
+- Copy Vitest `IntegrationHarness` or `E2E_*` constants into Playwright specs.
## Run
diff --git a/apps/web/playwright/api/partners/partners.spec.ts b/apps/web/playwright/api/partners/partners.spec.ts
index 2731af9d94..1fc27831ac 100644
--- a/apps/web/playwright/api/partners/partners.spec.ts
+++ b/apps/web/playwright/api/partners/partners.spec.ts
@@ -1,15 +1,42 @@
import { conn } from "@/lib/planetscale";
import { prisma } from "@/lib/prisma";
import type { EnrolledPartnerProps } from "@/lib/types";
+import { EnrolledPartnerSchema as EnrolledPartnerSchemaDate } from "@/lib/zod/schemas/partners";
+import { nanoid } from "@dub/utils";
import { expect } from "@playwright/test";
+import slugify from "@sindresorhus/slugify";
+import * as z from "zod/v4";
import { randomName, randomPartnerEmail } from "../../utils";
-import { test } from "../fixtures";
+import { test, type ApiClient } from "../fixtures";
import { TEST_WORKSPACE } from "../setup-test-workspace";
test.describe.configure({
mode: "parallel",
});
+const EnrolledPartnerSchema = EnrolledPartnerSchemaDate.extend({
+ createdAt: z.string(),
+ bannedAt: z.string().nullish(),
+ payoutsEnabledAt: z.string().nullish(),
+ identityVerifiedAt: z.string().nullish(),
+ trustedAt: z.string().nullish(),
+});
+
+function reEscape(s: string) {
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+}
+
+async function createPartner(
+ api: ApiClient,
+ overrides: Record<string, unknown> = {},
+) {
+ return api.post<EnrolledPartnerProps>("/api/partners", {
+ name: randomName(),
+ email: randomPartnerEmail(),
+ ...overrides,
+ });
+}
+
async function deletePartner(partnerId: string | undefined) {
if (!partnerId) return;
@@ -46,18 +73,24 @@ test("POST /partners", async ({ api, program }) => {
partnerId = data.id;
expect(status).toEqual(201);
- expect(data).toMatchObject({
+ const parsed = EnrolledPartnerSchema.parse(data);
+ expect(parsed).toMatchObject({
id: expect.any(String),
name: body.name,
email: body.email,
programId: program.id,
status: "approved",
});
- expect(data.links).toEqual(
+ expect(parsed.links).toEqual(
expect.arrayContaining([
expect.objectContaining({
domain: TEST_WORKSPACE.program.domain,
- url: expect.stringMatching(/^https?:\/\//),
+ url: expect.stringMatching(
+ new RegExp(`^${reEscape(TEST_WORKSPACE.program.url)}/?$`),
+ ),
+ shortLink: expect.stringMatching(
+ new RegExp(`^https://${reEscape(TEST_WORKSPACE.program.domain)}/`),
+ ),
clicks: 0,
leads: 0,
sales: 0,
@@ -69,3 +102,165 @@ test("POST /partners", async ({ api, program }) => {
await deletePartner(partnerId);
}
});
+
+test("POST /partners – all fields", async ({ api, program }) => {
+ let partnerId: string | undefined;
+ const tenantId = nanoid();
+
+ try {
+ const body = {
+ name: randomName(),
+ email: randomPartnerEmail(),
+ tenantId,
+ groupId: program.defaultGroupId,
+ description: "A description of the partner",
+ country: "US",
+ };
+
+ const { status, data } = await api.post<EnrolledPartnerProps>(
+ "/api/partners",
+ {
+ ...body,
+ image: `https://api.dicebear.com/9.x/micah/png?seed=${tenantId}`,
+ },
+ );
+ partnerId = data.id;
+
+ expect(status).toEqual(201);
+ const parsed = EnrolledPartnerSchema.parse(data);
+ expect(parsed).toMatchObject({
+ name: body.name,
+ email: body.email,
+ tenantId: body.tenantId,
+ description: body.description,
+ country: body.country,
+ image: null,
+ });
+ } finally {
+ await deletePartner(partnerId);
+ }
+});
+
+test("POST /partners – username", async ({ api }) => {
+ let partnerId: string | undefined;
+ const username = nanoid();
+
+ try {
+ const { status, data } = await createPartner(api, { username });
+ partnerId = data.id;
+
+ expect(status).toEqual(201);
+ const parsed = EnrolledPartnerSchema.parse(data);
+ const keyRe = new RegExp(`^${reEscape(username)}(-[a-z0-9]{4})?$`);
+ expect(parsed.links).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ key: expect.stringMatching(keyRe),
+ shortLink: expect.stringMatching(
+ new RegExp(
+ `^https://${reEscape(TEST_WORKSPACE.program.domain)}/${reEscape(username)}(-[a-z0-9]{4})?$`,
+ ),
+ ),
+ }),
+ ]),
+ );
+ } finally {
+ await deletePartner(partnerId);
+ }
+});
+
+test("POST /partners – invalid username", async ({ api }) => {
+ expect(
+ await api.post("/api/partners", {
+ email: randomPartnerEmail(),
+ username: "invalid username",
+ }),
+ ).toEqual({
+ status: 422,
+ data: {
+ error: {
+ code: "unprocessable_entity",
+ message:
+ "custom: username: Invalid username. Must be a URL-friendly string.",
+ doc_url:
+ "https://dub.co/docs/api-reference/errors#unprocessable-entity",
+ },
+ },
+ });
+});
+
+test("POST /partners – linkProps.prefix on default link", async ({
+ api,
+ program,
+}) => {
+ let partnerId: string | undefined;
+ const email = randomPartnerEmail();
+ const identitySlug = slugify(email.split("@")[0]);
+ const prefixedKeyRe = new RegExp(
+ `^c/${reEscape(identitySlug)}(-[a-z0-9]{4})?$`,
+ );
+
+ try {
+ const { status, data } = await api.post<EnrolledPartnerProps>(
+ "/api/partners",
+ {
+ email,
+ groupId: program.defaultGroupId,
+ linkProps: { prefix: "/c/" },
+ },
+ );
+ partnerId = data.id;
+
+ expect(status).toEqual(201);
+ const parsed = EnrolledPartnerSchema.parse(data);
+ expect(parsed.links?.length).toBeGreaterThanOrEqual(1);
+ for (const link of parsed.links!) {
+ expect(link.key).toMatch(prefixedKeyRe);
+ expect(link.shortLink).toBe(`https://${link.domain}/${link.key}`);
+ }
+ } finally {
+ await deletePartner(partnerId);
+ }
+});
+
+test("POST /partners – upsert tenantId on existing partner", async ({
+ api,
+ program,
+}) => {
+ let partnerId: string | undefined;
+
+ try {
+ const email = randomPartnerEmail();
+ const { status: firstStatus, data: firstData } = await createPartner(api, {
+ email,
+ groupId: program.defaultGroupId,
+ });
+ partnerId = firstData.id;
+
+ expect(firstStatus).toEqual(201);
+ const firstParsed = EnrolledPartnerSchema.parse(firstData);
+ expect(firstParsed).toMatchObject({
+ email,
+ tenantId: null,
+ });
+
+ const tenantId = nanoid();
+ const { status: secondStatus, data: secondData } = await createPartner(
+ api,
+ {
+ email,
+ tenantId,
+ },
+ );
+
+ expect(secondStatus).toEqual(201);
+ const secondParsed = EnrolledPartnerSchema.parse(secondData);
+ expect(secondParsed).toMatchObject({
+ id: firstParsed.id,
+ email,
+ tenantId,
+ });
+ } finally {
+ await deletePartner(partnerId);
+ }
+});
diff --git a/apps/web/tests/partners/create-partner.test.ts b/apps/web/tests/partners/create-partner.test.ts
deleted file mode 100644
index fdc18a0751..0000000000
--- a/apps/web/tests/partners/create-partner.test.ts
+++ /dev/null
@@ -1,211 +0,0 @@
-import { generateRandomName } from "@/lib/names";
-import { EnrolledPartnerSchema as EnrolledPartnerSchemaDate } from "@/lib/zod/schemas/partners";
-import { R2_URL } from "@dub/utils";
-import { Partner } from "@prisma/client";
-import slugify from "@sindresorhus/slugify";
-import { describe, expect, test } from "vitest";
-import { randomId, randomPartnerEmail } from "../utils/helpers";
-import { IntegrationHarness } from "../utils/integration";
-import { E2E_PARTNER_GROUP, E2E_PROGRAM } from "../utils/resource";
-import { normalizedPartnerDateFields } from "./resource";
-
-function reEscape(s: string) {
- return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
-}
-
-const EnrolledPartnerSchema = EnrolledPartnerSchemaDate.extend(
- normalizedPartnerDateFields.shape,
-);
-
-describe.sequential("POST /partners", async () => {
- const h = new IntegrationHarness();
- const { http } = await h.init();
-
- test("with required fields only", async () => {
- const partner = {
- name: generateRandomName(),
- email: randomPartnerEmail(),
- groupId: E2E_PARTNER_GROUP.id,
- };
-
- const { data, status } = await http.post<Partner>({
- path: "/partners",
- body: partner,
- });
-
- expect(status).toEqual(201);
- const parsed = EnrolledPartnerSchema.parse(data);
- expect(parsed.name).toBe(partner.name);
- expect(parsed.email).toBe(partner.email);
- });
-
- test("with all fields", async () => {
- const partner = {
- name: generateRandomName(),
- email: randomPartnerEmail(),
- tenantId: randomId(),
- groupId: E2E_PARTNER_GROUP.id,
- description: "A description of the partner",
- country: "US",
- };
-
- const { data, status } = await http.post<Partner>({
- path: "/partners",
- body: {
- ...partner,
- image: `https://api.dicebear.com/9.x/micah/png?seed=${partner.tenantId}`,
- },
- });
-
- expect(status).toEqual(201);
- const parsed = EnrolledPartnerSchema.parse(data);
- expect(parsed.name).toBe(partner.name);
- expect(parsed.email).toBe(partner.email);
- expect(parsed.tenantId).toBe(partner.tenantId);
- expect(parsed.description).toBe(partner.description);
- expect(parsed.country).toBe(partner.country);
-
- // wait 2.5s, and then request the partners/[partnerId] endpoint
- await new Promise((resolve) => setTimeout(resolve, 2500));
- const { data: partnerData } = await http.get<Partner>({
- path: `/partners/${data.id}`,
- });
-
- // make sure the image is successfully stored in R2
- expect(partnerData.image).toMatch(
- new RegExp(`^${R2_URL}/partners/${data.id}/image_.*`),
- );
- });
-
- test("with partner.username field", async () => {
- const username = randomId();
-
- const partner = {
- name: generateRandomName(),
- email: randomPartnerEmail(),
- groupId: E2E_PARTNER_GROUP.id,
- };
-
- const { data, status } = await http.post<Partner>({
- path: "/partners",
- body: {
- username,
- ...partner,
- },
- });
-
- expect(status).toEqual(201);
- const parsed = EnrolledPartnerSchema.parse(data);
- expect(parsed.name).toBe(partner.name);
- expect(parsed.email).toBe(partner.email);
- const keyRe = new RegExp(`^${reEscape(username)}(-[a-z0-9]{4})?$`);
- expect(parsed.links).toEqual(
- expect.arrayContaining([
- expect.objectContaining({
- domain: E2E_PROGRAM.domain,
- url: expect.stringMatching(/^https?:\/\//),
- key: expect.stringMatching(keyRe),
- shortLink: expect.stringMatching(
- new RegExp(
- `^https://${reEscape(E2E_PROGRAM.domain)}/${reEscape(username)}(-[a-z0-9]{4})?$`,
- ),
- ),
- clicks: 0,
- leads: 0,
- sales: 0,
- saleAmount: 0,
- }),
- ]),
- );
- });
-
- test("with invalid partner.username field", async () => {
- const { status, data } = await http.post<Partner>({
- path: "/partners",
- body: {
- email: randomPartnerEmail(),
- username: "invalid username",
- },
- });
- expect(status).toEqual(422);
- expect(data).toStrictEqual({
- error: {
- code: "unprocessable_entity",
- message:
- "custom: username: Invalid username. Must be a URL-friendly string.",
- doc_url:
- "https://dub.co/docs/api-reference/errors#unprocessable-entity",
- },
- });
- });
-
- test("with linkProps.prefix on default link", async () => {
- const id = randomId();
- const email = `prefix-e2e-${id}@example.com`;
- const identitySlug = slugify(email.split("@")[0]);
- const prefixedKeyRe = new RegExp(
- `^c/${reEscape(identitySlug)}(-[a-z0-9]{4})?$`,
- );
-
- const { data, status } = await http.post<Partner>({
- path: "/partners",
- body: {
- email,
- groupId: E2E_PARTNER_GROUP.id,
- linkProps: { prefix: "/c/" },
- },
- });
-
- expect(status).toEqual(201);
- const parsed = EnrolledPartnerSchema.parse(data);
- expect(parsed.links?.length).toBeGreaterThanOrEqual(1);
- for (const link of parsed.links!) {
- expect(link.key).toMatch(prefixedKeyRe);
- expect(link.shortLink).toBe(`https://${link.domain}/${link.key}`);
- }
- });
-
- test("upsert behavior - update existing partner with tenantId", async () => {
- const email = randomPartnerEmail();
-
- // First, create a partner with email and no tenantId
- const initialPartner = {
- email,
- name: generateRandomName(),
- groupId: E2E_PARTNER_GROUP.id,
- };
-
- const { data: firstData, status: firstStatus } = await http.post<Partner>({
- path: "/partners",
- body: initialPartner,
- });
-
- expect(firstStatus).toEqual(201);
-
- const firstParsed = EnrolledPartnerSchema.parse(firstData);
- expect(firstParsed.name).toBe(initialPartner.name);
- expect(firstParsed.email).toBe(initialPartner.email);
- expect(firstParsed.tenantId).toBeNull();
-
- // Then, create the same partner with the same email but with a tenantId
- const updatedPartner = {
- email,
- tenantId: randomId(),
- };
-
- const { data: secondData, status: secondStatus } = await http.post<Partner>(
- {
- path: "/partners",
- body: updatedPartner,
- },
- );
-
- expect(secondStatus).toEqual(201);
- const secondParsed = EnrolledPartnerSchema.parse(secondData);
-
- // Should be the same partner (same ID) but with updated fields
- expect(secondParsed.id).toBe(firstParsed.id);
- expect(secondParsed.email).toBe(email);
- expect(secondParsed.tenantId).toBe(updatedPartner.tenantId);
- });
-});