Skip to main content

Mock APIs

Web APIs are usually implemented as HTTP endpoints. Playwright provides APIs to mock and modify network traffic, both HTTP and HTTPS. Any requests that a page does, including XHRs and fetch requests, can be tracked, modified and mocked.

Mock API requests

Following code will intercept all the calls to https://dog.ceo/api/breeds/list/all and will return the test data instead. No requests to the https://dog.ceo/api/breeds/list/all endpoint will be made.

Read more about advanced networking.

await page.route('https://dog.ceo/api/breeds/list/all', async route => {
const json = {
message: { 'test_breed': [] }
};
await route.fulfill({ json });
});

Modify API responses

Sometimes, it is essential to make an API request, but response needs to be patched to allow for reproducible testing. In that case, instead of mocking the request, one can perform the request and fulfill it with the modified response.

Read more about advanced networking.

await page.route('https://dog.ceo/api/breeds/list/all', async route => {
const response = await route.fetch();
const json = await response.json();
json.message['big_red_dog'] = [];
// Fulfill using the original response, while patching the response body
// with the given JSON object.
await route.fulfill({ response, json });
});