Rayrun
← Back to Discord Forum

Returning request response

MS_Custodianposted in #help-playwright
Open in Discord
MS_Custodian
MS_Custodian

E2E test. I am able to validate that the correct api request is triggered when I click a button, but how can I return the request body(JSON) and compare it to an expected JSON? I am trying to use request.postData but its not in a format I can view the actual data that was sent.

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?"

3 replies

After you call const response = await postData();

You will need to request the body by const body = await response.json()

MS_Custodian
MS_Custodian

There is no .json(). Here is what I have so far

const [request] = await Promise.all([ this.page.waitForRequest(**test/test), await this.clickConfirmYes() ]);

const res = await request.postData;
const [request] = await Promise.all([
        this.page.waitForRequest(**test/test),
        await this.clickConfirmYes()
      ]);

      const res = await request.postData;
      const resJson = await res.json(); // <--- add this

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.

Related Discord Threads

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.