Playwright QA Automation QA Tools

Mocking API Responses with HAR Files in Playwright and Typescript 

Mocking API Responses with HAR Files in Playwright and Typescript

In the fast-paced world of web development, testing plays a crucial role in ensuring that your application functions as expected. Mocking API responses can significantly enhance the efficiency and reliability of tests, especially when the actual API endpoints are unavailable or difficult to manipulate. In this blog, we’ll explore how to use HAR (HTTP Archive) files to mock API responses in Playwright, a powerful end-to-end testing framework. 

Introduction to Playwright and HAR Files

Overview of Playwright: 

Playwright, developed by Microsoft, is a powerful testing framework designed for automating browser interactions. It facilitates comprehensive testing of web applications by supporting multiple browsers, including Chromium, Firefox, and WebKit. With its advanced API, Playwright enables developers to script intricate browser interactions, making it well-suited for complex testing scenarios. 

What are HAR Files?

HAR (HTTP Archive) files are a standardized format used to track and record HTTP network requests and responses. They are valuable tools for debugging and testing, as they capture detailed information about all network traffic during a web session. This includes requests, responses, headers, and payloads, providing a comprehensive snapshot of the interactions between a browser and a server. 

What is Mocking API?

Mocking an API involves creating a simulated version of a real API to use for testing. Instead of connecting to a live API, which might be offline, slow, or unreliable, you use a mock API that provides predefined responses. This allows you to test how your application handles various scenarios without relying on the actual API. 

Benefits of API Mocking

Mocking API responses helps create stable and predictable test environments. It allows you to simulate various scenarios and edge cases without relying on live API endpoints, which might be unstable, slow, or return inconsistent data. 

Use Cases for Mocking in Testing

Mocking is particularly useful in scenarios where: 

  1.  The API is still under development. 
  2. The API has rate limits that could impact testing. 
  3. You need to test how your application handles different responses, such as errors or timeout 

Setting Up Playwright for API Mocking 

1. Installing Playwright

Before you start mocking API responses, you need to install Playwright in your project. Follow these steps: 

a. Initialize your project (if not already done):
npm init -y 



Wrote to /Users/saurabh.bhore/Documents/Playwright/package.json:

{

"name": "playwright",

"version": "1.0.0",

"main": "index.js",

"scripts": {

"test": "echo \"Error: no test specified\" && exit 1"

},

"keywords": [],

"author": "",

"license": "ISC",

"dependencies": {

"@playwright/test": "^1.46.0",

"playwright": "^1.46.0"

},

"devDependencies": {},

"description": ""

}
 b. Install Playwright:
npm install playwright

2. Install necessary browsers:

The playwright supports multiple browsers. You can install the necessary browser binaries using the following command: 

npx playwright install 

3. Create a Test Script File

  touch mocking.test.js

Using HAR Files to Mock API Responses

Recording HAR Files:

To mock API responses, you first need to record them into a HAR (HTTP Archive) file. HAR files capture HTTP traffic and include information about requests and responses, which is crucial for simulating API responses during testing. Here’s how you can record a HAR file using browser developer tools. 

Choose a Website and API to Mock 

Step 1: Let’s use the GitHub API  and API   ‘/users/octocat’ for hands-on practice. 

Step 2: Capture the HAR File using the Browser Developer Tool 

  • Visit https://api.github.com/users/octocat. 
  • Right-click anywhere on the page and select “Inspect” to open Chrome DevTools. 
  • Navigate to the “Network” tab. 
  • Ensure the “Preserve log” option is checked. 
  • Refresh the page to capture the network request to /users/octocat 
  • Export the Har file 
Mocking API Responses

This way, you have downloaded the HAR file and are ready to use it to mock API responses. 

Mocking APIs with HAR Files in Playwright:

1. Create a Mocking Script:   

const { test, expect } = require('@playwright/test'); 



test('mocking api using the HAR file', async ({ page }) => {

// Load the HAR file

await page.routeFromHAR('github_octocat.har', {

url: 'https://api.github.com/users/octocat',

update: false,

});



await page.goto('https://api.github.com/users/octocat');



});

When we run the above script with update=true, the HAR file is updated while navigating to the specified URL, and a JSON file containing the API response is created. 

Mocking API Responses

2. Now, let’s mock the API.

We will set update=false and modify the JSON according to our test case. Let’s add our name to the JSON file, run the script npx playwright test –ui , and see the result. 

{ 

"my_name":"Saurabh",

"login": "octocat",

"id": 583231,

"node_id": "MDQ6VXNlcjU4MzIzMQ==",

Before Output:

Before Output:

After Output: 

After Output: 

We have successfully modified the API response and mocked the API using the HAR file. 

Advanced Techniques in API Mocking

  1. Conditional Mocking:
    • Concept: Adjust mock responses based on request details (e.g., URL, headers, body). 
    • Benefit: Enables dynamic testing of various scenarios. 
    • Example: Return different responses for different types of requests. 
  2. Delayed Responses:
    • Concept: Simulate network latency by introducing delays before fulfilling responses. 
    • Benefit: Tests how your application behaves under slow network conditions 
    • Example: Implement a delay to mimic real-world network performance issues.
  3. Response Modification: 
    • Concept: Alter the response payload to test different edge cases or scenarios.
    • Benefit: Ensures your application can handle modified or unexpected data. 
    • Example: Add custom fields or change values in the response data.

Conclusion

Mocking API responses using HAR files in Playwright provides a powerful and adaptable method for testing web applications. HAR (HTTP Archive) files capture network traffic, including requests and responses, which can then be leveraged to simulate various API interactions during testing. This approach allows you to create highly reliable and efficient test scenarios by mimicking real-world conditions without making actual network requests. By incorporating HAR files into your test suites, you can ensure that your application’s behaviour remains consistent across different environments and updates. 

saurabh-bhore

Test Engineer