You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Jest+TypeScript的globalTeardown中使用async

Jest + TypeScript 环境下 globalTeardown 使用 async 语法报错问题

问题场景

在 Jest 搭配 TypeScript 的项目中,globalSetup 里使用 async/await 能正常运行,但 globalTeardown 中使用同样的语法却触发类型错误。

相关配置文件

jest.config.js

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  testPathIgnorePatterns: ['<rootDir>/dist/', '<rootDir>/node_modules/'],
  globalSetup: '<rootDir>/tests/global-setup.ts',
  globalTeardown: '<rootDir>/tests/global-teardown.ts',
};

global-teardown.ts(报错版本)

require('ts-node/register');
import { redisClient } from "../config/session";

export default async () => {
  await redisClient.quit();
  console.log('Exiting test...');
  process.exit();
};

触发的错误信息

Error: Jest: Got error running globalTeardown - /ROOT_OF_APP/tests/global-teardown.ts, reason: [TSError: tests/global-teardown.ts:26:111 - error TS2322: Type 'number' is not assignable to type '{ label: number; sent: () => any; trys: never[]; ops: never[]; }'.

正常运行的 globalSetup.ts

require('ts-node/register');
// imported modules here...

export default async () => {
  await someAsyncFunction();
};

tsconfig.json

{
  "compilerOptions": {
    "noImplicitAny": false,
    "target": "es5",
    "lib": ["es2020"],
    "module": "commonjs",
    "sourceMap": true,
    "outDir": "./dist",
    "strict": true,
    "esModuleInterop": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "typeRoots": ["./node_modules/@types", "./typings"]
  },
  "include": ["**/*.ts"]
}

疑问与求助

为何 globalTeardown 无法使用 async 语法,而 globalSetup 可以?求可行的解决方案。

内容的提问来源于stack exchange,提问作者Hiroki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 14:33:19