Rayrun

How do I intercept network requests and compare their JSON bodies to expected JSON in an end-to-end test using Playwright?

Answer

Intercepting and Comparing JSON in 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.

References

Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

Related Discord Threads

Related Questions

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

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 luc@ray.run.