This thread is trying to answer question "How can I return the request body(JSON) and compare it to an expected JSON in an E2E test?"
Related Ask AI answer for "How do I intercept network requests and compare their JSON bodies to expected JSON in an end-to-end test using Playwright?".
You can intercept network requests and compare their JSON bodies to expected JSON in an end-to-end test using Playwright's page.route
method.
First, use page.route
to intercept the API endpoint:
await page.route('*/**/api/v1/fruits', async (route) => {
const response = await route.fetch();
const json = await response.json();
const expectedJson = { name: 'Playwright', id: 100 };
expect(json).toEqual(expectedJson);
await route.fulfill({ response, json });
});
Then, navigate to the URL where the API call is made:
await page.goto('https://ray.run/api-mocking');
Finally, assert that your expected data is visible on the page:
await expect(page.getByText('Playwright', { exact: true })).toBeVisible();
With page.route
, you can access request bodies, modify them, and compare them against expected JSON objects. This is a powerful tool for end-to-end testing. For more tips on efficient Playwright test scripts, check out this blog post.
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].