What is the method to mock API responses using Playwright?


Mocking API Responses with Playwright

You can easily mock API responses with Playwright. Let's say you want to intercept an API call at /api/users and return a few test users instead of all local dev users. Here's how you can do it:

await page.route('https://ray.run/api/users', async (route) => {
  const testUsers = [
    { name: 'Test User 1', id: 1 },
    { name: 'Test User 2', id: 2 },
  await route.fulfill({ json: testUsers });

This code intercepts any request made to /api/users and fulfills it with a custom JSON response containing only the specified test users.

Playwright also lets you mock API requests using HAR files. HAR files record network requests made by a page and can be used to simulate network traffic in tests. Here's how you can use a HAR file for mocking:

await page.routeFromHAR('./path/to/your/har/file.har', {
  url: 'https://ray.run/api/users',
  update: false,

This code replays API requests from the specified HAR file instead of making actual network calls. This allows you to have fine-grained control over your test data by modifying or creating custom responses in your recorded HAR files.

Remember, these methods are great for isolating your tests from external dependencies or when testing scenarios where it's not feasible or desirable to make real API calls. Happy testing with Playwright!


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

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.