我有一个顶级等待来加载应用程序机密,如下所示:
// lib/config/secrets.ts
const secrets = await loadSecrets();
export default secrets;
Run Code Online (Sandbox Code Playgroud)
我将其导入其他模块中以进行数据库连接设置等:
// lib/db/index.ts
import { Pool } from "pg";
import secrets from "lib/config/secrets";
const pool = new Pool({
connectionString: secrets.dbUrl,
...
});
Run Code Online (Sandbox Code Playgroud)
当通过 Webpack 运行我的应用程序时,这工作正常,但是当使用 jest 运行单元测试时,我收到以下错误:
SyntaxError: await is only valid in async functions and the top level bodies of modules。我已经在这个问题上停留了一段时间,甚至考虑过其他途径来完全避免异步秘密加载,因为我还没有找到解决方案。我见过类似的问题Jest won't receive top-level-await with NodeJS16 & TypeScript,但我没有ts-jest在我的项目中使用。我的配置是否有任何明显的情况会导致测试期间出现此问题,或者这只是不受支持?
我next.config.js通过 Webpack 支持顶级等待:
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true, …Run Code Online (Sandbox Code Playgroud)