Mastering Playwright: Learn secure HAR-Based Mocking in Playwright

JagsJags
2 min read

To start, you'll need to record all necessary network calls into a HAR (HTTP Archive) file. The process for doing so varies slightly depending on the browser you're using.

Next, you'll want to sanitize your HAR file to remove any sensitive information that could compromise security. This includes:

  • Authorization headers and tokens

  • Traceparent and IP addresses

  • x-* headers (and any other headers you deem private or sensitive)

You can use tools like https://har- sanitizer.pages.dev/ or https://github.com/google/har-sanitizer to sanitize your HAR files. For a deeper dive into how sanitization works, you can check out the code at https://github.com/cloudflare/har-sanitizer/blob/main/src/lib/har_sanitize.tsx

Finally, save your sanitized HAR file in a folder and update your Playwright code using the following as reference:

Docs: https://playwright.dev/docs/mock#mocking-with-har-files

await page.routeFromHAR(filePath, {
  url: '**/graphql',
  update: false
 });
await page.reload();

Test and Optimize:
After setting up your HAR files, run your tests to ensure everything is working as expected. Use the results to optimize your tests and improve their efficiency.

Using Fixtures:
If you're using fixtures to manage your test data, you can add the following code to get started:

Fixture Code for reference:

export const applyHarFileMock = async (page: Page, filePath: string) =>
  await page.routeFromHAR(filePath, {
    url: '**/graphql',
    update: false,
  });

Usage code for reference:

test.use({
  storageState: "<path>",
  actionTimeout: 2000,
  mockFromHarFile: './e2e/har-files/sanitized_replay_har.har',
});

Note that this code should be tailored to your specific use case and testing environment.

0
Subscribe to my newsletter

Read articles from Jags directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Jags
Jags

I am Senior Test Automation Engineer, who is interested in Open Source & Quality at scale.