我想运行一个在运行测试之前打开数据库连接的函数(全局设置),以及另一个在运行测试后关闭数据库连接的函数(全局拆卸)。目前我有以下配置:
包.json:
//...
"jest": {
"testEnvironment": "node",
"globalSetup": "./src/jest/globalSetUp.ts",
"globalTeardown": "./src/jest/globalTearDown.ts",
"moduleFileExtensions": [
"js",
"ts"
],
"transform": {
"\\.(ts|tsx)$": "ts-jest"
}
}
和我的 globalSetUp.ts:
import { initDB } from "../dbUtils"
module.exports = async () => {
await initDB();
}
全局TearDown.ts:
import { closeDB } from "../dbUtils"
module.exports = async () => {
await closeDB();
}
但是当我运行测试时,我遇到了两个主要错误。
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
and
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));
}
当我运行测试时我看到inside initDB
但我没有看到connected to db
。我认为 createConnection() 会查看我的实体目录,当它到达 Table1.ts 时问题就会出现。然后它抱怨说
导入{实体,PrimaryGenerateColumn,列,OneToMany,索引,
PrimaryColumn, ColumnType, ColumnOptions } 来自“typeorm”;
^^^^^^
SyntaxError: Cannot use import statement outside a module
如果我删除 globalSetup 和 globalTearDown ,而只是在测试文件中使用 beforeAll 和 afterAll ,那么一切都会正常。