End-to-End testing of a Next.js application using Playwright and MSW. Continue


This article is a continuation of the previous one «End-to-End Testing of a Next.js Application Using Playwright and MSW», and aims to explain why we ultimately opt to use a separate mock server despite the fact that it’s possible to mock current requests directly within the test environment.

Initially, using the @mswjs/http-middleware library to start a separate server wasn't part of the plan. The idea was to hook into the existing server within the test environment. To do this, we add a .env.test file with the following contents:

APP_ENV=test

And in the main layout file app/layout.tsx, we’ll use this environment variable to determine whether the mock server should be enabled or not:

import { server } from '@/mocks/server';

// only TEST ENV: run server.listen for e2e-testing
if (process.env.APP_ENV === 'test') {
    server.listen({
        onUnhandledRequest(request) {
            console.log('Unhandled %s %s', request.method, request.url);
        },
    });
}

In this case, the tests will be run with the environment variable set, like so:

npm run build

NODE_ENV=test next start

npx playwright test

This is the “canonical” approach that’s commonly recommended.

Unfortunately, this method turned out to be incompatible with next-auth, which makes internal requests to port 8000. Since our server is running on the same port (3000) as the application itself, those internal requests fail and return errors.

By contrast, using a separate server with @mswjs/http-middleware allows us to easily mock all internal requests. As a bonus, it also enables running the mock server not only during tests but also during development, using the same mock data.

Комментарии

Популярные сообщения из этого блога

Стайлгайд и компонентная разработка

z-index

React Native: путь новичка