Skip to content

Open-source document signature platform. Not affiliated with DocuSign.

TypeScript

Add a Playwright end-to-end test of the signing flow

Clauded743058e9cbe
diff --git a/e2e/global-setup.ts b/e2e/global-setup.ts
new file mode 100644
index 0000000..1980df7
--- /dev/null
+++ b/e2e/global-setup.ts
@@ -0,0 +1,67 @@
+import { execFileSync } from "node:child_process";
+import { rm } from "node:fs/promises";
+
+import pg from "pg";
+
+import { e2eDataDir, e2eDatabaseUrl } from "../playwright.config";
+
+function assertDisposableDatabase(connectionString: string) {
+ const databaseName = new URL(connectionString).pathname.replace(/^\//, "");
+
+ if (!databaseName.toLowerCase().includes("e2e")) {
+ throw new Error(
+ `Refusing to wipe database "${databaseName}". The end-to-end test database must have "e2e" in its name.`,
+ );
+ }
+}
+
+async function ensureDatabaseExists(connectionString: string) {
+ const targetUrl = new URL(connectionString);
+ const databaseName = targetUrl.pathname.replace(/^\//, "");
+ const adminUrl = new URL(connectionString);
+
+ adminUrl.pathname = "/postgres";
+
+ const client = new pg.Client({ connectionString: adminUrl.toString() });
+
+ try {
+ await client.connect();
+
+ const existing = await client.query(
+ "select 1 from pg_database where datname = $1",
+ [databaseName],
+ );
+
+ if (existing.rowCount === 0) {
+ await client.query(`create database "${databaseName}"`);
+ }
+ } catch {
+ // No access to the maintenance database: assume the test database was
+ // created some other way and let the reset below report any real problem.
+ } finally {
+ await client.end().catch(() => undefined);
+ }
+}
+
+export default async function globalSetup() {
+ assertDisposableDatabase(e2eDatabaseUrl);
+ await ensureDatabaseExists(e2eDatabaseUrl);
+
+ const client = new pg.Client({ connectionString: e2eDatabaseUrl });
+
+ await client.connect();
+
+ try {
+ await client.query("drop schema if exists public cascade");
+ await client.query("create schema public");
+ } finally {
+ await client.end();
+ }
+
+ execFileSync(process.execPath, ["db/migrate.mjs"], {
+ env: { ...process.env, DATABASE_URL: e2eDatabaseUrl },
+ stdio: "inherit",
+ });
+
+ await rm(e2eDataDir, { force: true, recursive: true });
+}
diff --git a/e2e/signing-flow.spec.ts b/e2e/signing-flow.spec.ts
new file mode 100644
index 0000000..2ad56fc
--- /dev/null
+++ b/e2e/signing-flow.spec.ts
@@ -0,0 +1,201 @@
+import { expect, test, type Page } from "@playwright/test";
+
+import { extractLink, extractLinks, waitForEmail } from "./support/outbox";
+import { writeSamplePdf } from "./support/sample-pdf";
+
+const PASSWORD = "correct horse battery staple 42";
+const ENVELOPE_TITLE = "E2E sample agreement";
+
+function watchForContentSecurityPolicyViolations(page: Page, sink: string[]) {
+ page.on("console", (message) => {
+ const text = message.text();
+
+ if (/content security policy/i.test(text)) {
+ sink.push(text);
+ }
+ });
+}
+
+async function expectPdfResponse(response: {
+ body(): Promise<Buffer>;
+ headers(): Record<string, string>;
+ status(): number;
+}) {
+ expect(response.status()).toBe(200);
+ expect(response.headers()["content-type"]).toContain("application/pdf");
+ expect(response.headers()["content-disposition"]).toContain("attachment");
+ expect((await response.body()).subarray(0, 5).toString()).toBe("%PDF-");
+}
+
+test("a sender can send a PDF and a recipient can sign it", async ({
+ browser,
+ page,
+}, testInfo) => {
+ const runId = String(Date.now());
+ const senderEmail = `sender+${runId}@example.com`;
+ const signerEmail = `signer+${runId}@example.com`;
+ const cspViolations: string[] = [];
+ let envelopeId = "";
+
+ watchForContentSecurityPolicyViolations(page, cspViolations);
+
+ await test.step("sign up and verify the email address", async () => {
+ await page.goto("/signup");
+ await page.getByLabel("Full name").fill("Sam Sender");
+ await page.getByLabel("Email").fill(senderEmail);
+ await page.getByLabel("Password").fill(PASSWORD);
+ await page.getByRole("button", { name: "Sign up" }).click();
+ await expect(
+ page.getByText("Check your email to verify your sender account."),
+ ).toBeVisible();
+
+ const verificationEmail = await waitForEmail({
+ template: "email_verification",
+ to: senderEmail,
+ });
+
+ await page.goto(
+ extractLink(verificationEmail.text, "/api/auth/verify-email"),
+ );
+ await expect(page).toHaveURL(/\/login/);
+ });
+
+ await test.step("log in", async () => {
+ await page.getByLabel("Email").fill(senderEmail);
+ await page.getByLabel("Password").fill(PASSWORD);
+ await page.getByRole("button", { name: "Log in" }).click();
+ await expect(page).toHaveURL(/\/dashboard$/);
+ await expect(
+ page.getByRole("heading", { name: "No documents yet" }),
+ ).toBeVisible();
+ });
+
+ await test.step("upload a PDF", async () => {
+ const pdfPath = await writeSamplePdf(testInfo.outputPath("sample.pdf"));
+
+ await page.goto("/envelopes/new");
+ await page.getByLabel("Envelope title").fill(ENVELOPE_TITLE);
+ await page.getByLabel("Upload PDF").setInputFiles(pdfPath);
+ await expect(page.getByText("sample.pdf")).toBeVisible();
+ await page.getByRole("button", { name: "Next ->" }).click();
+ await expect(page).toHaveURL(/\/envelopes\/[^/]+\/signers$/);
+
+ envelopeId = /\/envelopes\/([^/]+)\/signers$/.exec(page.url())?.[1] ?? "";
+ expect(envelopeId).not.toBe("");
+ });
+
+ await test.step("add a signer", async () => {
+ await page.getByLabel("Signer 1 name").fill("Riley Recipient");
+ await page.getByLabel("Signer 1 email").fill(signerEmail);
+ await page.getByRole("button", { name: "Next →" }).click();
+ await expect(page).toHaveURL(/\/prepare$/);
+ });
+
+ await test.step("place a signature field on the rendered page", async () => {
+ await expect(
+ page.getByRole("img", { name: "Rendered PDF page 1" }),
+ ).toBeVisible();
+ await page.getByRole("button", { exact: true, name: "Signature" }).click();
+
+ const placementTarget = page.getByLabel("Place Signature on page 1");
+ const box = await placementTarget.boundingBox();
+
+ expect(box).not.toBeNull();
+ await placementTarget.click({
+ position: { x: box!.width * 0.3, y: box!.height * 0.7 },
+ });
+ await expect(
+ page.getByRole("button", { name: "Riley Recipient · Sign" }),
+ ).toBeVisible();
+ await expect(page.getByText("Signature ready")).toBeVisible();
+ await expect(page.getByRole("status")).toHaveText("Saved");
+ await page.getByRole("button", { name: "Next →" }).click();
+ await expect(page).toHaveURL(/\/review$/);
+ });
+
+ await test.step("review and send", async () => {
+ await expect(
+ page.getByRole("heading", { name: ENVELOPE_TITLE }),
+ ).toBeVisible();
+ await page.getByRole("button", { name: "Send envelope" }).click();
+
+ const confirmation = page.getByRole("dialog", {
+ name: "Send this envelope?",
+ });
+
+ await confirmation.getByRole("checkbox").check();
+ await confirmation.getByRole("button", { name: "Send now" }).click();
+ });
+
+ const invitation = await waitForEmail({
+ template: "signing_invitation",
+ to: signerEmail,
+ });
+ const signingLink = extractLink(invitation.text, "/sign/");
+
+ await test.step("the recipient signs without an account", async () => {
+ const recipientContext = await browser.newContext({
+ viewport: { height: 900, width: 1440 },
+ });
+ const recipientPage = await recipientContext.newPage();
+
+ watchForContentSecurityPolicyViolations(recipientPage, cspViolations);
+
+ await recipientPage.goto(signingLink);
+ await expect(
+ recipientPage.getByRole("img", { name: "Rendered PDF page 1" }),
+ ).toBeVisible();
+ await expect(recipientPage.getByText("1 required remaining")).toBeVisible();
+ await recipientPage
+ .getByRole("button", { exact: true, name: "Signature" })
+ .click();
+ await recipientPage
+ .getByRole("dialog", { name: "Add your signature" })
+ .getByRole("button", { name: "Apply signature" })
+ .click();
+ await recipientPage.getByRole("button", { name: "Finish" }).click();
+ await recipientPage
+ .getByRole("dialog", { name: "Finish signing?" })
+ .getByRole("button", { name: "Finish signing" })
+ .click();
+ await expect(recipientPage).toHaveURL(/\/sign\/[^/]+\/done/);
+
+ const completionEmail = await waitForEmail({
+ template: "completion_notification",
+ to: signerEmail,
+ });
+ const downloadLinks = extractLinks(completionEmail.text).filter((link) =>
+ new URL(link).pathname.startsWith("/api/download/"),
+ );
+
+ expect(downloadLinks.length).toBeGreaterThanOrEqual(1);
+
+ for (const downloadLink of downloadLinks) {
+ await expectPdfResponse(await recipientContext.request.get(downloadLink));
+ }
+
+ await recipientContext.close();
+ });
+
+ await test.step("the sender sees it completed and can download", async () => {
+ await waitForEmail({
+ template: "completion_notification",
+ to: senderEmail,
+ });
+ await page.goto(`/envelopes/${envelopeId}`);
+ await expect(page.getByText("Completed", { exact: true })).toBeVisible();
+ await expect(
+ page.getByRole("button", { name: "Download signed PDF" }),
+ ).toBeVisible();
+
+ for (const type of ["signed", "evidence"]) {
+ await expectPdfResponse(
+ await page.request.get(
+ `/api/envelopes/${envelopeId}/download?type=${type}`,
+ ),
+ );
+ }
+ });
+
+ expect(cspViolations).toEqual([]);
+});
diff --git a/e2e/support/outbox.ts b/e2e/support/outbox.ts
new file mode 100644
index 0000000..567dfc0
--- /dev/null
+++ b/e2e/support/outbox.ts
@@ -0,0 +1,80 @@
+import { readdir, readFile } from "node:fs/promises";
+import path from "node:path";
+
+import { e2eOutboxDir } from "../../playwright.config";
+
+export type CapturedEmail = {
+ subject: string;
+ template: string;
+ text: string;
+ to: string[];
+};
+
+async function readOutbox(): Promise<CapturedEmail[]> {
+ let fileNames: string[];
+
+ try {
+ fileNames = await readdir(e2eOutboxDir);
+ } catch {
+ return [];
+ }
+
+ const emails = await Promise.all(
+ fileNames
+ .filter((fileName) => fileName.endsWith(".json"))
+ .sort()
+ .map(
+ async (fileName) =>
+ JSON.parse(
+ await readFile(path.join(e2eOutboxDir, fileName), "utf8"),
+ ) as CapturedEmail,
+ ),
+ );
+
+ return emails;
+}
+
+/** Waits for the newest captured email with this template and recipient. */
+export async function waitForEmail(
+ input: { template: string; to: string },
+ timeoutMs = 30_000,
+): Promise<CapturedEmail> {
+ const deadline = Date.now() + timeoutMs;
+
+ for (;;) {
+ const match = (await readOutbox())
+ .reverse()
+ .find(
+ (email) =>
+ email.template === input.template && email.to.includes(input.to),
+ );
+
+ if (match) {
+ return match;
+ }
+
+ if (Date.now() > deadline) {
+ throw new Error(
+ `No "${input.template}" email for ${input.to} within ${String(timeoutMs)} ms.`,
+ );
+ }
+
+ await new Promise((resolve) => setTimeout(resolve, 250));
+ }
+}
+
+export function extractLinks(text: string): string[] {
+ return text.match(/https?:\/\/[^\s<>"]+/g) ?? [];
+}
+
+export function extractLink(text: string, pathPrefix: string): string {
+ const link = extractLinks(text).find((candidate) =>
+ new URL(candidate).pathname.startsWith(pathPrefix),
+ );
+
+ if (!link) {
+ throw new Error(`No link starting with ${pathPrefix} in the email.`);
+ }
+
+ return link;
+}
diff --git a/e2e/support/sample-pdf.ts b/e2e/support/sample-pdf.ts
new file mode 100644
index 0000000..91d272a
--- /dev/null
+++ b/e2e/support/sample-pdf.ts
@@ -0,0 +1,30 @@
+import { writeFile } from "node:fs/promises";
+
+import { PDFDocument, StandardFonts } from "pdf-lib";
+
+/** Writes a small two-page PDF and returns its path. */
+export async function writeSamplePdf(filePath: string): Promise<string> {
+ const document = await PDFDocument.create();
+ const font = await document.embedFont(StandardFonts.Helvetica);
+
+ for (const pageNumber of [1, 2]) {
+ const page = document.addPage([612, 792]);
+
+ page.drawText(`Sample agreement, page ${String(pageNumber)}`, {
+ font,
+ size: 18,
+ x: 72,
+ y: 700,
+ });
+ page.drawText("Signature: ______________________", {
+ font,
+ size: 12,
+ x: 72,
+ y: 200,
+ });
+ }
+
+ await writeFile(filePath, await document.save());
+
+ return filePath;
+}
diff --git a/package-lock.json b/package-lock.json
index def008a..756ee28 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -30,6 +30,7 @@
"zod": "^4.3.6"
},
"devDependencies": {
+ "@playwright/test": "1.63.0",
"@tailwindcss/postcss": "^4",
"@types/node": "^20",
"@types/pg": "^8.20.0",
@@ -3162,9 +3163,8 @@
"version": "1.63.0",
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.63.0.tgz",
"integrity": "sha512-oxMK4vllB9RK5NQ2l1pq1IfOf2AvnEuj/vYGDj0H2nMtmtZpKtCwt/l00GEO6xjGfpBNAvjovvYdCm50dRQkpQ==",
+ "devOptional": true,
"license": "Apache-2.0",
- "optional": true,
- "peer": true,
"dependencies": {
"playwright": "1.63.0"
},
@@ -5675,70 +5675,6 @@
"node": ">=14.0.0"
}
},
- "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core": {
- "version": "1.8.1",
- "dev": true,
- "inBundle": true,
- "license": "MIT",
- "optional": true,
- "dependencies": {
- "@emnapi/wasi-threads": "1.1.0",
- "tslib": "^2.4.0"
- }
- },
- "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime": {
- "version": "1.8.1",
- "dev": true,
- "inBundle": true,
- "license": "MIT",
- "optional": true,
- "dependencies": {
- "tslib": "^2.4.0"
- }
- },
- "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads": {
- "version": "1.1.0",
- "dev": true,
- "inBundle": true,
- "license": "MIT",
- "optional": true,
- "dependencies": {
- "tslib": "^2.4.0"
- }
- },
- "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime": {
- "version": "1.1.1",
- "dev": true,
- "inBundle": true,
- "license": "MIT",
- "optional": true,
- "dependencies": {
- "@emnapi/core": "^1.7.1",
- "@emnapi/runtime": "^1.7.1",
- "@tybys/wasm-util": "^0.10.1"
- },
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/Brooooooklyn"
- }
- },
- "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util": {
- "version": "0.10.1",
- "dev": true,
- "inBundle": true,
- "license": "MIT",
- "optional": true,
- "dependencies": {
- "tslib": "^2.4.0"
- }
- },
- "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib": {
- "version": "2.8.1",
- "dev": true,
- "inBundle": true,
- "license": "0BSD",
- "optional": true
- },
"node_modules/@tailwindcss/oxide-win32-arm64-msvc": {
"version": "4.2.2",
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.2.2.tgz",
@@ -11790,9 +11726,8 @@
"version": "1.63.0",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.63.0.tgz",
"integrity": "sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==",
+ "devOptional": true,
"license": "Apache-2.0",
- "optional": true,
- "peer": true,
"dependencies": {
"playwright-core": "1.63.0"
},
@@ -11807,9 +11742,8 @@
"version": "1.63.0",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz",
"integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==",
+ "devOptional": true,
"license": "Apache-2.0",
- "optional": true,
- "peer": true,
"bin": {
"playwright-core": "cli.js"
},
diff --git a/package.json b/package.json
index 6223b6c..08a5758 100644
--- a/package.json
+++ b/package.json
@@ -15,7 +15,8 @@
"typecheck": "next typegen && tsc --noEmit --incremental false",
"lint": "eslint .",
"format": "prettier --write .",
- "format:check": "prettier --check ."
+ "format:check": "prettier --check .",
+ "test:e2e": "playwright test"
},
"dependencies": {
"@aws-sdk/client-s3": "^3.1012.0",
@@ -39,6 +40,7 @@
"zod": "^4.3.6"
},
"devDependencies": {
+ "@playwright/test": "1.63.0",
"@tailwindcss/postcss": "^4",
"@types/node": "^20",
"@types/pg": "^8.20.0",
diff --git a/playwright.config.ts b/playwright.config.ts
new file mode 100644
index 0000000..ab3922e
--- /dev/null
+++ b/playwright.config.ts
@@ -0,0 +1,61 @@
+import path from "node:path";
+
+import { defineConfig, devices } from "@playwright/test";
+
+// One end-to-end test that walks the whole product against a real Postgres,
+// with files on local disk and emails captured to JSON instead of sent.
+//
+// npm run db:start (once, for a local Postgres)
+// npm run test:e2e
+//
+// The test database is wiped on every run. It must have "e2e" in its name.
+const port = Number(process.env.E2E_PORT ?? 3100);
+const baseURL = `http://localhost:${String(port)}`;
+
+export const e2eDatabaseUrl =
+ process.env.E2E_DATABASE_URL ??
+ "postgres://signudoc:[email protected]:5432/signudoc_e2e";
+export const e2eDataDir = path.resolve(".data", "e2e");
+export const e2eOutboxDir = path.join(e2eDataDir, "outbox");
+
+export default defineConfig({
+ expect: { timeout: 20_000 },
+ forbidOnly: Boolean(process.env.CI),
+ fullyParallel: false,
+ globalSetup: "./e2e/global-setup.ts",
+ projects: [
+ {
+ name: "chromium",
+ use: {
+ ...devices["Desktop Chrome"],
+ viewport: { height: 900, width: 1440 },
+ },
+ },
+ ],
+ reporter: process.env.CI ? [["github"], ["list"]] : "list",
+ retries: process.env.CI ? 1 : 0,
+ testDir: "./e2e",
+ timeout: 180_000,
+ use: {
+ baseURL,
+ trace: "retain-on-failure",
+ },
+ webServer: {
+ command: `npx next dev --port ${String(port)}`,
+ env: {
+ APP_URL: baseURL,
+ BETTER_AUTH_SECRET: "e2e-only-secret-not-used-anywhere-else-0123456789",
+ BETTER_AUTH_URL: baseURL,
+ DATABASE_URL: e2eDatabaseUrl,
+ EMAIL_CAPTURE_DIR: e2eOutboxDir,
+ EMAIL_DRIVER: "capture",
+ NEXT_TELEMETRY_DISABLED: "1",
+ STORAGE_DRIVER: "local",
+ STORAGE_LOCAL_DIR: path.join(e2eDataDir, "storage"),
+ },
+ reuseExistingServer: false,
+ timeout: 180_000,
+ url: `${baseURL}/login`,
+ },
+ workers: 1,
+});