让 Jest 全局设置和全局拆卸在 TypeScript 项目中工作

LTM*_*LTM 10 node.js npm typescript jestjs typeorm

我想运行一个在运行测试之前打开数据库连接的函数(全局设置),以及另一个在运行测试后关闭数据库连接的函数(全局拆卸)。目前我有以下配置:

包.json:

//...
"jest": {
    "testEnvironment": "node",
    "globalSetup": "./src/jest/globalSetUp.ts",
    "globalTeardown": "./src/jest/globalTearDown.ts",
    "moduleFileExtensions": [
      "js",
      "ts"
    ],
    "transform": {
      "\\.(ts|tsx)$": "ts-jest"
    }
  }
Run Code Online (Sandbox Code Playgroud)

和我的 globalSetUp.ts:

import { initDB } from "../dbUtils"

module.exports = async () => {
  await initDB();
}
Run Code Online (Sandbox Code Playgroud)

全局TearDown.ts:

import { closeDB } from "../dbUtils"

module.exports = async () => {
  await closeDB();
}
Run Code Online (Sandbox Code Playgroud)

但是当我运行测试时,我遇到了两个主要错误。

Determining test suites to run.../home/me/Projects/.../Table1.ts:1
import { Entity, PrimaryGeneratedColumn, Column, OneToMany, Index, PrimaryColumn, ColumnType, ColumnOptions } from "typeorm";
^^^^^^

SyntaxError: Cannot use import statement outside a module
Run Code Online (Sandbox Code Playgroud)

CannotExecuteNotConnectedError:无法在“默认”连接上执行操作,因为尚未建立连接。

这意味着全局设置功能未运行。注意我正在使用 typeORM。

我如何正确设置才能使其发挥作用?

编辑:我的 initDB 函数:

export async function initDB() {
  console.log("inside intiDB");

  await createConnection().then(async connection => {
    console.log("connected to db");
  }).catch(error => console.log(error));
}
Run Code Online (Sandbox Code Playgroud)

当我运行测试时,我看到了inside initDB,但没有看到connected to db。我认为 createConnection() 会查看我的实体目录,当它到达 Table1.ts 时问题就会出现。然后它抱怨说

从“typeorm”导入{Entity、PrimaryGenerateColumn、Column、OneToMany、Index、PrimaryColumn、ColumnType、ColumnOptions};^^^^^^

SyntaxError: Cannot use import statement outside a module
Run Code Online (Sandbox Code Playgroud)

如果我删除 globalSetup 和 globalTearDown ,而只是在测试文件中使用 beforeAll 和 afterAll ,那么一切都会正常。

nis*_*ush -1

尝试在拆卸和安装文件中使用require语句而不是语句,如下所示:import

//globalTearDown.ts

const { initDB } = require("../dbUtils"); //<--- use require instead of import

module.exports = async () => {
  await initDB();
}

Run Code Online (Sandbox Code Playgroud)

对您的拆卸文件执行相同的操作。