PlaywrightのtestInfo.attachでレポートに添付する方法
CI で E2E テストが失敗したとき、そのときの API の応答や画面、テストの中で書き出したファイルがレポートに残っていると、原因を調べやすくなります。Playwright では、テストの中で testInfo.attach() を呼ぶと、文字列や Buffer、ディスク上のファイルを、そのテストの添付(attachment)として HTML レポートなどに付けられます。
検証環境で、文字列・JSON・スクリーンショット・CSV ファイルを付け、レポートのどこに何が残るかを確かめました。await を付け忘れたときに添付が残らないことがある点も、20回ずつ動かして比べています。
検証環境は Ubuntu 24.04、Node.js 22.23.5、@playwright/test 1.63.0(Chromium 158.0.8127.36、ヘッドレス)、TypeScript 5.9.3 です。レポーターは list・html・json の3つを同時に使いました(await の有無を20回ずつ比べたときだけは json のみ)。ページは page.setContent() で作っています。Firefox と WebKit、Windows と macOS、junit などほかのレポーターは試していません。
body で値を、path でファイルを付ける
testInfo.attach() の API リファレンスによると、第1引数は添付の名前で、第2引数には中身として body(文字列か Buffer)か path(ファイルのパス)のどちらかを渡します。testInfo は、テストの関数の2つ目の引数で受け取れます。
猫の一覧のページを開き、5種類の添付を付けるテストを書きました。
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. 文字列を、そのまま付ける(contentType を書かない)
await testInfo.attach('メモ', { body: '一覧には2匹が出ていた' });
// 2. JSON の文字列を、contentType を付けて付ける
const cats = await page.getByRole('listitem').allTextContents();
await testInfo.attach('一覧の中身', {
body: JSON.stringify({ cats }, null, 2),
contentType: 'application/json',
});
// 3. スクリーンショットの Buffer を付ける
const png = await page.screenshot();
await testInfo.attach('一覧の画面', { body: png, contentType: 'image/png' });
// 4. ファイルを書いて、path で付ける(contentType は拡張子から決まる)
const csvPath = testInfo.outputPath('cats.csv');
await writeFile(csvPath, '名前,年齢\nたま,3\nみけ,5\n');
await testInfo.attach('書き出した CSV', { path: csvPath });
// attach のあとで元のファイルを消す
await rm(csvPath);
// 5. Buffer を 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 なし)');
}
});
最後の for で、付けた添付の一覧(testInfo.attachments)を出しています。実行すると、テストは通り、次のように出ました。作業ディレクトリのパスは /path/to/app に置き換えています。
$ 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)
contentType を書かなかった添付は、文字列なら text/plain、Buffer なら application/octet-stream になりました。path で付けた CSV は、拡張子から text/csv になっています。API リファレンスの contentType の説明にも、省くと path から決め、それができなければ文字列は text/plain、Buffer は application/octet-stream にすると書かれています。
contentType は、レポートでの見せ方を決めるのに使われます(あとの「HTML レポートと list レポーターでの見え方」の画像)。JSON やスクリーンショットを付けるときは、application/json や image/png を書いておきます。
path で付けたファイルは、元を消してもレポートに残る
上のテストでは、CSV を attach() したすぐあとに、元のファイルを rm() で消しました。それでも、添付の path は元のファイルとは別の場所(test-results/<テストごとのフォルダ>/attachments/)を指していて、そこに中身が残っていました。テストのあとで、その CSV を表示した結果です。
$ cat test-results/*/attachments/*.csv
名前,年齢
たま,3
みけ,5
ファイル名は、添付の名前(空白は - に置き換わる)のあとに、長い英数字と拡張子が付いた形でした。API リファレンスにも、attach() は付けたファイルをレポーターが読める場所へコピーするので、attach() を await したあとなら元のファイルを消してよいと書かれています。
HTML レポート(playwright-report/)の側では、data/ フォルダに次の3つのファイルができました。PNG と CSV と、application/octet-stream で付けた Buffer です。
playwright-report/data/0c7a623fd2bbc05b06423be359e4021d36e721ad.bin
playwright-report/data/5bd823bf6d115cfdaf6ed5971ee70332453bd4f5.csv
playwright-report/data/c3799c7412299be03dac2792e818a6a5131b88f8.png
playwright-report/index.html
text/plain と application/json の2つは、data/ にファイルができませんでした。この2つは、次の節の画像のように、HTML レポートの中に文字として出ます。data/ の CSV の中身も、元のファイルと同じでした。
HTML レポートと list レポーターでの見え方
添付を付けたテストが失敗したときに、レポートにどう出るかを確かめました。一覧に3匹いるはずなのに2匹しかいない、というテストです。
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 });
});
HTML レポートでこのテストを開くと、image/png の添付は「Screenshots」の欄に画像として出ました。JSON とテキストの添付は「Attachments」の欄に名前が並び、名前をクリックして開くと、中身の文字がそのまま出ました。

その下の error-context は、自分では付けていません。テストが失敗したときに、Playwright が自動で付けたものです(json レポーターの出力では text/markdown の添付でした)。
一方、ターミナルに出る list レポーターの出力では、出た添付は text/plain の「メモ」だけでした。次の出力は、失敗の詳細のうちエラーの部分を省いて、そのあとを抜き出したものです。
attachment #2: メモ (text/plain) ─────────────────────────────────────────────────────────────────
3匹のはずが、2匹しかいない
────────────────────────────────────────────────────────────────────────────────────────────────
Error Context: test-results/fail-失敗したテストにも、付けたものが出る/error-context.md
番号が #2 になっているとおり、1つ目の JSON(body で付けた application/json)と3つ目の PNG は、list レポーターの出力には出ませんでした。ターミナルのログだけで原因を追いたいときは、短い文字列を text/plain で付けておくと、失敗の詳細と一緒に読めます。なお、通ったテストでは、list レポーターに添付は出ませんでした(最初のテストの出力)。
await を付けずに元のファイルを消すと、添付が残らないことがある
attach() は Promise を返します。await を付けずに呼び、そのまま元のファイルを消してテストを終えるとどうなるかを確かめました。
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);
});
テストは通り、エラーも警告も出ませんでした。ところが json レポーターの出力を見ると、attachments は空([])で、HTML レポートの data/ にも CSV はありませんでした。一方で、test-results/…/attachments/ には CSV のコピーができていました。ファイルはコピーされているのに、テストの結果の添付には入っていない、という状態です。
この結果は、実行するたびに変わりました。そこで、await なしのテストと、同じテストの attach() に await を付けたものを、npx playwright test --reporter=json でそれぞれ20回動かしました。毎回、json レポーターの出力からテストの結果(status)と添付の数(attachments.length)を取り出して並べると、次のとおりです。passed:1 は添付が1件載った回、passed:0 は載らなかった回です。出力の見出しの行は、分かりやすく書き換えています。
# await なし(20回)
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
# await あり(20回)
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
await を付けなかった20回のうち、添付が載ったのは4回で、残りの16回は載りませんでした。await testInfo.attach(...) と書いたほうは、20回とも載りました。前の節で引いた API リファレンスの注意書きも、元のファイルを消してよいのは attach() を「await したあと」としています。添付が付いたり付かなかったりするときは、attach() の前に await があるかを見直します。
ヘルパー関数の中から付けるときは test.info()
ページの状態を記録する処理をヘルパー関数にまとめると、関数の引数に testInfo を足す必要があります。test.info() を使うと、実行中のテストの TestInfo を、引数で受け取らずに取り出せます。
async function attachList(page: import('@playwright/test').Page) {
const cats = await page.getByRole('listitem').allTextContents();
// 引数で testInfo を受け取らなくても、test.info() で今のテストの TestInfo を取れる
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}`));
});
[ '一覧の中身 application/json' ]
✓ 1 tests/test-info.spec.ts:9:5 › ヘルパー関数の中から付ける (99ms)
test.step() の中で呼んだ場合も、添付はテストの attachments に入り、json レポーターの出力にも載りました。
path と body を両方渡すとエラーになる
path と body は、どちらか一方だけを渡します。両方を渡すと、テストは次のエラーで失敗しました。
await testInfo.attach('両方', { body: 'abc', path: testInfo.outputPath('x.txt') });
Error: Exactly one of "path" and "body" must be specified
ファイルの中身をすでに文字列や Buffer で持っているなら body、ディスクにあるファイルをそのまま付けるなら path を選びます。path で付けるファイルの置き場所には、上の例のように testInfo.outputPath() を使うと、並列で動くほかのテストとファイルがぶつかりません(API リファレンスの説明による)。





