NextJS Jest测试中间件时locale未定义及赋值报错问题
解决Next.js中间件测试中NextURL.locale未定义/赋值报错问题
问题根源
手动创建NextRequest时,默认生成的nextUrl不会自动加载项目next.config.js里的i18n配置(支持的locale列表、默认locale等)。这直接导致:
- 初始状态下
req.nextUrl.locale为undefined - 直接赋值合法locale(比如
en)时,NextURL因未识别该locale在配置中存在,抛出TypeError: The NextURL configuration includes no locale "en"错误
解决方案
测试时先手动创建带有i18n配置的NextURL,再用它初始化NextRequest,确保NextURL知晓项目支持的locale集合。
修正后的测试代码
import { NextRequest, NextResponse, NextURL } from 'next/server'; it('should redirect to default locale URL for default locale paths without token', async () => { // 1. 实例化带有i18n配置的NextURL const nextUrl = new NextURL('https://example.com/register', undefined, { locales: ['en', 'default'], // 替换为项目实际支持的locale列表 defaultLocale: 'default', // 替换为项目的默认locale }); // 2. 用配置好的NextURL创建NextRequest const req = new NextRequest(nextUrl); req.cookies.set(appConfig.i18n.cookie_locale, 'en'); // 现在可安全设置locale,不会触发报错 req.nextUrl.locale = 'en'; const response = await middleware(req); expect(response).toEqual( NextResponse.redirect(new URL('/register', req.url)) ); });
关键说明
NextURL构造函数的第三个参数为配置对象,必须包含locales(支持的locale数组)和defaultLocale(默认locale)- 测试环境中Next.js不会自动解析请求头填充
nextUrl.locale,无需依赖请求头设置,直接通过配置好的NextURL初始化即可
内容的提问来源于stack exchange,提问作者BaptisteG
相关产品推荐
相关产品推荐

