Rayrun
← Back to Discord Forum

NextJS server actions

dsmith1024
dsmith1024

Hey hey. I have a NextJS app using server actions heavily. Is there a way to mock those network calls? I am guessing not because they happen on the server not in the browser.

Anyone handled this in a clean way?

I think we will have to setup a full environment versus mocking APIs now.

This thread is trying to answer question "Is there a way to mock network calls in a NextJS app using server actions heavily?"

2 replies

If browser does not "see" those requests then you can't mock them.

Check https://mswjs.io, you can do mocking with it in nextjs dev environment

Answer

Sure, you can mock network calls in your Next.js app using Playwright. It provides APIs to intercept and modify network traffic, including HTTP and HTTPS requests.

Here's how you can do it:

import { test } from '@playwright/test';

test('mocks an API call', async ({ page }) => {
  await page.route('https://ray.run/api/v1/fruits', async (route) => {
    const json = [{ name: 'Strawberry', id: 21 }];
    await route.fulfill({ json });
  });

  // Now, perform actions that trigger the mocked API call

  // Then, assert that the expected data is present on the page
});

In this example, page.route() intercepts calls to https://ray.run/api/v1/fruits and fulfills them with a custom JSON response. This lets you test your app's behavior under different conditions without relying on actual backend services.

But be careful if you're using tools like Mock Service Worker (MSW). It may interfere with Playwright's native browserContext.route() and page.route() methods. In such cases, it's better to use Playwright's built-in routing capabilities for response mocking.

So, Playwright gives you powerful APIs to mock and modify network calls in your Next.js app. By defining custom routes and intercepting requests, you can simulate different responses and test your app's behavior under various scenarios.

For more details, check out this blog post on how to mock HTTP traffic in Playwright tests.

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