Rayrun

What are the ways to manipulate JSON payload in @playwright/test?

Answer

Working with JSON Payload in @playwright/test

You can manipulate JSON payload in two main ways in @playwright/test.

Modifying Response Body with route.fulfill()

You can use the route.fulfill() method with the json option to modify the response body and fulfill the request with your modified data. Here's how you can do it:

// Fetch the original settings
let response = await route.fetch();

// Modify the settings
let json = await response.json();
json.theme = 'dark';

// Fulfill the request with the modified data
await route.fulfill({ json });

Setting Post Data of a Request with postData Option

You can also set the post data of a request using the postData option. If your data parameter is an object, it will be serialized to a JSON string and the content-type header will be set to application/json if not explicitly set.

await page.route('https://ray.run/api/posts', route => {
  route.fulfill({
    postData: JSON.stringify({ title: 'New Post', body: 'Hello, world!' }),
    headers: { 'Content-Type': 'application/json' }
  });
});

Remember, the headers option applies to both fetched requests and any redirects initiated by them. If you only want headers applied to the original request but not redirects, consider using route.continue() instead.

For more tips and tricks on using @playwright/test, check out Mastering Playwright Test Automation: Your Comprehensive Cheat Sheet.

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 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 [email protected].