Mock The API Information With Playwright – DZone – Uplaza

Mocking API responses refers back to the observe of making simulated responses from an API with out really interacting with the actual API. This method is usually utilized in software program improvement, particularly throughout testing phases, to imitate the habits of actual API endpoints. By utilizing mock responses, builders can isolate particular elements of their code for testing functions with out counting on exterior companies, thus enabling extra environment friendly and managed testing environments.

There are numerous instruments and libraries accessible for mocking API responses in numerous programming languages and frameworks. Mocking API responses with Playwright is a helpful approach for testing your internet purposes with out counting on actual API servers. It lets you simulate completely different eventualities and responses out of your APIs, making your assessments extra sturdy and unbiased of exterior companies.

How Mocking Is Useful

Mocking API responses utilizing instruments like Playwright can supply a number of advantages. Among the profit defined under

  • Isolation for testing: By mocking API responses, you’ll be able to isolate the testing of front-end and back-end elements. This implies which you can totally check the habits of your front-end utility with out being depending on the supply or consistency of the back-end companies.
  • Effectivity in testing: Mocking responses permits testers to simulate varied eventualities and edge circumstances with out counting on the precise back-end infrastructure. This could velocity up the testing course of considerably, as you’ll be able to shortly simulate completely different responses with out ready for the precise APIs to reply.
  • Managed testing setting: With mocked responses, you will have full management over the info and eventualities your assessments encounter. This lets you create particular check circumstances to cowl varied eventualities, similar to profitable responses, error responses, or edge circumstances.
  • Price discount: Utilizing mocked responses reduces the necessity for making precise API calls throughout testing, which might save on API utilization prices, particularly when coping with third-party companies which will have usage-based pricing fashions.
  • Testing edge circumstances: With mocked API responses, you’ll be able to simulate varied eventualities, together with error circumstances, edge circumstances, and conditions that is perhaps tough or not possible to breed with the precise API. This allows extra complete testing of your utility’s error dealing with and resilience.

Mocking Information Utilizing Playwright

In Playwright, the web page.route() technique is used to intercept and modify community requests made by an online web page. This technique lets you intercept particular requests and reply to them programmatically.

Right here’s how the web page.route() technique works:

Route Setup

You name the web page.route() technique and supply a URL sample or a predicate operate that matches the requests you need to deal with. The tactic returns a Route object.

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

Request Interception

When the web page makes a request that matches the desired URL sample or predicate operate, Playwright intercepts the request and pauses it earlier than sending it out.

Request Dealing with

The web page.route() technique takes a callback operate that receives the intercepted Route object. Inside this callback, you’ll be able to carry out varied actions on the intercepted request:

  • Proceed the request: Name route.proceed() to permit the request to be despatched as-is.
  • Fulfill the request: Name route.fulfill() to offer a customized response for the request with out sending it to the server.
  • Abort the request: Name route.abort() to cancel the request and return an error.

Response Dealing with

In the event you proceed the request, Playwright will obtain the response from the server and full the request lifecycle. In the event you fulfilled the request, the offered customized response will likely be used as an alternative.

Mocking API Information in Playwright

In Playwright, utilizing the web page.route() technique, you’ll be able to certainly mock information at each the time of request interception and response interception.

Mocking Information on the Time of Request

When a request is intercepted, you will have the chance to switch it earlier than it’s despatched. This implies you’ll be able to manipulate the request headers, physique, URL, technique, and many others. to match your testing situation or to simulate completely different circumstances. For instance, you’ll be able to change the request parameters, add customized headers, and even redirect the request to a special endpoint.

Mocking Information on the Time of Response

As soon as the request is shipped, and a response is acquired (or intercepted), you may as well modify the response information earlier than it reaches the browser. This lets you simulate varied server responses with out really making requests to the server. You possibly can present customized response our bodies, set particular HTTP standing codes, modify response headers, and even simulate error circumstances.

Instance Mocking API Information In Playwright

Right here’s a easy instance demonstrating the utilization of web page.route() in Playwright:

Let’s say you will have an online web page that makes a request to an API endpoint. You need to intercept this request and supply a mock response for testing functions.

Mocking Information on the Time of Requesting the Information

Let’s take into account the instance of the “api-mocking” demo from the Playwright web site. Right here’s how we are able to use Playwright to mock the API response on the time of the request:

const { check, anticipate } = require("@playwright/test");
check("mocks a fruit and doesn't call api", async ({ web page }) => {
 // Mock the api name earlier than navigating
 await web 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 web page
 await web page.goto("https://demo.playwright.dev/api-mocking");
 // Assert that the Raspberries fruit is seen
 await anticipate(web page.getByText("Guava")).toBeVisible();
});

Code Walkthrough

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

This line imports the check and anticipate features from the Playwright testing library.

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

This can be a Playwright check case. The check operate takes an outline string and an asynchronous callback operate. The callback operate receives an object with the web page property, which represents the browser web page occasion.

await web 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 a part of the code units up a mock for the /api/v1/fruits API route. At any time when the browser navigates to a URL that matches this route sample, the offered callback operate will likely be executed. Contained in the callback, an array of fruit objects is created, and the route.fulfill technique is known as with this array because the response information. Which means as an alternative of constructing an precise API name, the check will obtain the mocked information.

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

This line navigates the browser web page to the desired URL.

await anticipate(web page.getByText("Guava")).toBeVisible();

After navigating to the web page, this line asserts that the textual content “Guava” (which is without doubt one of the mocked fruit names) is seen on the web page. The getByText technique is used to retrieve the ingredient containing the given textual content, and the toBeVisible assertion checks if that ingredient is seen.

Execute the Check Case

Let’s execute the check case utilizing under command:

npx playwright check assessments/mockRequest.spec.js - ui

Within the screenshot under you’ll be able to see 5 fruits that we added or / mock displaying in under display.


Mocking Information on the Time of Getting the Response

Let’s have a look at an instance of mocking information on the time of the response utilizing the this URL.

const { check, anticipate } = require("@playwright/test");
check("Modify API responses ", async ({ web page }) => {
 // Get the response and add to it
 await web page.route("*/**/api/v1/fruits", async (route) => {
 const response = await route.fetch();
 const json = await response.json();
 json.push(
 { title: "Dragon fruit", id: 11 },
 { title: "Gooseberries", id: 12 },
 { title: "Coconut", id: 13 }
 );
 // Fulfill utilizing the unique response, to switch the response with given JSON object.
 await route.fulfill({ response, json });
 });
 // Go to the web page
 await web page.goto("https://demo.playwright.dev/api-mocking");
 // Assert to confirm that the brand new fruit is seen
 await anticipate(web page.getByText("Dragon fruit", { precise: true })).toBeVisible();
});

Code Walkthrough

const { check, anticipate } = require("@playwright/test");

This line imports the check and anticipate features from the @playwright/check module. The check operate is used to outline a check case, and the anticipate operate is used for making assertions within the check case.

check("Modify API responses ", async ({ web page }) => {

Contained in the check operate, an asynchronous operate is outlined utilizing the async key phrase. This operate takes a web page object as a parameter, which represents the browser web page that Playwright will work together with.

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

This line units up a route interception for any URLs that match the sample */*/api/v1/fruits. The async operate handed because the second argument to web page.route will likely be referred to as at any time when a request matches this sample.

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

Contained in the async operate, route.fetch() is used to fetch the unique response for the intercepted request. Then, response.json() is used to parse the response physique as JSON.

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

This line modifies the parsed JSON information by including three new objects representing fruits. js.

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

The route.fulfill technique is used to meet the intercepted request with a modified response. The response choice is ready to the unique response object, and the json choice is ready to the modified JSON information.

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

This line navigates the browser web page to the URL.

await anticipate(web page.getByText(“Dragon fruit”, { precise: true })).toBeVisible();

Lastly, this line asserts that the textual content “Dragon fruit” is seen on the web page. The web page.getByText technique is used to pick out a component containing the desired textual content, and the anticipate(…).toBeVisible() assertion checks if the chosen ingredient is seen on the web page.

Trendy software program improvement requires API testing, and Playwright gives a robust, adaptable framework for constructing thorough API check suites. You possibly can create assessments that cowl each step of the appliance move with Playwright, from interacting with UI components to submitting API queries and validating the responses. In consequence, Playwright turns into an awfully complete device that lets you check the UI’s reference to the API and gives you with a complete understanding of your utility’s capabilities.

Execute the Check Case

Let’s execute the check case utilizing under command:

npx playwright check assessments/mockResponce.spec.js - ui

Wrapping Up

In conclusion, mocking API responses with Playwright is a robust approach for testing internet purposes that depend on exterior APIs. By intercepting and modifying API responses, builders can simulate varied eventualities and edge circumstances that may be tough to breed. Total, Playwright’s API mocking capabilities present builders with a robust device for constructing sturdy and dependable internet purposes, enabling them to jot down extra complete assessments and catch potential points earlier within the improvement cycle.

Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Exit mobile version