测试
使用 next-intl 的组件可以在单元测试中使用:
import {render} from '@testing-library/react';
import {NextIntlClientProvider} from 'next-intl';
import {expect, it} from 'vitest';
import messages from '../../messages/en.json';
import UserProfile from './UserProfile';
it('renders', () => {
render(
<NextIntlClientProvider locale="en" messages={messages}>
<UserProfile />
</NextIntlClientProvider>
);
});为了避免必须模拟服务器组件,将组件定义为非异步函数可能会很有帮助,这样可以灵活地在任何环境中渲染它们。
Vitest
next-intl 被打包为仅支持 ESM,这要求在内部使用显式文件扩展名。然而,为了避免在 Next.js 中发生性能降级,next-intl 目前必须从 next/navigation 而不是 next/navigation.js 进行导入。
Vitest 会正确地假定文件扩展名,因此暂时来说,如果你正在使用 createNavigation,需要让 Vitest 处理 next-intl 内的导入:
vitest.config.mts
import {defineConfig} from 'vitest/config';
export default defineConfig({
test: {
server: {
deps: {
// https://github.com/vercel/next.js/issues/77200
inline: ['next-intl']
}
}
}
});Jest
由于 Jest 不内置对 ESM 的支持,你需要指示 Jest 转换来自 next-intl 的导入:
jest.config.js
const nextJest = require('next/jest');
const createJestConfig = nextJest({dir: './'});
module.exports = async () => ({
...(await createJestConfig({
testEnvironment: 'jsdom',
rootDir: 'src'
})()),
// https://github.com/vercel/next.js/issues/40183
transformIgnorePatterns: ['node_modules/(?!next-intl)/']
});