NextJS 12 与新编译器 SWC
NextJS 版本 12 引入了一个新的编译器 SWC,用 Rust 编写。使用此编译器管理环境变量非常简单并且是内置的。文档位于https://nextjs.org/docs/advanced-features/compiler#jest https://nextjs.org/docs/advanced-features/compiler#jest描述如何设置 Jest 配置:
// jest.config.js
const nextJest = require('next/jest');
// Providing the path to your Next.js app which will enable loading next.config.js and .env files
const createJestConfig = nextJest({ dir: './' });
// Any custom config you want to pass to Jest
const customJestConfig = {
moduleDirectories: ['node_modules', __dirname]
};
// createJestConfig is exported in this way to ensure that next/jest can load the Next.js configuration, which is async
module.exports = createJestConfig(customJestConfig);
在这里我添加了一个自定义配置moduleDirectories
因为我在运行测试时遇到了绝对导入的问题。由于我的代码位于.
我想添加'.'
作为模块目录。但由于一个Jest 中的开放错误 https://github.com/facebook/jest/issues/12889你必须指定__dirname
反而。
NextJS 11 及更早版本
自从我问这个问题以来,文档已经更新,并提供了比在测试之前完全开始下一步更好的答案。
https://nextjs.org/docs/basic-features/environment-variables#test-environment-variables https://nextjs.org/docs/basic-features/environment-variables#test-environment-variables
将环境变量加载到测试环境中的建议方法是添加 jest 的配置文件,添加安装脚本,并在该脚本中使用包含的 NextJSloadEnvConfig
功能。
The .env.test
可以填充虚拟数据并签入您的存储库。与普通环境变量一样,您可以使用以下命令在本地覆盖它们.env.test.local
-file.
// jest.config.js
module.exports = {
globalSetup: '<rootDir>/__test__/setupEnv.js'
}
// __test__/setupEnv.js
import { loadEnvConfig } from '@next/env'
export default async () => {
const projectDir = process.cwd()
loadEnvConfig(projectDir)
}
# .env.test
MY_ENVIRONMENT_VARIABLE="a-variable-for-testing"