Mocking API responses refers back to the observe of making simulated responses from an API with out truly interacting with the actual API. This system is usually utilized in software program growth, particularly throughout testing phases, to imitate the habits of actual API endpoints. Through the use of mock responses, builders can isolate particular components 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 obtainable for mocking API responses in numerous programming languages and frameworks. Mocking API responses with Playwright is a helpful method for testing your net functions with out counting on actual API servers. It permits you to simulate completely different situations and responses out of your APIs, making your exams extra strong and impartial of exterior companies.
How Mocking Is Useful
Mocking API responses utilizing instruments like Playwright can provide a number of advantages. Among the profit defined beneath
- Isolation for testing: By mocking API responses, you may isolate the testing of front-end and back-end elements. This implies that you would be able to 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 numerous situations and edge circumstances with out counting on the precise back-end infrastructure. This could velocity up the testing course of considerably, as you may rapidly simulate completely different responses with out ready for the precise APIs to reply.
- Managed testing surroundings: With mocked responses, you could have full management over the information and situations your exams encounter. This lets you create particular check circumstances to cowl numerous situations, similar to profitable responses, error responses, or edge circumstances.
- Value discount: Utilizing mocked responses reduces the necessity for making precise API calls throughout testing, which may save on API utilization prices, particularly when coping with third-party companies that will have usage-based pricing fashions.
- Testing edge circumstances: With mocked API responses, you may simulate numerous situations, together with error circumstances, edge circumstances, and conditions that is likely to be troublesome or unattainable 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 permits you to 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 wish to deal with. The tactic returns a Route object.
const route = await web page.route('**/api/knowledge', route => {…});
Request Interception
When the web page makes a request that matches the required 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 may carry out numerous 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 supply 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
If you happen to proceed the request, Playwright will obtain the response from the server and full the request lifecycle. If you happen to fulfilled the request, the supplied customized response can be used as a substitute.
Mocking API Information in Playwright
In Playwright, utilizing the web page.route()
technique, you may certainly mock knowledge at each the time of request interception and response interception.
Mocking Information on the Time of Request
When a request is intercepted, you could have the chance to switch it earlier than it’s despatched. This implies you may manipulate the request headers, physique, URL, technique, and so on. to match your testing state of affairs or to simulate completely different circumstances. For instance, you may change the request parameters, add customized headers, and even redirect the request to a distinct endpoint.
Mocking Information on the Time of Response
As soon as the request is shipped, and a response is obtained (or intercepted), you can even modify the response knowledge earlier than it reaches the browser. This lets you simulate numerous server responses with out truly 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 could have an online web page that makes a request to an API endpoint. You wish 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 capabilities from the Playwright testing library.
check("mocks a fruit and doesn't call api", async ({ web page }) => {
// …
});
It is 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. Each time the browser navigates to a URL that matches this route sample, the supplied callback operate can be executed. Contained in the callback, an array of fruit objects is created, and the route.fulfill technique known as with this array because the response knowledge. Which means that as a substitute of creating an precise API name, the check will obtain the mocked knowledge.
await web page.goto("https://demo.playwright.dev/api-mocking");
This line navigates the browser web page to the required URL.
await anticipate(web page.getByText("Guava")).toBeVisible();
After navigating to the web page, this line asserts that the textual content “Guava”
(which is likely one of the mocked fruit names) is seen on the web page. The getByText
technique is used to retrieve the aspect containing the given textual content, and the toBeVisible
assertion checks if that aspect is seen.
Execute the Check Case
Let’s execute the check case utilizing beneath command:
npx playwright check exams/mockRequest.spec.js - ui
Within the screenshot beneath you may see 5 fruits that we added or / mock displaying in beneath display screen.
Mocking Information on the Time of Getting the Response
Let’s have a look at an instance of mocking knowledge 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 capabilities 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 can be known 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 knowledge 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 possibility is about to the unique response object, and the json possibility is about to the modified JSON knowledge.
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 required textual content, and the anticipate(…).toBeVisible()
assertion checks if the chosen aspect is seen on the web page.
Trendy software program growth requires API testing, and Playwright affords a robust, adaptable framework for constructing thorough API check suites. You possibly can create exams that cowl each step of the applying movement with Playwright, from interacting with UI components to submitting API queries and validating the responses. Because of this, Playwright turns into a very complete software that allows you to check the UI’s reference to the API and offers you with a complete understanding of your utility’s capabilities.
Execute the Check Case
Let’s execute the check case utilizing beneath command:
npx playwright check exams/mockResponce.spec.js - ui
Wrapping Up
In conclusion, mocking API responses with Playwright is a robust method for testing net functions that depend on exterior APIs. By intercepting and modifying API responses, builders can simulate numerous situations and edge circumstances that might be troublesome to breed. General, Playwright’s API mocking capabilities present builders with a robust software for constructing strong and dependable net functions, enabling them to jot down extra complete exams and catch potential points earlier within the growth cycle.