DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Architecting a Comprehensive Testing Framework for API and UI Testing
  • Cypress API Testing: A Detailed Guide
  • Which API Testing Strategy Should You Use? Manual vs. Automated
  • What Is API-First?

Trending

  • The 4 R’s of Pipeline Reliability: Designing Data Systems That Last
  • Event-Driven Architectures: Designing Scalable and Resilient Cloud Solutions
  • Java Virtual Threads and Scaling
  • Evolution of Cloud Services for MCP/A2A Protocols in AI Agents
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Mock The API Data (Request and Responses) With Playwright

Mock The API Data (Request and Responses) With Playwright

Mocking API responses refers to the practice of creating simulated responses from an API without actually interacting with the real API.

By 
Kailash Pathak user avatar
Kailash Pathak
DZone Core CORE ·
Jun. 05, 24 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
3.9K Views

Join the DZone community and get the full member experience.

Join For Free

Mocking API responses refers to the practice of creating simulated responses from an API without actually interacting with the real API. This technique is commonly used in software development, especially during testing phases, to mimic the behavior of real API endpoints. By using mock responses, developers can isolate specific parts of their code for testing purposes without relying on external services, thus enabling more efficient and controlled testing environments.

There are various tools and libraries available for mocking API responses in different programming languages and frameworks. Mocking API responses with Playwright is a useful technique for testing your web applications without relying on real API servers. It allows you to simulate different scenarios and responses from your APIs, making your tests more robust and independent of external services.

How Mocking Is Beneficial

Mocking API responses using tools like Playwright can offer several benefits. Some of the benefit explained below

  • Isolation for testing: By mocking API responses, you can isolate the testing of front-end and back-end components. This means that you can thoroughly test the behavior of your front-end application without being dependent on the availability or consistency of the back-end services.
  • Efficiency in testing: Mocking responses allows testers to simulate various scenarios and edge cases without relying on the actual back-end infrastructure. This can speed up the testing process significantly, as you can quickly simulate different responses without waiting for the actual APIs to respond.
  • Controlled testing environment: With mocked responses, you have full control over the data and scenarios your tests encounter. This allows you to create specific test cases to cover various scenarios, such as successful responses, error responses, or edge cases.
  • Cost reduction: Using mocked responses reduces the need for making actual API calls during testing, which can save on API usage costs, especially when dealing with third-party services that may have usage-based pricing models.
  • Testing edge cases: With mocked API responses, you can simulate various scenarios, including error conditions, edge cases, and situations that might be difficult or impossible to reproduce with the actual API. This enables more comprehensive testing of your application’s error handling and resilience.

Mocking Data Using Playwright

In Playwright, the page.route() method is used to intercept and modify network requests made by a web page. This method allows you to intercept specific requests and respond to them programmatically.

Here’s how the page.route() method works:

Route Setup

You call the page.route() method and provide a URL pattern or a predicate function that matches the requests you want to handle. The method returns a Route object.

JavaScript
 
const route = await page.route('**/api/data', route => {…});


Request Interception

When the page makes a request that matches the specified URL pattern or predicate function, Playwright intercepts the request and pauses it before sending it out.

Request Handling

The page.route() method takes a callback function that receives the intercepted Route object. Within this callback, you can perform various actions on the intercepted request:

  • Continue the request: Call route.continue() to allow the request to be sent as-is.
  • Fulfill the request: Call route.fulfill() to provide a custom response for the request without sending it to the server.
  • Abort the request: Call route.abort() to cancel the request and return an error.

Response Handling

If you continue the request, Playwright will receive the response from the server and complete the request lifecycle. If you fulfilled the request, the provided custom response will be used instead.

Mocking API Data in Playwright

In Playwright, using the page.route() method, you can indeed mock data at both the time of request interception and response interception.

Mocking Data at the Time of Request

When a request is intercepted, you have the opportunity to modify it before it is sent. This means you can manipulate the request headers, body, URL, method, etc. to match your testing scenario or to simulate different conditions. For example, you can change the request parameters, add custom headers, or even redirect the request to a different endpoint.

Mocking Data at the Time of Response

Once the request is sent, and a response is received (or intercepted), you can also modify the response data before it reaches the browser. This allows you to simulate various server responses without actually making requests to the server. You can provide custom response bodies, set specific HTTP status codes, modify response headers, or even simulate error conditions.

Example Mocking API Data In Playwright

Here’s a simple example demonstrating the usage of page.route() in Playwright:

Let’s say you have a web page that makes a request to an API endpoint. You want to intercept this request and provide a mock response for testing purposes.

Mocking Data at the Time of Requesting the Data

Let’s consider the example of the “api-mocking” demo from the Playwright website. Here’s how we can use Playwright to mock the API response at the time of the request:

JavaScript
 
const { test, expect } = require("@playwright/test");
test("mocks a fruit and doesn't call api", async ({ page }) => {
 // Mock the api call before navigating
 await page.route("*/**/api/v1/fruits", async (route) => {
 const json = [
 { name: "Lucuma", id: 11 },
 { name: "Guava", id: 12 },
 { name: "Kiwi", id: 13 },
 { name: "Peach", id: 14 },
 { name: "Fig", id: 15 },
 ];
 await route.fulfill({ json });
 });
 // Go to the page
 await page.goto("https://demo.playwright.dev/api-mocking");
 // Assert that the Raspberries fruit is visible
 await expect(page.getByText("Guava")).toBeVisible();
});


Code Walkthrough

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

This line imports the test and expect functions from the Playwright testing library.

JavaScript
 
test("mocks a fruit and doesn't call api", async ({ page }) => {
 // …
});


This is a Playwright test case. The test function takes a description string and an asynchronous callback function. The callback function receives an object with the page property, which represents the browser page instance.

JavaScript
 
await page.route("\\*\\/\*\\/api/v1/fruits", async (route) => {
 const json = [
 { name: "Lucuma", id: 11 },
 { name: "Guava", id: 12 },
 { name: "Kiwi", id: 13 },
 { name: "Peach", id: 14 },
 { name: "Fig", id: 15 },
 ];
 await route.fulfill({ json });
});


This part of the code sets up a mock for the /api/v1/fruits API route. Whenever the browser navigates to a URL that matches this route pattern, the provided callback function will be executed. Inside the callback, an array of fruit objects is created, and the route.fulfill method is called with this array as the response data. This means that instead of making an actual API call, the test will receive the mocked data.

JavaScript
 
await page.goto("https://demo.playwright.dev/api-mocking");


This line navigates the browser page to the specified URL.

JavaScript
 
await expect(page.getByText("Guava")).toBeVisible();


After navigating to the page, this line asserts that the text “Guava” (which is one of the mocked fruit names) is visible on the page. The getByText method is used to retrieve the element containing the given text, and the toBeVisible assertion checks if that element is visible.

Execute the Test Case

Let’s execute the test case using below command:

npx playwright test tests/mockRequest.spec.js - ui


In the screenshot below you can see five fruits that we added or / mock displaying in below screen.

render a list of fruits

Mocking Data at the Time of Getting the Response

Let’s look at an example of mocking data at the time of the response using the this URL.

JavaScript
 
const { test, expect } = require("@playwright/test");
test("Modify API responses ", async ({ page }) => {
 // Get the response and add to it
 await page.route("*/**/api/v1/fruits", async (route) => {
 const response = await route.fetch();
 const json = await response.json();
 json.push(
 { name: "Dragon fruit", id: 11 },
 { name: "Gooseberries", id: 12 },
 { name: "Coconut", id: 13 }
 );
 // Fulfill using the original response, to modify the response with given JSON object.
 await route.fulfill({ response, json });
 });
 // Go to the page
 await page.goto("https://demo.playwright.dev/api-mocking");
 // Assert to verify that the new fruit is visible
 await expect(page.getByText("Dragon fruit", { exact: true })).toBeVisible();
});


Code Walkthrough

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


This line imports the test and expect functions from the @playwright/test module. The test function is used to define a test case, and the expect function is used for making assertions in the test case.

JavaScript
 
test("Modify API responses ", async ({ page }) => {


Inside the test function, an asynchronous function is defined using the async keyword. This function takes a page object as a parameter, which represents the browser page that Playwright will interact with.

JavaScript
 
await page.route("\\*/\\*\\*/api/v1/fruits", async (route) => {


This line sets up a route interception for any URLs that match the pattern */*/api/v1/fruits. The async function passed as the second argument to page.route will be called whenever a request matches this pattern.

JavaScript
 
const response = await route.fetch();
const json = await response.json();


Inside the async function, route.fetch() is used to fetch the original response for the intercepted request. Then, response.json() is used to parse the response body as JSON.

JavaScript
 
json.push(
 { name: "Dragon fruit", id: 11 },
 { name: "Apple", id: 12 },
 { name: "Mango", id: 13 }
);


This line modifies the parsed JSON data by adding three new objects representing fruits. js.

JavaScript
 
await route.fulfill({ response, json });


The route.fulfill method is used to fulfill the intercepted request with a modified response. The response option is set to the original response object, and the json option is set to the modified JSON data.

JavaScript
 
await page.goto("https://demo.playwright.dev/api-mocking");


This line navigates the browser page to the URL.

await expect(page.getByText(“Dragon fruit”, { exact: true })).toBeVisible();

Finally, this line asserts that the text “Dragon fruit” is visible on the page. The page.getByText method is used to select an element containing the specified text, and the expect(…).toBeVisible() assertion checks if the selected element is visible on the page.

Modern software development requires API testing, and Playwright offers a strong, adaptable framework for building thorough API test suites. You can create tests that cover every step of the application flow with Playwright, from interacting with UI elements to submitting API queries and validating the responses. As a result, Playwright turns into an extraordinarily comprehensive tool that enables you to test the UI’s connection with the API and provides you with a comprehensive understanding of your application’s capabilities.

Execute the Test Case

Let’s execute the test case using below command:

npx playwright test tests/mockResponce.spec.js - ui


Wrapping Up

In conclusion, mocking API responses with Playwright is a powerful technique for testing web applications that rely on external APIs. By intercepting and modifying API responses, developers can simulate various scenarios and edge cases that would be difficult to reproduce. Overall, Playwright’s API mocking capabilities provide developers with a powerful tool for building robust and reliable web applications, enabling them to write more comprehensive tests and catch potential issues earlier in the development cycle.

API Data (computing) Testing API testing

Published at DZone with permission of Kailash Pathak. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Architecting a Comprehensive Testing Framework for API and UI Testing
  • Cypress API Testing: A Detailed Guide
  • Which API Testing Strategy Should You Use? Manual vs. Automated
  • What Is API-First?

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!