Rayrun

How do I mock API responses using the request fixture in Playwright?

Answer

Sure, you can mock API responses in Playwright using only the request fixture. Playwright's page.route() method is your friend here. It intercepts and modifies network requests made by a page. You can match requests to intercept using a URL pattern or a regular expression.

Here's how you can fulfill a request with a custom response using route.fulfill(). You can provide a JSON object as the response body or modify an existing response.

await page.route('*/**/api/v1/fruits', async (route) => {
  const json = [{ name: 'Strawberry', id: 21 }];
  await route.fulfill({ json });
});

In this example, all calls to */**/api/v1/fruits will be intercepted and fulfilled with a custom JSON response.

Now, navigate to your URL that makes API calls and check that the mocked data is present on the page.

await page.goto('https://ray.run/api-mocking');
await expect(page.getByText('Strawberry')).toBeVisible();

This code navigates to https://ray.run/api-mocking and checks that the fruit "Strawberry" is visible on the page.

By using page.route() and route.fulfill(), you can mock API responses without relying on specific fixtures like page. This gives you more flexibility in mocking responses during testing scenarios.

For more details on mocking HTTP traffic in Playwright tests, 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.