Skip to content

Commit c24ec8f

Browse files
buzz-codeclaude
andauthored
Browser E2E (Playwright): login/dashboard, CRUD round-trip, export download — wired into CI (#135)
* Add browser E2E pilot (Playwright): login -> dashboard First real-browser test in the repo — drives the actual client against a live server + real MySQL, not mocks/jsdom. Scoped as a pilot for one flow to prove the pattern before deciding whether to extend it further or wire it into CI (see multi-repo-codespace's TEST_COVERAGE_TODO.md, Phase 6). - Registers a fresh user via POST /auth/register (same pattern as the server/test/*-crud.e2e-spec.ts suites) rather than relying on seeded DB fixtures, whose password hashes aren't real bcrypt hashes of any known password. - Logs in through the actual UI form, confirms the dashboard loads (sidebar renders, no leftover login form, no error page). - Uses the pre-installed Chromium at $PLAYWRIGHT_BROWSERS_PATH via launchOptions.executablePath, avoiding a browser download. - README documents the run-without-docker stack setup needed to run it, including a real gotcha hit while building this: NODE_ENV=development gates the CORS localhost allowlist in bootstrap.util.ts, so a server started without it fails every browser request as a silent CORS error (curl/supertest don't hit this — no Origin header). Not wired into CI — deliberately a manual pilot for now. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017YepEQ4PfrEhS2L8imLLRe * Bump client/shared: fix createResourceTests discovery + crash detection Picks up nra-client@a760e90: resource discovery now expands SubMenu groups (real entities were never being found before, only ~8 static utility pages), and Create/Edit crash detection now checks for the per-route error fallback (<h1 role="alert">) instead of relying on sidebar menuitems alone, since react-admin's per-route ErrorBoundary doesn't take the sidebar down with it. Verified against this app: injected a call to a never-imported function into student.jsx's Create/Edit Inputs — the suite passed before this fix (false negative) and failed after it. * Bump client/shared: eliminate redundant duplicate entities.test.js run Picks up nra-client@07c823a. This app's client/src/entities.test.js already calls createResourceTests(App) directly; the generic fallback in client/shared/utils/testing/entities.test.js was running the exact same List/Create/Edit sweep over the same App a second time for zero extra coverage. Harmless while resource discovery silently found nothing (fixed in the prior commit), but a real cost now that it works — this is very likely why CI's "Run client tests" job just ran two full ~50min sweeps of the same 46 resources back to back instead of one. Also widens the per-phase timeout further, since CI hardware measured noticeably slower than local dev for this workload. * CI: bump test heap limit, bump client/shared for DOM-reset fix Picks up nra-client@98c5164. The previous fix (dedup + wider timeouts) got CI's client-tests job through the full List/Create/Edit sweep, but it then failed on the lightweight Common shared routes tests that run right after — consistent with resource/DOM accumulation across ~140 renders in one process rather than any single resource being slow. Two mitigations: createResourceTests.js now hard-resets document.body between iterations (MUI portals can mount outside what RTL's cleanup() tracks), and this job now runs yarn test with a larger V8 heap. * Bump client/shared: entities.test.js from ~29min to ~3min Picks up nra-client@a8c10e8, which stops remounting the whole app per page (remount cost was climbing monotonically across iterations, which is what made this job degrade) and drops testing-library *ByRole queries that cost ~666ms each under jsdom. Also fixes two false-pass bugs found on the way: content was being sampled before React's startTransition swapped in the new page, and the getOne mock's fixed id made create-less resources look like real crashes. Locally: 171s for the full file, all green; jest's own estimate for the previous version was 1339s. * e2e: fix Copilot findings, add CRUD + export flows, wire into CI Fixes both outstanding review comments: - README referenced $PLAYWRIGHT_BROWSERS_PATH but the config actually read PLAYWRIGHT_CHROMIUM_PATH; config now points at /opt/pw-browsers/chromium (a stable symlink, so it survives Chromium version bumps) and the README matches. - registerTestUser()'s apiContext.dispose() wasn't called on the throw path; wrapped in try/finally. Adds two flows chosen for what only a real browser + server + database can catch, verified end-to-end against a from-scratch MySQL database (not assumed — actually torn down and rebuilt to prove the CI steps work): - crud-roundtrip.spec.ts: create/edit/delete a klass_type through the real UI, checking after each step that the change round-tripped through the server and database, not just that the request didn't throw. klass_type as a non-admin user needs only two plain fields, no reference picker. - export-download.spec.ts: downloads a real Excel export and checks it's non-empty. Exporting is gated on isPaid, which nothing in the app can set for a fresh registration, so tests/helpers.ts's markUserAsPaid() reaches directly into the DB for setup — same reasoning as registerTestUser() already reaching around the UI via the API. Shared setup (registerTestUser, markUserAsPaid, loginThroughUi) extracted into tests/helpers.ts; login-dashboard.spec.ts now uses it too. Wires all three into CI as a new e2e-tests job: a MySQL service container, migrations from db/data.sql + yarn typeorm:run, server and client started and polled for readiness, then the suite. Ran this exact sequence locally against a torn-down-and-recreated database before committing. * CI: fix set -e aborting the server-readiness retry loop GitHub Actions runs run: steps under bash -e. code=$(curl ...) is a plain assignment, not exempt from -e the way 'curl ... && break' is — so on the very first, expected-to-fail connection attempt (server not up yet) curl's exit 7 aborted the whole step before the retry loop ran a single iteration. Reproduced exactly locally (bash -e against an unreachable port: SCRIPT_EXIT=7, zero loop output) and confirmed '|| true' fixes it (loop runs to completion, SCRIPT_EXIT=0) before pushing. * e2e: fall back to Playwright's own managed browser off the sandbox /opt/pw-browsers/chromium is specific to the dev sandbox this pilot was first built in — GitHub Actions runners don't have it, so CI failed with 'Failed to launch chromium because executable doesn't exist'. My earlier local proof run didn't catch this because it also ran inside that same sandbox. playwright.config.ts now only pins executablePath when that path actually exists on disk; otherwise it's left unset so Playwright uses its own managed browser. CI installs one via 'npx playwright install --with-deps chromium' in the Install E2E deps step. Verified locally: pointing PLAYWRIGHT_CHROMIUM_PATH at a path that doesn't exist reproduces CI's exact failure mode (Playwright's own 'please run playwright install' error) — confirming the fallback needs that install step, not just an unset executablePath, and that this is the same failure CI hit. --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent d7982c4 commit c24ec8f

11 files changed

Lines changed: 561 additions & 1 deletion

File tree

‎.github/workflows/run-tests.yml‎

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,4 +71,123 @@ jobs:
7171
cache-dependency-path: client/yarn.lock
7272
- run: yarn
7373
- run: yarn test
74+
env:
75+
# entities.test.js renders the full admin app ~140 times in one
76+
# process (every resource's List/Create/Edit page); the default
77+
# heap limit is tight enough on CI runners that later tests in the
78+
# same run degrade/fail from GC pressure even though they pass
79+
# fine in isolation.
80+
NODE_OPTIONS: --max-old-space-size=4096
81+
82+
e2e-tests:
83+
name: Run browser E2E tests
84+
runs-on: ubuntu-latest
85+
needs: prepare
86+
if: ${{ needs.prepare.outputs.client == 'true' || needs.prepare.outputs.server == 'true' }}
87+
services:
88+
mysql:
89+
image: mysql:8.4
90+
env:
91+
MYSQL_ROOT_PASSWORD: root
92+
MYSQL_DATABASE: mysql_database
93+
ports:
94+
- 3306:3306
95+
options: >-
96+
--health-cmd="mysqladmin ping -proot"
97+
--health-interval=10s
98+
--health-timeout=5s
99+
--health-retries=10
100+
env:
101+
MYSQL_HOST: 127.0.0.1
102+
MYSQL_PORT: 3306
103+
MYSQL_USER: mysql_user
104+
MYSQL_PASSWORD: mysql_password
105+
MYSQL_DATABASE: mysql_database
106+
JWT_SECRET: jwt_secret
107+
steps:
108+
- uses: actions/checkout@v4
109+
with:
110+
submodules: recursive
111+
- uses: actions/setup-node@v4
112+
with:
113+
node-version: '20'
114+
115+
# data.sql (the run-without-docker checkpoint dump) both creates the
116+
# schema/seed data and grants mysql_user its privileges, but assumes
117+
# the account itself already exists — the docker-based setup creates
118+
# it via the image's own MYSQL_USER/MYSQL_PASSWORD env vars, which the
119+
# plain `mysql:` service image doesn't expose the same way.
120+
- name: Set up database
121+
run: |
122+
mysql -h127.0.0.1 -uroot -proot -e "
123+
CREATE USER IF NOT EXISTS 'mysql_user'@'%' IDENTIFIED BY 'mysql_password';
124+
GRANT ALL PRIVILEGES ON mysql_database.* TO 'mysql_user'@'%';
125+
FLUSH PRIVILEGES;
126+
"
127+
mysql -h127.0.0.1 -uroot -proot mysql_database < db/data.sql
128+
129+
- name: Install server deps, run pending migrations
130+
working-directory: ./server
131+
run: |
132+
yarn
133+
NODE_ENV=development yarn typeorm:run
134+
135+
# Backgrounded within this step, with the wait loop right after it in
136+
# the same step: the workflow can't move on to the next step until
137+
# this one is confirmed answering requests — a later step starting
138+
# before this one is truly ready would just fail on connection-refused
139+
# instead of waiting for it.
140+
- name: Start server
141+
working-directory: ./server
142+
run: |
143+
NODE_ENV=development PORT=3001 yarn start:dev > /tmp/server.log 2>&1 &
144+
ready=false
145+
for i in $(seq 1 60); do
146+
# Any HTTP response (even a 400 from an empty body) means the
147+
# server is up; curl's own exit code only tells us the TCP
148+
# connection was refused or not. GitHub Actions runs this script
149+
# under `bash -e`, and `code=$(curl ...)` is a plain assignment
150+
# (not exempt the way `curl ... && break` is) — so on the very
151+
# first, expected-to-fail attempt curl's connection-refused exit
152+
# code aborted the whole step before the retry loop ran at all.
153+
# `|| true` neutralizes that; emptiness is still checked below.
154+
code=$(curl -s -o /dev/null -w "%{http_code}" -X POST http://localhost:3001/auth/register -H "Content-Type: application/json" -d '{}' || true)
155+
if [ -n "$code" ] && [ "$code" != "000" ]; then ready=true; break; fi
156+
sleep 1
157+
done
158+
if [ "$ready" != "true" ]; then
159+
echo "Server did not become ready:"; cat /tmp/server.log; exit 1
160+
fi
161+
162+
- name: Install client deps, start client
163+
working-directory: ./client
164+
run: |
165+
yarn
166+
yarn start > /tmp/client.log 2>&1 &
167+
for i in $(seq 1 60); do
168+
curl -sf -o /dev/null http://localhost:3000 && break
169+
sleep 1
170+
done
171+
curl -sf -o /dev/null http://localhost:3000 || (echo "Client did not become ready:"; cat /tmp/client.log; exit 1)
172+
173+
- name: Install E2E deps
174+
working-directory: ./e2e
175+
run: |
176+
yarn
177+
# playwright.config.ts prefers a pre-installed Chromium at
178+
# $PLAYWRIGHT_CHROMIUM_PATH (present in some dev sandboxes) but
179+
# falls back to Playwright's own managed browser when that path
180+
# doesn't exist — which is always the case on this runner.
181+
npx playwright install --with-deps chromium
182+
183+
- name: Run E2E tests
184+
working-directory: ./e2e
185+
run: yarn test
186+
187+
- uses: actions/upload-artifact@v4
188+
if: failure()
189+
with:
190+
name: playwright-report
191+
path: e2e/test-results/
192+
retention-days: 7
74193

‎e2e/.gitignore‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
node_modules/
2+
test-results/
3+
playwright-report/

‎e2e/README.md‎

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
# Browser E2E (Playwright)
2+
3+
Real-browser tests, driving the actual client + server + a real database — not
4+
mocks, not jsdom. Deliberately narrow: three flows chosen for what only a real
5+
browser + server + database can catch, not for breadth (the jsdom-based
6+
`entities.test.js` smoke tests already cover every resource page cheaply —
7+
see "What this catches that jsdom smoke tests don't" below). Wired into CI
8+
as the `e2e-tests` job in `.github/workflows/run-tests.yml`, which stands up
9+
a real MySQL service container, runs migrations, boots server + client, then
10+
runs this suite against them.
11+
12+
## Why Playwright, and which browser it launches
13+
14+
Some dev sandboxes this pilot runs in ship a pre-installed Chromium under
15+
`$PLAYWRIGHT_BROWSERS_PATH` (`/opt/pw-browsers`), so there's no download step
16+
there — `playwright.config.ts` points `launchOptions.executablePath` at
17+
`/opt/pw-browsers/chromium` (a stable symlink to the current versioned
18+
build) when that path exists, which avoids both a network fetch that may
19+
not be reachable in a sandbox and a redundant download of a browser that's
20+
already there. Override with `PLAYWRIGHT_CHROMIUM_PATH` if your environment
21+
installs it elsewhere.
22+
23+
CI (and most other environments) doesn't have that path — there,
24+
`executablePath` is left unset and Playwright falls back to its own managed
25+
browser, installed by the `Install E2E deps` step's `npx playwright install
26+
--with-deps chromium`. Run that same command locally first if your
27+
environment has neither a pre-installed Chromium nor one Playwright has
28+
already downloaded.
29+
30+
## Prerequisites: a live stack
31+
32+
Playwright needs the client and server actually running against a real
33+
database — see the `run-without-docker` skill (`multi-repo-codespace/.github/skills/`)
34+
for the full walkthrough if you don't have Docker. Short version:
35+
36+
```bash
37+
# 1. MySQL, once
38+
apt-get install -y mysql-server-8.0 && service mysql start
39+
mysql -u root -e "
40+
CREATE DATABASE mysql_database CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;
41+
CREATE USER 'mysql_user'@'localhost' IDENTIFIED BY 'mysql_password';
42+
GRANT ALL PRIVILEGES ON mysql_database.* TO 'mysql_user'@'localhost';
43+
GRANT SYSTEM_USER ON *.* TO 'mysql_user'@'localhost';
44+
FLUSH PRIVILEGES;
45+
"
46+
47+
# 2. Load the schema checkpoint + remaining migrations (fast path — see
48+
# run-without-docker for the full-replay alternative)
49+
mysql -u root mysql_database < db/data.sql
50+
cd server && NODE_ENV=development yarn typeorm:run
51+
52+
# 3. Start server and client — NODE_ENV=development is required, not optional:
53+
# server/shared/utils/bootstrap.util.ts only allows the browser's
54+
# localhost origin through CORS when NODE_ENV === 'development'. Without
55+
# it every request from the client to the API fails as a silent CORS
56+
# error in the browser (curl/supertest calls don't hit this — they don't
57+
# send an Origin header — so this is easy to miss when smoke-testing the
58+
# API directly).
59+
NODE_ENV=development MYSQL_HOST=localhost MYSQL_PORT=3306 \
60+
MYSQL_USER=mysql_user MYSQL_PASSWORD=mysql_password MYSQL_DATABASE=mysql_database \
61+
JWT_SECRET=jwt_secret PORT=3001 yarn start:dev # server, separate shell
62+
63+
cd client && yarn start # client, separate shell — picks 3000, falls back if taken
64+
```
65+
66+
Default API URL resolution in the client (`constantsProvider.js`) is
67+
`http://<hostname>:<client-port + 1>`, so client on 3000 + server on 3001
68+
just works with no extra client-side config.
69+
70+
## Running
71+
72+
```bash
73+
cd e2e
74+
yarn install
75+
yarn test # against http://localhost:3000
76+
E2E_BASE_URL=... E2E_API_URL=... yarn test # against a different stack
77+
```
78+
79+
## What's covered
80+
81+
All three specs share `tests/helpers.ts`'s `registerTestUser()` — registers a
82+
fresh user via the API (same pattern as `server/test/*-crud.e2e-spec.ts`, not
83+
seeded DB fixtures — the checkpoint dump's password hashes aren't real bcrypt
84+
hashes of any known password) — and `loginThroughUi()`, which logs that user
85+
in through the actual UI form.
86+
87+
- `tests/login-dashboard.spec.ts` — confirms the dashboard loads after login
88+
(sidebar renders, no leftover login form, no error page).
89+
- `tests/crud-roundtrip.spec.ts` — creates, edits, and deletes a `klass_type`
90+
through the real UI, checking after each step that the change actually
91+
round-tripped through the server and database (not just that the request
92+
didn't throw). `klass_type` is used because, as a non-admin user, it only
93+
needs two plain fields (no reference-picker dropdown to drive).
94+
- `tests/export-download.spec.ts` — downloads a real Excel export and checks
95+
the file is non-empty. Exporting is gated on the user's `isPaid` flag, which
96+
nothing in the app itself can set for a fresh registration, so
97+
`tests/helpers.ts`'s `markUserAsPaid()` reaches directly into the database —
98+
setup for the flow under test, same reasoning as `registerTestUser()`
99+
reaching around the UI via the API.
100+
101+
## What this catches that jsdom smoke tests don't
102+
103+
Real browser rendering, real CORS/cookie/auth wiring end to end, an actual
104+
multi-page flow (form submit → redirect → authenticated data fetch →
105+
render), a create/edit/delete that really persists through the server and
106+
database instead of a mocked `dataProvider`, and a real server-generated
107+
file (the export test) — none of which a jsdom test with a mocked
108+
`dataProvider` can exercise, since there's no real server or file on the
109+
other end of the call. `entities.test.js`'s smoke tests are cheaper and
110+
catch a different, much larger class of bug (any resource crashing on
111+
mount) across every resource in the app — see that file's comments for the
112+
trade-off between the two.

‎e2e/package.json‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
{
2+
"name": "react-admin-nestjs-e2e",
3+
"private": true,
4+
"scripts": {
5+
"test": "playwright test"
6+
},
7+
"devDependencies": {
8+
"@playwright/test": "^1.48.0",
9+
"mysql2": "^3.11.0"
10+
}
11+
}

‎e2e/playwright.config.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import { defineConfig } from '@playwright/test';
2+
import { existsSync } from 'fs';
3+
4+
// The sandboxed dev environment this pilot was first built in ships a
5+
// pre-installed Chromium under $PLAYWRIGHT_BROWSERS_PATH (/opt/pw-browsers)
6+
// with a stable `chromium` symlink to the current versioned build — using
7+
// it avoids a redundant download there. GitHub Actions runners (and most
8+
// other environments) don't have that path at all, so this only pins
9+
// executablePath when the path is actually present; otherwise it's left
10+
// undefined and Playwright falls back to its own managed browser (installed
11+
// via `npx playwright install --with-deps chromium` — see the CI workflow
12+
// and this package's README).
13+
const sandboxChromium = process.env.PLAYWRIGHT_CHROMIUM_PATH || '/opt/pw-browsers/chromium';
14+
15+
export default defineConfig({
16+
testDir: './tests',
17+
timeout: 30000,
18+
retries: 0,
19+
use: {
20+
baseURL: process.env.E2E_BASE_URL || 'http://localhost:3000',
21+
launchOptions: {
22+
...(existsSync(sandboxChromium) ? { executablePath: sandboxChromium } : {}),
23+
args: ['--no-sandbox'],
24+
},
25+
screenshot: 'only-on-failure',
26+
},
27+
});

‎e2e/tests/crud-roundtrip.spec.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import { test, expect } from '@playwright/test';
2+
import { registerTestUser, loginThroughUi } from './helpers';
3+
4+
// Exercises a real dataProvider <-> nestjs-crud round trip through the
5+
// actual UI: create, appears in the list, edit, change is visible, delete,
6+
// gone from the list. jsdom's entities.test.js smoke tests (mocked
7+
// dataProvider) prove pages don't crash on mount; they can't prove a create
8+
// actually persists, an edit actually updates, or a delete actually removes
9+
// a row — that needs a real server and a real database.
10+
//
11+
// klass_type is used because as a non-admin user (a fresh registration,
12+
// same as the login test) it only requires two fields — key (number) and
13+
// name (text) — with no reference picker to drive; every other field on
14+
// this app's entities that was checked either needed a reference-select
15+
// dropdown or is admin-only.
16+
test('create, edit and delete a klass type through the real UI and API', async ({ page }) => {
17+
const { username, password } = await registerTestUser();
18+
await loginThroughUi(page, username, password);
19+
20+
const uniqueSuffix = Date.now();
21+
const originalName = `E2E Klass ${uniqueSuffix}`;
22+
const updatedName = `E2E Klass ${uniqueSuffix} (updated)`;
23+
24+
// --- Create ---
25+
await page.goto('/klass_type/create');
26+
await page.locator('input[name="key"]').fill('1');
27+
await page.locator('input[name="name"]').fill(originalName);
28+
await page.locator('button[type="submit"]').first().click();
29+
30+
// A successful create redirects to the list, which is the read half of
31+
// the round trip: the row has to come back from a real GET, not just be
32+
// assumed present because the POST returned 2xx.
33+
await expect(page).toHaveURL(/\/klass_type$/, { timeout: 10000 });
34+
await expect(page.getByText(originalName, { exact: true })).toBeVisible({ timeout: 10000 });
35+
36+
// --- Edit ---
37+
await page.getByText(originalName, { exact: true }).click();
38+
await expect(page).toHaveURL(/\/klass_type\/\d+$/, { timeout: 10000 });
39+
const nameInput = page.locator('input[name="name"]');
40+
await nameInput.fill(updatedName);
41+
await page.locator('button[type="submit"]').first().click();
42+
43+
await expect(page).toHaveURL(/\/klass_type$/, { timeout: 10000 });
44+
await expect(page.getByText(updatedName, { exact: true })).toBeVisible({ timeout: 10000 });
45+
// The pre-edit name should be gone, not just the new one added alongside it.
46+
await expect(page.getByText(originalName, { exact: true })).toHaveCount(0);
47+
48+
// --- Delete ---
49+
await page.locator('input[type="checkbox"]').nth(1).check();
50+
await page.getByRole('button', { name: 'מחק' }).click();
51+
await page.getByRole('button', { name: 'אשר' }).click();
52+
53+
await expect(page.getByText(updatedName, { exact: true })).toHaveCount(0, { timeout: 10000 });
54+
});

‎e2e/tests/export-download.spec.ts‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import { test, expect } from '@playwright/test';
2+
import fs from 'fs';
3+
import { registerTestUser, loginThroughUi, markUserAsPaid } from './helpers';
4+
5+
// Downloads a real Excel export of a real list. jsdom cannot exercise this
6+
// at all: the server builds actual .xlsx bytes (see server/shared's
7+
// BaseReportGenerator family) and the client turns a base64 JSON payload
8+
// into a real browser download via file-saver — there is no DOM to render,
9+
// so a mocked-dataProvider unit test has nothing to assert against here.
10+
// This is the file-download counterpart to crud-roundtrip's persistence
11+
// check: it proves the export pipeline produces real, non-empty content,
12+
// not just that clicking the button doesn't throw.
13+
test('exports a real, non-empty Excel file for a resource', async ({ page }) => {
14+
const { username, password } = await registerTestUser();
15+
16+
// Exporting is gated on the user's isPaid flag (see server/shared's
17+
// base-entity.util validateUserHasPaid). There is no self-service way to
18+
// become paid through the app itself — billing happens outside it — so
19+
// this reaches directly into the DB, same as registerTestUser reaches
20+
// around the UI via the API: setup for the flow under test, not the flow
21+
// itself.
22+
await markUserAsPaid(username);
23+
24+
await loginThroughUi(page, username, password);
25+
26+
// The export button is disabled when the list is empty, so give it one
27+
// row to actually export.
28+
await page.goto('/klass_type/create');
29+
await page.locator('input[name="key"]').fill('1');
30+
await page.locator('input[name="name"]').fill(`Export Test ${Date.now()}`);
31+
await page.locator('button[type="submit"]').first().click();
32+
await expect(page).toHaveURL(/\/klass_type$/, { timeout: 10000 });
33+
34+
await page.getByRole('button', { name: 'ייצא' }).click();
35+
36+
const downloadPromise = page.waitForEvent('download', { timeout: 10000 });
37+
await page.getByRole('menuitem', { name: 'אקסל' }).click();
38+
const download = await downloadPromise;
39+
40+
expect(download.suggestedFilename()).toMatch(/\.xlsx$/);
41+
42+
const path = await download.path();
43+
expect(path).toBeTruthy();
44+
const { size } = fs.statSync(path!);
45+
// A real xlsx (it's a zip container) is at minimum a few hundred bytes;
46+
// an empty/corrupt response would be at or near 0.
47+
expect(size).toBeGreaterThan(200);
48+
});

0 commit comments

Comments
 (0)