How do I generate and save HAR files during test running in Playwright?


Sure, you can generate HAR files with @playwright/test. Use the --save-har option with the Playwright CLI. This option lets you create a HAR file during your test run.

Here's how you do it:

npx playwright open --save-har=example.har https://ray.run

This command opens the browser, navigates to https://ray.run, and saves all API requests as "example.har" in your current directory.

Want to save specific API endpoints? Use the --save-har-glob option. This lets you specify a glob pattern that matches only certain requests for inclusion in the HAR file. Here's an example:

npx playwright open --save-har=example.har --save-har-glob="**/api/**" https://ray.run

In this case, only API requests that have "/api/" in their URL will be saved in the "example.har" file.

If your HAR file name ends with ".zip", all artifacts will be written as separate files and compressed into a single zip archive.

Playwright also has methods like page.routeFromHAR() or browserContext.routeFromHAR() for recording or updating existing HAR files. These methods let you serve requests from a specified path to simulate network responses during testing.

To modify an existing HAR file, just edit its corresponding hashed .txt file inside your 'hars' folder and update the JSON data. Don't forget to commit this modified HAR file to your source control.

To replay a modified HAR file and serve matching responses in your test, turn off or remove the update option when using page.routeFromHAR(). This will run the test against the HAR file instead of hitting the actual API.


Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

Related Discord Threads

Related Questions

AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.