ts-jest 说“只允许顶级‘await’表达式...”但我已经设置了“target”:“ES2022”,“module”:“ES2022”

问题描述 投票:0回答:1
尝试运行新测试时遇到此错误:

error TS1378: Top-level 'await' expressions are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher.
但是 server/tsconfig.json 已经有:

{ "compilerOptions": { "target": "ES2022", "esModuleInterop": true, "module": "ES2022", "strictNullChecks": true, "allowSyntheticDefaultImports": true, "lib": ["ES2021.String"], "moduleResolution": "node", "composite": true /* Enable project compilation https://www.typescriptlang.org/docs/handbook/project-references.html */ }, "references": [ { "path": "../src" }, { "path": "../shared" } ] }
我的 Jest 测试如下:

test('something', async () => { await updateTransactions(); // ... }
 updateTransactions.ts 看起来像:

const connectionString = process.env.POSTGRESQL_CONNECTION_STRING; const pgClient = new pg.Client({ connectionString }); await pgClient.connect(); export async function updateTransactions() { // ... }
我已经研究过诸如

仅当“module”选项设置为“esnext”时才允许顶级“await”表达式如何在顶层使用 async/await?

我知道我可以将

await pgClient.connect();

 重构为函数内,但由于各种原因,我很好奇如何启用顶级等待。

typescript jestjs ts-jest
1个回答
0
投票
对我来说,添加“ts-jest/presets/default-esm”预设如下解决了这个问题。

jest.config.js:

export default { testEnvironment: 'node', moduleNameMapper: { "(.+)\\.js": "$1", }, preset: 'ts-jest/presets/default-esm', // or other ESM presets }
参考:

https://kulshekhar.github.io/ts-jest/docs/guides/esm-support/#use-esm-presets

© www.soinside.com 2019 - 2024. All rights reserved.