Generate HAR files from Playwright test execution
npm install playwright-har!npm
playwright-har is capturing HAR files) from browser network traffic and saves them to simplify debugging of failed tests.
This is a port of puppeteer-har that was adjusted to work with Playwright.
```
npm i --save playwright-har
`ts
import { chromium } from 'playwright'
import { PlaywrightHar } from 'playwright-har'
(async () => {
const browser = await chromium.launch();
const context = await browser.newContext();
const page = await context.newPage();
const playwrightHar = new PlaywrightHar(page);
await playwrightHar.start();
await page.goto('http://whatsmyuseragent.org/');
// ... other actions ...
await playwrightHar.stop('./example.har');
await browser.close();
})();
`
In CustomEnvironment.js :
`js
const PlaywrightEnvironment = require('jest-playwright-preset/lib/PlaywrightEnvironment').default
const { PlaywrightHar } = require('playwright-har');
class CustomEnvironment extends PlaywrightEnvironment {
constructor(config, context) {
super(config, context);
this.playwrightHar;
}
async handleTestEvent(event) {
if (event.name == 'test_start') {
if (this.global.browserName === 'chromium') {
this.playwrightHar = new PlaywrightHar(this.global.page);
await this.playwrightHar.start();
}
}
if (event.name == 'test_done') {
if (this.global.browserName === 'chromium') {
const parentName = event.test.parent.name.replace(/\W/g, '-');
const specName = event.test.name.replace(/\W/g, '-');
await this.playwrightHar.stop(./${parentName}_${specName}.har);
}
}
}
}
module.exports = CustomEnvironment;
`
This setup will create PlaywrightHar instance for each test statement in describe statement in spec file. Browser network traffic will be collected from this step execution and save it in .har file with name corresponding to describe name followed by test name.
* HAR files collection works only on chromium browser
* stop() has an optional argument path` - when specified, generated HAR file will be saved into provided path, otherwise it will be returned as an object