How to test middleware with Next and Vitest

24 views Asked by At

I'm using Next 14.1.0 and Vitest 0.34.6 and want to test Next middleware. I have a basic test that looks like this:

const request = new NextRequest('http://localhost/');
const response = middleware(request);
expect...

The problem is that when I run the test, I get an error:

The NextURL configuration includes no locale "en-gb"

The error occurs on this line:

url.locale = DEFAULT_LOCALE // en-gb

When I try to log request.nextUrl it emits this:

NextURL {
  [Symbol(NextURLInternal)]: {
    url: URL {},
    options: { headers: {}, nextConfig: undefined },
    basePath: '',
    domainLocale: undefined,
    defaultLocale: undefined,
    buildId: undefined,
    locale: undefined,
    trailingSlash: true
  }
}

As far as I understand, there is a problem with Next config for tests, but I can't figure out how to configure it correctly. Here is my configuration:

next.config.js

const nextConfig = {
  i18n: {
    locales: ['en-gb', 'en-au'],
    defaultLocale: 'en-gb',
    localeDetection: false,
  },
  ...

vitest.config.ts

export default defineConfig({
  test: {
    ...
    setupFiles: './vitest.setup.ts',
  },

vitest.setup.ts

dotenv.config({ path: '.env.test' });

I tried to setup config in vitest.setup.ts, but it doesn't help:

import { setConfig } from 'next/config';
import config from './next.config';

dotenv.config({ path: '.env.test' });
setConfig(config);

Any ideas on how to fix it?

0

There are 0 answers