Skip to content

Commit 41b5714

Browse files
AlexMari0claude
andcommitted
Add Playwright end-to-end tests for public and Company flows
- 14 Chromium tests (make e2e) against a separate stack: API :8090 on job-portal-e2e, production Next.js build on :3100, reseeded per file - api: local disk uploader (LOCAL_UPLOAD_DIR, served at /uploads/) as a Cloudinary stand-in for development and e2e - pin @clerk/nextjs to 7.9.23: 7.9.24+ breaks Partial Prerender resume (clerk/javascript#10700), forcing full client rendering; guarded by a test that fails on React error #419 - fix hover menus (status, logout) that covered their own trigger Refs #25 Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 24826fc commit 41b5714

19 files changed

Lines changed: 550 additions & 19 deletions

File tree

‎Makefile‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
.PHONY: dev db db-stop seed api web test api-types
1+
.PHONY: dev db db-stop seed api web test api-types e2e
22

33
# Start everything: MongoDB (Docker), Go API with hot reload, Next.js.
44
dev: db
@@ -28,3 +28,8 @@ test: db
2828
# Regenerate web/src/lib/api-types.ts after editing api/openapi.yaml.
2929
api-types:
3030
cd web && npm run gen:api
31+
32+
# Browser tests (Playwright) against a separate stack: API :8090, web :3100,
33+
# database job-portal-e2e, uploads on disk. First run: cd web && npx playwright install chromium
34+
e2e: db
35+
cd web && npm run e2e

‎api/.env.example‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,3 +27,9 @@ COMPANY_JWT_SECRET=
2727
# Sentry error reporting. Leave empty locally; set in staging/production.
2828
SENTRY_DSN=
2929
SENTRY_ENVIRONMENT=development
30+
31+
# Development alternative to Cloudinary: store uploads on disk and serve them
32+
# at PUBLIC_URL/uploads/ (used only when CLOUDINARY_CLOUD_NAME is empty).
33+
LOCAL_UPLOAD_DIR=
34+
# This API's origin as browsers see it (default http://localhost:$PORT).
35+
PUBLIC_URL=

‎api/cmd/api/main.go‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -73,14 +73,23 @@ func run() error {
7373
}
7474

7575
var uploader handler.Uploader
76-
if cfg.CloudinaryCloudName != "" {
76+
var files http.Handler
77+
switch {
78+
case cfg.CloudinaryCloudName != "":
7779
cld, err := upload.NewCloudinary(cfg.CloudinaryCloudName, cfg.CloudinaryAPIKey, cfg.CloudinaryAPISecret)
7880
if err != nil {
7981
return err
8082
}
8183
uploader = cld
82-
} else {
83-
slog.Warn("CLOUDINARY_CLOUD_NAME not set: upload routes return 503")
84+
case cfg.LocalUploadDir != "":
85+
local, err := upload.NewLocal(cfg.LocalUploadDir, cfg.PublicURL)
86+
if err != nil {
87+
return err
88+
}
89+
uploader, files = local, local.Handler()
90+
slog.Info("uploads stored on disk (development only)", "dir", cfg.LocalUploadDir)
91+
default:
92+
slog.Warn("neither CLOUDINARY_CLOUD_NAME nor LOCAL_UPLOAD_DIR set: upload routes return 503")
8493
}
8594

8695
var companyTokens *auth.CompanyTokens
@@ -98,6 +107,7 @@ func run() error {
98107
CandidateAuth: candidateAuth,
99108
FetchClerkUser: fetchClerkUser,
100109
Uploader: uploader,
110+
Files: files,
101111
CompanyTokens: companyTokens,
102112
})),
103113
ReadHeaderTimeout: 5 * time.Second,

‎api/internal/config/config.go‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,12 @@ type Config struct {
2222
// WebOrigin is the Next.js site's origin; Clerk tokens must be issued for it (azp).
2323
WebOrigin string
2424

25+
// LocalUploadDir stores uploads on disk instead of Cloudinary (development
26+
// and end-to-end tests). Used only when Cloudinary is not configured.
27+
LocalUploadDir string
28+
// PublicURL is this API's origin as browsers see it, for local upload URLs.
29+
PublicURL string
30+
2531
// Cloudinary account for uploads; all three empty disables uploads.
2632
CloudinaryCloudName string
2733
CloudinaryAPIKey string
@@ -40,15 +46,19 @@ type Config struct {
4046
func Load() Config {
4147
_ = godotenv.Load() // missing .env is fine: production sets real env vars
4248

49+
port := getenv("PORT", "8080")
4350
return Config{
44-
Port: getenv("PORT", "8080"),
45-
MongoURI: getenv("MONGODB_URI", "mongodb://localhost:27017"),
46-
MongoDB: getenv("MONGODB_DB", "job-portal"),
51+
Port: port,
52+
PublicURL: getenv("PUBLIC_URL", "http://localhost:"+port),
53+
MongoURI: getenv("MONGODB_URI", "mongodb://localhost:27017"),
54+
MongoDB: getenv("MONGODB_DB", "job-portal"),
4755

4856
ClerkWebhookSigningSecret: os.Getenv("CLERK_WEBHOOK_SIGNING_SECRET"),
4957
ClerkSecretKey: os.Getenv("CLERK_SECRET_KEY"),
5058
WebOrigin: getenv("WEB_ORIGIN", "http://localhost:3000"),
5159

60+
LocalUploadDir: os.Getenv("LOCAL_UPLOAD_DIR"),
61+
5262
CloudinaryCloudName: os.Getenv("CLOUDINARY_CLOUD_NAME"),
5363
CloudinaryAPIKey: os.Getenv("CLOUDINARY_API_KEY"),
5464
CloudinaryAPISecret: os.Getenv("CLOUDINARY_API_SECRET"),

‎api/internal/handler/router.go‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,9 @@ type Deps struct {
2424
FetchClerkUser FetchClerkUser
2525
// Uploader stores uploaded files (Cloudinary). Nil disables uploads (503).
2626
Uploader Uploader
27+
// Files serves locally stored uploads at /uploads/ (development and
28+
// end-to-end tests only, when uploads go to disk instead of Cloudinary).
29+
Files http.Handler
2730

2831
// CompanyTokens issues and verifies Company session tokens.
2932
// Nil disables Company login and the /company routes (503).
@@ -74,6 +77,10 @@ func NewRouter(d Deps) http.Handler {
7477
mux.Handle("/company/", off)
7578
}
7679

80+
if d.Files != nil {
81+
mux.Handle("GET /uploads/", d.Files)
82+
}
83+
7784
mux.Handle("POST /webhooks/clerk", ClerkWebhook(d.ClerkWebhookSecret, d.Store))
7885

7986
return mux

‎api/internal/upload/local.go‎

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
package upload
2+
3+
import (
4+
"context"
5+
"crypto/rand"
6+
"encoding/hex"
7+
"fmt"
8+
"io"
9+
"mime"
10+
"net/http"
11+
"os"
12+
"path"
13+
"path/filepath"
14+
"strings"
15+
)
16+
17+
// Local stores uploads on disk and serves them under /uploads/. It stands in
18+
// for Cloudinary in development and end-to-end tests, so nothing is sent to
19+
// a real account. Like Cloudinary's CDN it is a plain file host: browsers
20+
// load the files directly, but never call the API itself through it.
21+
type Local struct {
22+
dir string // where files are written
23+
baseURL string // public origin of this API, e.g. http://localhost:8090
24+
}
25+
26+
func NewLocal(dir, baseURL string) (*Local, error) {
27+
if err := os.MkdirAll(dir, 0o755); err != nil {
28+
return nil, fmt.Errorf("create upload dir: %w", err)
29+
}
30+
return &Local{dir: dir, baseURL: strings.TrimRight(baseURL, "/")}, nil
31+
}
32+
33+
// Upload writes the file under folder with a random name (keeping the
34+
// extension of its detected type) and returns its public URL.
35+
func (l *Local) Upload(_ context.Context, file io.Reader, folder string) (string, error) {
36+
data, err := io.ReadAll(file)
37+
if err != nil {
38+
return "", err
39+
}
40+
random := make([]byte, 12)
41+
if _, err := rand.Read(random); err != nil {
42+
return "", err
43+
}
44+
name := hex.EncodeToString(random) + extension(data)
45+
46+
if err := os.MkdirAll(filepath.Join(l.dir, filepath.FromSlash(folder)), 0o755); err != nil {
47+
return "", err
48+
}
49+
if err := os.WriteFile(filepath.Join(l.dir, filepath.FromSlash(folder), name), data, 0o644); err != nil {
50+
return "", fmt.Errorf("write upload: %w", err)
51+
}
52+
return l.baseURL + "/uploads/" + path.Join(folder, name), nil
53+
}
54+
55+
func extension(data []byte) string {
56+
exts, _ := mime.ExtensionsByType(http.DetectContentType(data))
57+
for _, preferred := range []string{".pdf", ".png", ".jpg", ".webp"} {
58+
for _, e := range exts {
59+
if e == preferred {
60+
return e
61+
}
62+
}
63+
}
64+
if len(exts) > 0 {
65+
return exts[0]
66+
}
67+
return ""
68+
}
69+
70+
// Handler serves GET /uploads/<folder>/<file>. Directory listings are
71+
// refused; http.Dir already blocks paths that escape the directory.
72+
func (l *Local) Handler() http.Handler {
73+
files := http.StripPrefix("/uploads/", http.FileServer(http.Dir(l.dir)))
74+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
75+
if strings.HasSuffix(r.URL.Path, "/") || strings.Contains(r.URL.Path, "..") {
76+
http.NotFound(w, r)
77+
return
78+
}
79+
files.ServeHTTP(w, r)
80+
})
81+
}

‎api/internal/upload/local_test.go‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package upload_test
2+
3+
import (
4+
"bytes"
5+
"context"
6+
"io"
7+
"net/http"
8+
"net/http/httptest"
9+
"strings"
10+
"testing"
11+
12+
"github.com/AlexMari0/job-portal/api/internal/upload"
13+
)
14+
15+
func TestLocalUploadAndServe(t *testing.T) {
16+
local, err := upload.NewLocal(t.TempDir(), "http://localhost:8090")
17+
if err != nil {
18+
t.Fatal(err)
19+
}
20+
png := []byte("\x89PNG\r\n\x1a\n0000IHDR")
21+
22+
url, err := local.Upload(context.Background(), bytes.NewReader(png), "job-portal/logos")
23+
if err != nil {
24+
t.Fatal(err)
25+
}
26+
if !strings.HasPrefix(url, "http://localhost:8090/uploads/job-portal/logos/") || !strings.HasSuffix(url, ".png") {
27+
t.Fatalf("url = %q", url)
28+
}
29+
30+
// The returned URL serves the same bytes.
31+
path := strings.TrimPrefix(url, "http://localhost:8090")
32+
rec := httptest.NewRecorder()
33+
local.Handler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, path, nil))
34+
body, _ := io.ReadAll(rec.Body)
35+
if rec.Code != http.StatusOK || !bytes.Equal(body, png) {
36+
t.Errorf("GET %s = %d, %d bytes", path, rec.Code, len(body))
37+
}
38+
39+
// Two uploads never share a name.
40+
other, _ := local.Upload(context.Background(), bytes.NewReader(png), "job-portal/logos")
41+
if other == url {
42+
t.Error("second upload overwrote the first")
43+
}
44+
}
45+
46+
func TestLocalHandlerRefusesListingsAndTraversal(t *testing.T) {
47+
local, _ := upload.NewLocal(t.TempDir(), "http://localhost:8090")
48+
_, _ = local.Upload(context.Background(), bytes.NewReader([]byte("%PDF-1.4\n")), "job-portal/resumes")
49+
50+
for _, path := range []string{"/uploads/", "/uploads/job-portal/resumes/", "/uploads/../go.mod"} {
51+
rec := httptest.NewRecorder()
52+
local.Handler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, path, nil))
53+
if rec.Code == http.StatusOK {
54+
t.Errorf("GET %s = 200, want refusal; body %q", path, rec.Body)
55+
}
56+
}
57+
}

‎web/.gitignore‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,3 +40,8 @@ yarn-error.log*
4040
# typescript
4141
*.tsbuildinfo
4242
next-env.d.ts
43+
44+
# Playwright
45+
/test-results/
46+
/playwright-report/
47+
/playwright/.cache/

‎web/e2e/company.spec.ts‎

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
import path from "node:path";
2+
import { expect, test } from "@playwright/test";
3+
import { ACME, expectToast, jobCardTitles, loginCompany, reseed } from "./helpers";
4+
5+
// One Company session through the whole file, as a recruiter would work.
6+
test.describe.configure({ mode: "serial" });
7+
test.beforeAll(reseed);
8+
9+
test("wrong password is rejected", async ({ page }) => {
10+
await loginCompany(page, ACME.email, "wrong-password");
11+
await expectToast(page, "Invalid email or password");
12+
await expect(page).toHaveURL("/");
13+
});
14+
15+
test.describe("signed in as Acme", () => {
16+
test.beforeEach(async ({ page }) => {
17+
await loginCompany(page, ACME.email, ACME.password);
18+
await expect(page).toHaveURL("/dashboard/manage-jobs");
19+
});
20+
21+
test("dashboard greets the Company and lists its Jobs", async ({ page }) => {
22+
await expect(page.getByText(`Welcome, ${ACME.name}!`)).toBeVisible();
23+
const rows = page.locator("tbody tr");
24+
await expect(rows).toHaveCount(3);
25+
await expect(rows.filter({ hasText: "Backend Engineer (Go)" }).locator("td").nth(4)).toHaveText("1"); // applicants
26+
});
27+
28+
test("hiding a Job removes it from the public list", async ({ page }) => {
29+
const row = page.locator("tbody tr").filter({ hasText: "Data Analyst" });
30+
await row.getByLabel("Visible").uncheck();
31+
await expectToast(page, "Visibility changed");
32+
await page.reload();
33+
await expect(page.locator("tbody tr").filter({ hasText: "Data Analyst" }).getByLabel("Visible")).not.toBeChecked();
34+
35+
await page.goto("/");
36+
await expect(jobCardTitles(page)).not.toContainText(["Data Analyst"]);
37+
});
38+
39+
test("posting a Job with the Quill editor", async ({ page }) => {
40+
await page.getByRole("link", { name: "Add Job" }).click();
41+
await page.getByLabel("Job Title").fill("E2E Platform Engineer");
42+
const editor = page.locator(".ql-editor");
43+
await editor.click();
44+
await page.keyboard.type("Run the ");
45+
await page.keyboard.press("ControlOrMeta+b");
46+
await page.keyboard.type("platform");
47+
await page.getByLabel("Job Category").selectOption("Programming");
48+
await page.getByLabel("Job Location").selectOption("Chennai");
49+
await page.getByLabel("Job Salary").fill("120000");
50+
await page.getByRole("button", { name: "ADD" }).click();
51+
await expectToast(page, "Job Added");
52+
await expect(page.getByLabel("Job Title")).toHaveValue(""); // form cleared
53+
54+
await page.getByRole("link", { name: "Manage Jobs" }).click();
55+
await expect(page.locator("tbody tr").first()).toContainText("E2E Platform Engineer"); // newest first
56+
57+
await page.goto("/");
58+
await page.locator("#job-list ~ div > div").filter({ hasText: "E2E Platform Engineer" }).getByRole("link", { name: "Learn more" }).click();
59+
await expect(page.locator(".rich-text strong")).toHaveText("platform"); // bold kept
60+
// The default level was accepted (shown next to the title).
61+
await expect(page.locator("span.flex").filter({ hasText: "Beginner level" })).toBeVisible();
62+
});
63+
64+
test("an empty description is refused", async ({ page }) => {
65+
await page.getByRole("link", { name: "Add Job" }).click();
66+
await page.getByLabel("Job Title").fill("No description");
67+
await page.getByLabel("Job Salary").fill("1");
68+
await page.getByRole("button", { name: "ADD" }).click();
69+
await expect(page.getByText("required")).toBeVisible(); // field error under the editor
70+
});
71+
72+
test("accepting an Application", async ({ page }) => {
73+
await page.getByRole("link", { name: "View Applications" }).click();
74+
const row = page.locator("tbody tr").filter({ hasText: "Alice Santoso" });
75+
await expect(row).toContainText("Backend Engineer (Go)");
76+
await row.getByRole("button", { name: "Change status" }).hover();
77+
await row.getByRole("button", { name: "Accept" }).click();
78+
await expectToast(page, "Status Changed");
79+
await expect(row.locator("td").last()).toHaveText("Accepted");
80+
});
81+
82+
test("logging out", async ({ page }) => {
83+
await page.getByRole("button", { name: "Account menu" }).hover();
84+
await page.getByRole("button", { name: "Logout" }).click();
85+
await expect(page).toHaveURL("/");
86+
await page.goto("/dashboard/manage-jobs");
87+
await expect(page).toHaveURL("/"); // no session: sent home by proxy.ts
88+
});
89+
});
90+
91+
test("signing up a new Company with a logo", async ({ page }) => {
92+
await page.goto("/");
93+
await page.getByRole("button", { name: "Recruiter Login" }).click();
94+
await page.getByRole("button", { name: "Sign Up" }).click();
95+
96+
const details = page.getByRole("form", { name: "Recruiter Sign Up" });
97+
await details.getByPlaceholder("Company Name").fill("E2E Company");
98+
await details.getByPlaceholder("Email Id").fill("[email protected]");
99+
await details.getByPlaceholder(/Password/).fill("secret123");
100+
await details.getByRole("button", { name: "next" }).click();
101+
102+
const logo = page.getByRole("form", { name: "Upload Company Logo" });
103+
await logo.locator('input[type="file"]').setInputFiles(path.join(__dirname, "fixtures", "logo.png"));
104+
await expect(logo.getByAltText("Company logo")).toHaveAttribute("src", /^blob:/); // preview
105+
await logo.getByRole("button", { name: "create account" }).click();
106+
107+
await expect(page).toHaveURL("/dashboard/manage-jobs");
108+
await expect(page.getByText("Welcome, E2E Company!")).toBeVisible();
109+
await expect(page.getByText("No Jobs posted yet")).toBeVisible();
110+
// The logo was stored (on disk in e2e) and is shown in the header.
111+
await expect(page.getByRole("button", { name: "Account menu" }).locator("img")).toHaveAttribute("src", /uploads/);
112+
});
113+
114+
test("signing up with a taken email goes back to step one", async ({ page }) => {
115+
await page.goto("/");
116+
await page.getByRole("button", { name: "Recruiter Login" }).click();
117+
await page.getByRole("button", { name: "Sign Up" }).click();
118+
const details = page.getByRole("form", { name: "Recruiter Sign Up" });
119+
await details.getByPlaceholder("Company Name").fill("Acme Again");
120+
await details.getByPlaceholder("Email Id").fill(ACME.email);
121+
await details.getByPlaceholder(/Password/).fill("secret123");
122+
await details.getByRole("button", { name: "next" }).click();
123+
await page.locator('input[type="file"]').setInputFiles(path.join(__dirname, "fixtures", "logo.png"));
124+
await page.getByRole("button", { name: "create account" }).click();
125+
126+
await expectToast(page, "already registered");
127+
await expect(page.getByRole("form", { name: "Recruiter Sign Up" }).getByPlaceholder("Email Id")).toHaveValue(ACME.email);
128+
});

‎web/e2e/fixtures/logo.png‎

69 Bytes
Loading

0 commit comments

Comments
 (0)