日本語

How to Attach Files to Playwright Test Reports with testInfo.attach

​​Playwright​E2E Testing,TypeScript

When an E2E test fails in CI, it is easier to find the cause if the API responses, the screen, and the files the test wrote are kept in the report. In Playwright, calling testInfo.attach() inside a test attaches a string, a Buffer, or a file on disk to that test as an attachment, which then appears in the HTML report and other reports.

In a test environment, I attached a string, JSON, a screenshot, and a CSV file, and checked what appeared in the report and where. I also ran the test 20 times each to compare the results when await is left off, since the attachment is not always kept in that case.

Note

The test environment was Ubuntu 24.04, Node.js 22.23.5, @playwright/test 1.63.0 (Chromium 158.0.8127.36, headless), and TypeScript 5.9.3. I used the list, html, and json reporters together (only the json reporter was used for the 20-run comparison of await). The page was built with page.setContent(). I have not tested Firefox or WebKit, Windows or macOS, or other reporters such as junit.

Attach a value with body, or a file with path

According to the testInfo.attach() API reference, the first argument is the attachment name, and the second argument takes the content as either body (a string or Buffer) or path (a file path). testInfo is received as the second argument of the test function.

I wrote a test that opens a page listing cats and attaches five kinds of attachments.

ts
import { test, expect } from '@playwright/test';
import { writeFile, rm } from 'node:fs/promises';

const html = `
  <h1>猫の一覧</h1>
  <ul id="cats"><li>たま(3歳)</li><li>みけ(5歳)</li></ul>
`;

test('猫の一覧を確かめ、結果をレポートに付ける', async ({ page }, testInfo) => {
  await page.setContent(html);
  await expect(page.getByRole('listitem')).toHaveCount(2);

  // 1. Attach a string as-is (don't specify contentType)
  await testInfo.attach('メモ', { body: '一覧には2匹が出ていた' });

  // 2. Attach a JSON string with contentType
  const cats = await page.getByRole('listitem').allTextContents();
  await testInfo.attach('一覧の中身', {
    body: JSON.stringify({ cats }, null, 2),
    contentType: 'application/json',
  });

  // 3. Attach a screenshot Buffer
  const png = await page.screenshot();
  await testInfo.attach('一覧の画面', { body: png, contentType: 'image/png' });

  // 4. Write a file and attach it by path (contentType is determined by the extension)
  const csvPath = testInfo.outputPath('cats.csv');
  await writeFile(csvPath, '名前,年齢\nたま,3\nみけ,5\n');
  await testInfo.attach('書き出した CSV', { path: csvPath });
  // Delete the original file after attach
  await rm(csvPath);

  // 5. Attach a Buffer without contentType
  await testInfo.attach('バイナリ', { body: Buffer.from([0x00, 0x01, 0x02]) });

  for (const a of testInfo.attachments) {
    console.log(a.name, '|', a.contentType, '|', a.path ?? '(path なし)', '|', a.body ? `body ${a.body.length} bytes` : '(body なし)');
  }
});

The final for loop prints the list of attachments that were added (testInfo.attachments). When I ran it, the test passed and printed the following. I replaced the working directory path with /path/to/app.

text
$ npx playwright test

Running 1 test using 1 worker

メモ | text/plain | (path なし) | body 31 bytes
一覧の中身 | application/json | (path なし) | body 66 bytes
一覧の画面 | image/png | (path なし) | body 12037 bytes
書き出した CSV | text/csv | /path/to/app/test-results/attach-猫の一覧を確かめ、結果をレポートに付ける/attachments/書き出した-CSV-2af598197bbb87eb5db540e7e0e67e128da4447d.csv | (body なし)
バイナリ | application/octet-stream | (path なし) | body 3 bytes
  ✓  1 tests/attach.spec.ts:9:5 › 猫の一覧を確かめ、結果をレポートに付ける (151ms)

  1 passed (533ms)

When contentType was omitted, a string attachment became text/plain, and a Buffer became application/octet-stream. The CSV attached with path became text/csv, derived from its extension. The API reference for contentType also says that if it is omitted, the type is taken from path; if that is not possible, strings become text/plain and Buffers become application/octet-stream.

contentType also determines how the attachment is shown in the report (see the images in "How it looks in the HTML report and the list reporter" below). For JSON or screenshots, specify application/json or image/png.

A file attached with path stays in the report even after the original is deleted

In the test above, I deleted the CSV with rm() right after calling attach(). The attachment's path, however, pointed to a different location from the original file (test-results/<per-test folder>/attachments/), and the contents remained there. This is what I got when I displayed that CSV after the test:

text
$ cat test-results/*/attachments/*.csv
名前,年齢
たま,3
みけ,5

The file name was the attachment name (with spaces replaced by -), followed by a long alphanumeric string and the extension. The API reference also states that attach() copies the attached file to a location the reporter can read, so once you have awaited attach(), you may delete the original file.

In the HTML report (playwright-report/), three files were created in the data/ folder: the PNG, the CSV, and the Buffer attached as application/octet-stream.

text
playwright-report/data/0c7a623fd2bbc05b06423be359e4021d36e721ad.bin
playwright-report/data/5bd823bf6d115cfdaf6ed5971ee70332453bd4f5.csv
playwright-report/data/c3799c7412299be03dac2792e818a6a5131b88f8.png
playwright-report/index.html

No files were created in data/ for the two attachments text/plain and application/json. These two appear as text inside the HTML report, as shown in the image in the next section. The contents of the CSV in data/ were the same as the original file.

How it looks in the HTML report and the list reporter

I checked how the attachments appear in the report when the test that attached them fails. The test expects three cats in the list but finds only two.

ts
test('失敗したテストにも、付けたものが出る', async ({ page }, testInfo) => {
  await page.setContent('<ul><li>たま</li><li>みけ</li></ul>');
  const cats = await page.getByRole('listitem').allTextContents();
  await testInfo.attach('一覧の中身', { body: JSON.stringify({ cats }), contentType: 'application/json' });
  await testInfo.attach('メモ', { body: '3匹のはずが、2匹しかいない' });
  await testInfo.attach('一覧の画面', { body: await page.screenshot(), contentType: 'image/png' });
  await expect(page.getByRole('listitem')).toHaveCount(3, { timeout: 1000 });
});

When I opened this test in the HTML report, the image/png attachment appeared as an image in the "Screenshots" section. The JSON and text attachments were listed by name in the "Attachments" section, and clicking a name showed its text as is.

Failed test in the Playwright HTML report, with the Screenshots and Attachments sections open. Under Screenshots, an image of the page showing two rows, Tama and Mike, is shown; the attachment is named "list screen" (the label is in Japanese in the report). Under Attachments, the JSON attachment "list contents" and the text note "memo" are shown expanded, with an error-context link below them
Three attachments added with attach(), as shown in the HTML report

The error-context entry below these was not attached by me. Playwright attaches it automatically when a test fails (in the json reporter output, it was a text/markdown attachment).

In the list reporter output shown in the terminal, the only attachment displayed was the text/plain note named "memo". The following output omits the error part of the failure details and shows what follows it.

text
    attachment #2: メモ (text/plain) ─────────────────────────────────────────────────────────────────
    3匹のはずが、2匹しかいない
    ────────────────────────────────────────────────────────────────────────────────────────────────

    Error Context: test-results/fail-失敗したテストにも、付けたものが出る/error-context.md

As the number #2 shows, the first attachment (the application/json added with body) and the third (the PNG) did not appear in the list reporter output. If you want to trace the cause from the terminal log alone, attach a short string as text/plain, and it will be read together with the failure details. For tests that pass, the list reporter showed no attachments (see the output of the first test).

If you delete the original file without await, the attachment may not be kept

attach() returns a Promise. I checked what happens when it is called without await, and the original file is deleted before the test ends.

ts
test('await を付けずに attach を呼ぶ', async ({}, testInfo) => {
  const csvPath = testInfo.outputPath('cats.csv');
  await writeFile(csvPath, '名前,年齢\nたま,3\n');
  testInfo.attach('書き出した CSV', { path: csvPath }); // await がない
  await rm(csvPath);
});

The test passed, and no errors or warnings were shown. However, in the json reporter output, attachments was empty ([]), and the CSV was not in the data/ folder of the HTML report. Meanwhile, a copy of the CSV did exist in test-results/…/attachments/. The file had been copied, but it was not included in the test result's attachments.

This result varied from run to run. So I ran the test without await and the same test with await on attach() each 20 times using npx playwright test --reporter=json. Each time, I extracted the test result (status) and the number of attachments (attachments.length) from the json reporter output and lined them up as follows. passed:1 means one attachment was recorded in that run, and passed:0 means none was recorded. The heading lines in the output were rewritten for clarity.

text
# Without await (20 times)
passed:0 passed:0 passed:0 passed:0 passed:0 passed:0 passed:0 passed:0 passed:0 passed:0 passed:0 passed:1 passed:0 passed:0 passed:1 passed:0 passed:0 passed:1 passed:1 passed:0 

# With await (20 times)
passed:1 passed:1 passed:1 passed:1 passed:1 passed:1 passed:1 passed:1 passed:1 passed:1 passed:1 passed:1 passed:1 passed:1 passed:1 passed:1 passed:1 passed:1 passed:1 passed:1 

Of the 20 runs without await, the attachment was recorded in 4 and missing in the other 16. With await testInfo.attach(...), it was recorded in all 20. The API reference note quoted in the previous section also says that the original file may be deleted only after attach() has been awaited. If attachments are sometimes present and sometimes missing, check whether await is in front of attach().

Use test.info() when attaching from a helper function

If you move the code that records page state into a helper function, you need to pass testInfo into the function as an argument. With test.info(), you can get the TestInfo of the running test without receiving it as an argument.

ts
async function attachList(page: import('@playwright/test').Page) {
  const cats = await page.getByRole('listitem').allTextContents();
  // Even without receiving testInfo as an argument, you can get the current test's TestInfo with test.info()
  await test.info().attach('一覧の中身', { body: JSON.stringify({ cats }), contentType: 'application/json' });
}

test('ヘルパー関数の中から付ける', async ({ page }) => {
  await page.setContent('<ul><li>たま</li><li>みけ</li></ul>');
  await test.step('一覧を記録する', async () => {
    await attachList(page);
  });
  await expect(page.getByRole('listitem')).toHaveCount(2);
  console.log(test.info().attachments.map((a) => `${a.name} ${a.contentType}`));
});
text
[ '一覧の中身 application/json' ]
  ✓  1 tests/test-info.spec.ts:9:5 › ヘルパー関数の中から付ける (99ms)

When called inside test.step(), the attachment was also added to the test's attachments, and it appeared in the json reporter output.

Passing both path and body causes an error

Pass only one of path or body. When both were passed, the test failed with the following error:

ts
await testInfo.attach('両方', { body: 'abc', path: testInfo.outputPath('x.txt') });
text
    Error: Exactly one of "path" and "body" must be specified

Use body when you already have the content as a string or Buffer, and path when you want to attach a file that is already on disk. For the location of a file to attach with path, use testInfo.outputPath() as in the example above, so that it does not collide with files from other tests running in parallel (per the API reference).

​Posted by 86