You can definitely intercept and record API responses with Playwright. It's a powerful tool that provides various methods to handle network requests and responses.
First, use the page.route()
method to set up a route for the API endpoint you want to monitor. Here's how:
await page.route('**/api/fetch_data', route => {
route.fulfill({ status: 200, body: testData });
});
In this code, any requests matching '**/api/fetch_data'
will be intercepted.
Next, perform actions on your web page that trigger the API call. For example:
await page.goto('https://ray.run');
await page.getByText('Update').click();
Then, wait for the intercepted response using page.waitForResponse()
. Like this:
const response = await page.waitForResponse('**/api/fetch_data');
Finally, access the response's properties. You can do something like:
console.log(response.status());
console.log(await response.json());
And that's it! You've just intercepted and recorded an API response. Remember, this is just one way to do it. Playwright offers other methods for handling network requests, so feel free to explore!
For more details, check out this blog post on API testing using Playwright.
If you still have questions, please ask a question and I will try to answer it.
Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].