A browser export test can appear to succeed and still leave its consumer with nothing useful. The test obtains a Playwright Download object, suggestedFilename() says report.csv, and the browser context closes. The next step then opens the path it thought represented the export and finds no file or, more dangerously, opens a plausible CSV containing the wrong records.
The acceptance question is narrower than “did a download happen?” It is: after the producing browser context has closed, can a new filesystem read on this runner open the test-owned destination and obtain the independently expected export bytes? Playwright defines the download event at the start of an attachment download, not at completion, and its download files belong to the browser context unless the caller copies them elsewhere.
In this playbook, the browser context owns the staged download. The test owns a separate destination created under Playwright Test’s output directory. A later local consumer owns the decision to accept that saved copy. We will serve synthetic CSV attachments from an owned loopback HTTP server, save one export before closing its manually created non-persistent context, reopen the copy afterward, and compare it with an independent Buffer. We will also prove the validator rejects a same-name, same-size wrong export.
The Playwright references used here are living documentation accessed December 4, 2026; RFC 6266 is the published June 2011 specification.
Define what the export consumer needs
Treat the export lifecycle as six different propositions rather than one “download passed” result.
The trigger proposition is that the test clicked the intended export control. The event proposition is that Playwright observed an attachment download start; the Page API explicitly defines download at attachment start. The transfer proposition is that the download completed without a reported transfer failure. The copy proposition is that download.saveAs(destination) resolved for a caller-chosen destination; Playwright documents that saveAs() copies to that path and waits for an in-progress transfer to finish if necessary.
The content proposition is stronger: a fresh readFile() after context closure returns exactly the bytes expected independently by the test. The handoff proposition is that the next local step receives this post-close copy instead of the browser-managed staging path.
Our acceptance point therefore sits after an awaited context.close() and before the test runner later cleans its output. Playwright’s testInfo.outputPath() returns a path within the current test’s output directory and isolates parallel tests from one another. This article only uses “persist” to mean that a second filesystem open on the same runner succeeds after this browser context closes. It does not mean indefinite retention.
The fixture is intentionally tiny:
id,amount
A7,19Nothing depends on a production account, remote service, service worker, routing handler, or external site. The expected Buffer is declared in test code rather than derived by fetching the response being tested.
Build a localhost export with independently known contents
Use an actual loopback origin because the behavior under test is browser download ownership, not request interception. That keeps this procedure separate from the limits of Playwright request interception: the browser navigates directly to an HTTP server that this test owns.
As of December 4, 2026, npm listed @playwright/test 1.65.2 as the current latest release. Pin that version for this reproduction rather than silently following a moving tag:
mkdir playwright-export-lab
cd playwright-export-lab
npm init -y
npm install --save-dev --save-exact @playwright/[email protected]
npx playwright install chromiumCommit the generated package-lock.json. On later machines use npm ci rather than resolving dependencies again.
A minimal package.json can be:
{
"name": "playwright-export-lab",
"private": true,
"scripts": {
"test:export": "playwright test tests/export.spec.js"
},
"devDependencies": {
"@playwright/test": "1.65.2"
}
}Disable retries for this lab so every record describes one deliberate execution:
// playwright.config.js
const { defineConfig } = require('@playwright/test');
module.exports = defineConfig({
testDir: './tests',
retries: 0,
workers: 1,
timeout: 15_000,
reporter: 'list'
});Create export-server.js:
const http = require('node:http');
const EXPECTED = Buffer.from('id,amount\nA7,19\n', 'utf8');
const WRONG = Buffer.from('id,amount\nB7,19\n', 'utf8');
function deferred() {
let resolve;
let reject;
const promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve, reject };
}
function attachmentHeaders(payload) {
return {
'Content-Type': 'text/csv; charset=utf-8',
'Content-Disposition': 'attachment; filename="report.csv"',
'Content-Length': String(payload.length)
};
}
async function startFixtureServer({ mark = () => {} } = {}) {
let gate;
const server = http.createServer(async (req, res) => {
if (req.url === '/') {
const html = <!doctype html>
<meta charset="utf-8">
<title>Export fixture</title>
<a id="good" href="/export-good.csv">Export good</a>
<a id="wrong" href="/export-wrong.csv">Export wrong</a>
<a id="gated" href="/export-gated.csv">Export gated</a>;
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8',
'Content-Length': String(Buffer.byteLength(html))
});
res.end(html);
return;
}
if (req.url === '/export-good.csv') {
res.writeHead(200, attachmentHeaders(EXPECTED));
res.end(EXPECTED);
return;
}
if (req.url === '/export-wrong.csv') {
res.writeHead(200, attachmentHeaders(WRONG));
res.end(WRONG);
return;
}
if (req.url === '/export-gated.csv') {
if (!gate) {
res.writeHead(409);
res.end('gate not armed');
return;
}
const prefix = EXPECTED.subarray(0, 8);
const suffix = EXPECTED.subarray(8);
res.writeHead(200, attachmentHeaders(EXPECTED));
res.flushHeaders();
res.write(prefix);
mark('prefix-sent');
gate.prefixSent.resolve();
const abort = () => {
if (!res.writableEnded) {
gate.aborted = true;
gate.release.resolve();
}
};
req.once('aborted', abort);
res.once('close', abort);
await gate.release.promise;
if (!gate.aborted && !res.destroyed && !res.writableEnded) {
res.end(suffix);
mark('final-chunk-released');
gate.finalChunkReleased.resolve();
}
return;
}
res.writeHead(404);
res.end('not found');
});
await new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', resolve);
});
const address = server.address();
const baseURL = http://127.0.0.1:${address.port};
return {
baseURL,
armGate() {
gate = {
aborted: false,
prefixSent: deferred(),
release: deferred(),
finalChunkReleased: deferred()
};
return {
prefixSent: gate.prefixSent.promise,
finalChunkReleased: gate.finalChunkReleased.promise,
release: () => gate.release.resolve()
};
},
async close(timeoutMs = 2_000) {
if (gate) gate.release.resolve();
let timer;
const closePromise = new Promise((resolve, reject) => {
server.close(error => error ? reject(error) : resolve());
});
const timeoutPromise = new Promise((_, reject) => {
timer = setTimeout(() => {
server.closeAllConnections?.();
reject(new Errorfixture server did not close within ${timeoutMs} ms));
}, timeoutMs);
});
try {
await Promise.race([closePromise, timeoutPromise]);
} finally {
clearTimeout(timer);
}
}
};
}
module.exports = { startFixtureServer, EXPECTED, WRONG };Run exactly one spec with:
npm ci
npx playwright install chromium
npm run test:exportLab environment. The lab used Node.js v22.16.0 and Debian 13.3, but installing @playwright/test did not complete, so the required bundled Chromium run was unavailable. The cases below describe expected results.
Choose two plausible files of equal length
The two payloads differ only in one row ID:
EXPECTED: id,amount\nA7,19\n
WRONG: id,amount\nB7,19\nBoth are UTF-8, both use LF line endings, both have the same byte length, and both routes advertise report.csv. The consumer’s reference is:
const EXPECTED = Buffer.from('id,amount\nA7,19\n', 'utf8');That constant is intentionally independent of the response under test. Exact byte equality establishes only that this fixture’s reopened copy equals this fixture’s predefined payload at this point in its lifetime. It does not prove that an arbitrary production export is semantically correct.
RFC 6266 section 4.3 says a filename supplied through Content-Disposition is advisory and specifically warns recipients not to let it select an unauthorized filesystem location. Treat report.csv as observed metadata; the test chooses its own destination.
Separate the browser’s staging area from the test output
Playwright’s Downloads guide describes attachments as being downloaded into temporary storage and shows the caller saving them explicitly after registering the event wait. The Download API is more precise about ownership: downloaded files belonging to a browser context are deleted when that context closes.
That lifecycle resembles other producer-owned temporary objects, although the owner here is Playwright rather than Python; temporary-file ownership in Python addresses a different producer lifetime.
Create caller destinations underneath testInfo.outputPath() and browser staging elsewhere:
const fs = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');
async function allocateDestination(testInfo, ...segments) {
const destination = testInfo.outputPath(...segments);
await fs.mkdir(path.dirname(destination), { recursive: true });
try {
await fs.access(destination);
throw new Errorrefusing existing destination: ${destination});
} catch (error) {
if (error.code !== 'ENOENT') throw error;
}
return destination;
}
async function makeStagingDir(caseId) {
return fs.mkdtemp(path.join(os.tmpdir(), pw-stage-${caseId}-));
}testInfo.outputPath() is explicitly designed to keep parallel tests from interfering with each other. Its runner-managed lifetime is a separate lifecycle from the browser context. This playbook makes no promise beyond the current test run and whatever output retention the runner is configured to provide.
Follow the owners of the two paths
A browser launch may specify downloadsPath, but Playwright’s BrowserType.launch() reference says that even when such a directory is supplied, downloads are deleted when the context that created them closes. That precise rule resolves the potentially misleading everyday meaning of “persist” in the Downloads guide: choosing downloadsPath controls staging location; it does not transfer ownership of the staged files beyond context closure.
The two path roles are therefore:
browser-managed: <staging-dir>/<Playwright-managed-name>
test-owned: <testInfo.outputDir>/accepted/case-a.csvDo not assume the staged filename equals suggestedFilename(). download.path() documents a random GUID-style download filename and waits for a successful local download to complete; it also documents that path() throws for remote connections, which this local experiment does not exercise.
Never use raw suggestedFilename() to choose a shared destination. RFC 6266 makes the server filename advisory, while testInfo.outputPath() gives the test a run-scoped location it controls.
Arm the listener before clicking Export
The normal ordering is not “click, then listen.” Playwright’s own Downloads guide and page.waitForEvent() example register the download wait first, click second, and await the saved promise third.
Use a bounded event wait:
const downloadPromise = page.waitForEvent('download', { timeout: 3_000 });
await page.locator('#good').click();
const download = await downloadPromise;A late listener can race because the download event is emitted when the attachment download starts. Event delivery therefore answers “did delivery start?” rather than “are all bytes independently readable at the destination?”
Metadata can be recorded immediately:
const metadata = {
url: download.url(),
suggestedFilename: download.suggestedFilename()
};Playwright says suggestedFilename() is typically computed by the browser from Content-Disposition or the element’s download attribute and notes that browsers can apply different filename logic. In this fixture, the URL is useful only as evidence that the intended owned route was selected; neither URL nor filename substitutes for content validation.
A finite event timeout converts “nothing happened” into a classifiable test failure rather than an unbounded wait. Keep that timeout a harness control, not an HTTP retry mechanism.
Reproduce the missing-file case at context teardown
The negative control should first prove that the test can observe path loss. Resolve download.path() while the context is open, read those staged bytes, close the context, then inspect the exact path again.
The documented contract predicts that the file will be gone after context closure. Do not require a particular post-close Playwright API error string; the evidence is filesystem state at the previously captured path.
async function readState(file) {
try {
return { state: 'present', bytes: await fs.readFile(file) };
} catch (error) {
if (error.code === 'ENOENT') return { state: 'missing' };
throw error; // permission or unrelated I/O failure is not "missing"
}
}
// inside a test:
const downloadPromise = page.waitForEvent('download', { timeout: 3_000 });
await page.locator('#good').click();
const download = await downloadPromise;
const stagedPath = await download.path();
const whileOpen = await fs.readFile(stagedPath);
assert.deepStrictEqual(whileOpen, EXPECTED);
await context.close();
const afterClose = await readState(stagedPath);
assert.equal(afterClose.state, 'missing');download.path() waits for completion before returning a successful local path. That makes the pre-close readFile() a clean observation of completed staging, not proof of persistence.
Expected result, not an observation: the staged bytes match while the context is open and the specific staged file is missing after context.close(). Do not assert that the entire custom staging directory disappears; the documented cleanup rule concerns the downloads created by the context.
If the read fails with EACCES, an I/O error, or some other class, record that separately. Calling every failure “deleted after context close” destroys the distinction the control is meant to establish.
Save the export while its context is still open
The positive counterpart changes one lifecycle operation: copy the download to the test-owned destination before closing its producing context.
Playwright documents saveAs() as copying the download to a user-specified path, safe to invoke while the transfer is still in progress, and waiting for completion when needed. That explicit copy is the handoff boundary.
A shared helper can launch bundled Chromium with explicit staging and a manually created non-persistent context:
const { chromium } = require('@playwright/test');
async function openCase(testInfo, caseId) {
const stagingDir = await makeStagingDir(caseId);
const browser = await chromium.launch({ downloadsPath: stagingDir });
const context = await browser.newContext({ acceptDownloads: true });
const page = await context.newPage();
return {
browser,
context,
page,
stagingDir,
environment: {
node: process.version,
playwright: require('@playwright/test/package.json').version,
browserVersion: browser.version(),
platform: ${process.platform} ${process.arch},
outputDir: testInfo.outputDir,
stagingDir
}
};
}The core case is:
const destination = await allocateDestination(
testInfo, 'accepted', 'case-a.csv'
);
const downloadPromise = page.waitForEvent('download', { timeout: 3_000 });
await page.locator('#good').click();
const download = await downloadPromise;
const stagedPath = await download.path();
await download.saveAs(destination);
const transferFailure = await download.failure();
assert.equal(transferFailure, null);
await context.close();
const actual = await fs.readFile(destination);
assert.deepStrictEqual(actual, EXPECTED);download.failure() waits for the transfer outcome and returns null when there is no download error. A null transfer failure is not a content verdict: the byte assertion still has to run.
The Download object may remain referenced for metadata in JavaScript, but that does not make its browser-managed staging path caller-owned. The saved destination and the staged path have different owners.
Read the destination through a fresh handle
The consumer should open the path again rather than reuse data already held during the browser phase:
const crypto = require('node:crypto');
const actual = await fs.readFile(destination);
assert.deepStrictEqual(actual, EXPECTED);
const evidence = {
bytes: actual.length,
sha256: crypto.createHash('sha256').update(actual).digest('hex')
};The byte count and digest are useful identifiers in an evidence record, but neither is an independent oracle when calculated only from the received file. The independent reference here is the predefined EXPECTED buffer.
Scope the conclusion precisely: the test-owned copy is readable by a fresh filesystem operation on the same runner after this producing browser context has closed, while the test output directory still exists.
Hold the final chunk to expose the completion boundary
A fast 16-byte response can hide the distinction between download-start and download-complete. The gated endpoint keeps that boundary visible without sleeps.
It sends an accurate Content-Length, flushes headers, writes a nonempty prefix, then waits for an explicit in-process release before sending the remaining bytes. The download event is expected at download start, while saveAs() is documented to wait for an in-progress transfer to finish.
The test sequence is:
const ledger = [];
let sequence = 0;
const mark = name => ledger.push({ sequence: ++sequence, name });
const server = await startFixtureServer({ mark });
const gate = server.armGate();
await page.goto(server.baseURL);
mark('start');
const downloadPromise = page.waitForEvent('download', { timeout: 3_000 });
await page.locator('#gated').click();
const download = await downloadPromise;
const destination = await allocateDestination(
testInfo, 'accepted', 'gated.csv'
);
const copyPromise = download.saveAs(destination).then(() => {
mark('copy-resolved');
});
await gate.prefixSent;
gate.release();
await gate.finalChunkReleased;
await copyPromise;
await context.close();
const actual = await fs.readFile(destination);
mark('post-close-read');
assert.deepStrictEqual(actual, EXPECTED);Do not write this:
await download.saveAs(destination);
gate.release();The endpoint is waiting for the test to release the final bytes, while saveAs() is waiting for the transfer to finish. Awaiting the copy before releasing the gate creates a harness deadlock.
Record the order without a sleep
The correlated ledger should contain these logical markers:
start
prefix-sent
final-chunk-released
copy-resolved
post-close-readUse promises for the gate and explicit timeouts for operations that can fail to happen. There is no need to guess the exact instant Chromium flushed bytes to disk.
Because browser buffering behavior is implementation-sensitive, do not turn the chosen eight-byte prefix into an unsupported universal assumption. If a conforming run does not surface the download event while the prefix is held, record the package version, browser version, OS, response shape, path configuration, method order, and error class; adjust the controlled fixture and rerun. Leave the ordering claim unresolved until the behavior is reproducible.
Expected result: once the final chunk is released, the pending saveAs() resolves; after context closure, a fresh read of its destination matches EXPECTED. No execution observation is claimed here.
Reject the wrong export even after a successful copy
A successful copy proves that some attachment was copied. It does not prove the attachment was the intended export.
Change only the route:
const downloadPromise = page.waitForEvent('download', { timeout: 3_000 });
await page.locator('#wrong').click();
const download = await downloadPromise;
assert.equal(download.suggestedFilename(), 'report.csv');
await download.saveAs(destination);
assert.equal(await download.failure(), null);
await context.close();
const actual = await fs.readFile(destination);
assert.deepStrictEqual(actual, EXPECTED);The wrong route still provides valid CSV, the same MIME type, the same advisory filename, and the same byte count. A content validator must reject it.
This is the same reason checking downloaded bytes after a curl retry is a separate concern from transport success: here there is no retry or partial replay, but independent bytes still determine whether the consumer received the intended object.
Playwright Test’s test.fail() annotation runs an expected-failure test and verifies that it actually fails. Use it for the deliberate control:
test.fail('wrong export is rejected by the byte oracle', async ({}, testInfo) => {
// perform wrong-route download, saveAs(), close context...
const actual = await fs.readFile(destination);
assert.deepStrictEqual(actual, EXPECTED);
});If that test unexpectedly passes, the negative control is broken.
Make the differentiating row visible
The entire distinction is:
expected row ID: A7
actual row ID: B7The filenames can both be report.csv. The lengths can match. The copies can both complete successfully. Equality with a constant fixture is appropriate because this synthetic contract defines exact bytes.
In a real application where row ordering, quoting, newline convention, BOM handling, or encoding is intentionally variable, the export owner must define a semantic CSV contract. Designing that parser is outside this playbook; do not quietly replace an exact fixture contract with unspecified normalization.
Cancel a deliberately unfinished transfer
Cancellation deserves its own controlled case because “cancel() returned” is not enough.
Arm the gated response, wait for the download to start while the final bytes remain withheld, then cancel it:
const gate = server.armGate();
const downloadPromise = page.waitForEvent('download', { timeout: 3_000 });
await page.locator('#gated').click();
const download = await downloadPromise;
await gate.prefixSent;
await download.cancel();
const failure = await download.failure();
assert.equal(failure, 'canceled');Playwright documents that successful cancellation makes download.failure() resolve to 'canceled'. It also says cancel() does not fail when the download has already finished or was already canceled, so the mere successful return from cancel() is inconclusive.
Do not call saveAs() into the accepted destination for this case. Assert only that no accepted file was created by your harness:
const accepted = testInfo.outputPath('accepted', 'canceled.csv');
await assert.rejects(
fs.access(accepted),
error => error.code === 'ENOENT'
);The server’s abort/close listeners release its gate so teardown is bounded. Do not assert a universal rule about browser-internal partial residues; that is outside the acceptance set. The relevant verdict is that a canceled transfer contributes no file to the caller-owned accepted set.
Give identical suggested names separate destinations
Now test the collision scenario explicitly. Two downloads may both suggest report.csv; RFC 6266 says that filename is advisory, and Playwright notes browser-specific logic may be involved in computing suggestedFilename().
Give each case an output selected before the download:
const destinationA = await allocateDestination(
testInfo, 'accepted', 'case-a.csv'
);
const destinationB = await allocateDestination(
testInfo, 'accepted', 'case-b.csv'
);Case A downloads /export-good.csv, saves to case-a.csv, and closes its context. Case B uses a fresh manually created context, downloads /export-wrong.csv, saves to case-b.csv, and closes that context.
Then reopen both:
const actualA = await fs.readFile(destinationA);
const actualB = await fs.readFile(destinationB);
assert.deepStrictEqual(actualA, EXPECTED);
assert.deepStrictEqual(actualB, WRONG);Both may legitimately record:
assert.equal(downloadA.suggestedFilename(), 'report.csv');
assert.equal(downloadB.suggestedFilename(), 'report.csv');The destination is therefore a test ownership decision, not a server naming decision.
testInfo.outputPath() isolates different tests from each other. Two writes inside the same test still need distinct paths chosen by that test. If a destination already exists during setup, fail or allocate a new run-scoped path. Never erase a shared directory merely to turn a stale-file condition green.
That rule prevents a prior run’s correct case-a.csv from satisfying today’s case merely because the old file happened to remain on disk.
Reconcile the browser events with the file evidence
Preserve one record per case rather than compressing all outcomes into “download succeeded.” That same evidence discipline underlies first-attempt evidence in Playwright, although retries remain disabled in this lab.
A worksheet for this fixture is:
Download event and transfer
Case/run ID | Route | Event observed | Suggested label | Transfer status |
case-missing / ___ | /export-good.csv | ___ | ___ | ___ |
case-save / ___ | /export-good.csv | ___ | ___ | ___ |
case-gated / ___ | /export-gated.csv | ___ | ___ | ___ |
case-wrong / ___ | /export-wrong.csv | ___ | ___ | ___ |
case-cancel / ___ | /export-gated.csv | ___ | ___ | expected canceled |
case-same-name-a / ___ | /export-good.csv | ___ | expected report.csv | ___ |
case-same-name-b / ___ | /export-wrong.csv | ___ | expected report.csv | ___ |
Staged file and saved destination
Case/run ID | Managed source after close | Destination | Post-close read |
case-missing / ___ | ___ | not applicable | not applicable |
case-save / ___ | optional sample | accepted/case-a.csv | ___ |
case-gated / ___ | not required | accepted/gated.csv | ___ |
case-wrong / ___ | not required | accepted/wrong.csv | ___ |
case-cancel / ___ | not applicable | none accepted | not applicable |
case-same-name-a / ___ | not required | accepted/case-a.csv | ___ |
case-same-name-b / ___ | not required | accepted/case-b.csv | ___ |
Content check and verdict
Case/run ID | Expected identity | Actual identity | Verdict |
case-missing / ___ | A7 fixture | ___ | ___ |
case-save / ___ | A7 fixture | ___ | ___ |
case-gated / ___ | A7 fixture | ___ | ___ |
case-wrong / ___ | A7 fixture | ___ | expected B7 |
case-cancel / ___ | not applicable | not applicable | ___ |
case-same-name-a / ___ | A7 | ___ | ___ |
case-same-name-b / ___ | B7 | ___ | ___ |
Fill the blank cells with observations from your bundled Chromium run.
Keep environment and ledger records under the test-owned output:
const evidencePath = testInfo.outputPath('evidence', 'record.json');
await fs.mkdir(path.dirname(evidencePath), { recursive: true });
await fs.writeFile(
evidencePath,
JSON.stringify({ environment, ledger, worksheetRow }, null, 2)
);
A missing managed file after closure indicates lifecycle loss. A missing caller destination indicates no usable copy. Non-null failure() indicates a transfer problem. A readable destination with unequal bytes indicates wrong content. These are different diagnoses.
Decide when the consumer can accept the export
The acceptance rule is intentionally local and conservative:
Evidence after context closure | Decision |
Current case produced the destination; fresh read succeeds; bytes equal the independent expected payload | Hand off locally |
Fresh read succeeds but bytes differ | Reject |
Transfer reports canceled | Reject |
No caller-owned destination exists | Reject as unavailable for consumption |
Unknown I/O error, missing environment evidence, or lab could not run | Hold and repeat one bounded case |
Negative control fails exactly because wrong bytes are rejected | Validator control succeeded |
Negative control unexpectedly passes | Reject validator as ineffective |
The phrase “current case produced the destination” matters. A correct old file is not evidence about today’s export.
An expected failure can therefore represent a successful test-suite check: test.fail() is supposed to execute the case and ensure that it actually fails. In the wrong-export control, the suite succeeds at its purpose precisely when the validator refuses B7.
Assign each ambiguous result to an owner
Give ambiguity to the owner who can reproduce the relevant boundary.
If the QA owner sees no download event, provide the case ID, route, registered-listener timestamp, click timestamp, event timeout, Playwright version, and browser version; rerun only the event-ordering case with the listener armed before the click.
If the export owner receives a completed saved copy whose bytes contain B7 instead of independently expected A7, provide the saved file, route, expected fixture identity, byte count, digest, and case ID; rerun the wrong-content case after the source data or export implementation is corrected.
If the runner owner sees EACCES, premature deletion of testInfo.outputDir, or another output-path failure, provide the absolute output directory, destination, filesystem error class/code, Node version, OS, and runner cleanup timing; rerun the clean saved-copy case.
Do not silently replace the failed record with the rerun. Preserve the original case record and give the bounded rerun a new run ID.
Recover a missing export in a fresh run
If the only completed file was the browser-managed staged download and its context has already closed, the documented ownership contract gives you no caller-owned file to hand off. Playwright says context-owned downloads are deleted on context close, including when downloadsPath was explicitly configured.
Repeat the deterministic export in a fresh context with a fresh destination:
old: accepted/run-014/case-a.csv -> unavailable or untrusted
new: accepted/run-015/case-a.csv -> current candidateArm the download wait before clicking, call saveAs() while the new context remains open, await it, close the context, and perform a new readFile() against the new path. Compare that copy with the new run’s own expected case identity.
If a saved copy already exists but fails its independent expected bytes, do not “recover” it by renaming it or accepting its filename. Keep it out of handoff until the producing source or the assertion contract is corrected.
This procedure is scoped to the deterministic synthetic export. It is not a retry policy for arbitrary production operations.
A later CI job requires a separate, explicit artifact handoff and retention mechanism for the verified caller-owned file; that boundary is outside this article, as are details such as file modes after a GitHub Actions artifact handoff.
Bring export acceptance into QA automation practice
The reusable handoff is small: publish the test-owned destination, case/run identity, and verified expected-content result beside the export case result. Do not hand another step a browser staging path merely because a download event and plausible filename were observed.
Playwright’s contracts give the lifecycle boundaries: register the event wait before the click; treat the event as attachment start; use saveAs() to create the caller-selected copy; remember that context-owned downloads are deleted when the context closes; and use a fresh post-close filesystem read as the consumer-side acceptance point.
For engineers seeking structured practice around repeatable automation, Refonte Learning’s Quality Assurance Automation Engineering Program lists a three-month, 12–14-hours-per-week curriculum covering automated test-script writing and execution, automation frameworks, CI/CD integration, performance testing, and practical QA projects; its listed outcomes include QA Automation Engineer, QA Engineer, and Software Tester.
