Rayrun
← Back to Discord Forum

Intercept an API call and mock the results

hopepunkelsaposted in #help-playwright
Open in Discord

I have a Users page that makes a call to get a list of users, and I want to intercept that call and mock the response to just show a few test users. The page is loading with all of my local dev users, not the shortened list of test users. I have added contentType: "application/json; charset=utf-8" to the route.fulfill but in the trace viewer network tab it's still showing as Content-Type: text/html; charset=utf-8

image.png

This thread is trying to answer question "How can I intercept an API call and mock the response to display a few test users instead of all local dev users?"

2 replies
.aleksandaraleksandrov
.aleksandaraleksandrov

Hello elsa, https://playwright.dev/docs/mock I hope this helps. 🙂

Thank you, I have been using the official docs.

Answer

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!

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.