【发布时间】:2021-02-07 00:43:14
【问题描述】:
我想运行一个在运行测试之前打开数据库连接的函数(全局设置)和另一个在运行测试后关闭数据库连接的函数(全局拆除)。目前我有以下配置:
package.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();
}
globalTearDown.ts:
import { closeDB } from "../dbUtils"
module.exports = async () => {
await closeDB();
}
但是当我运行我的测试时,我得到了 2 个主要错误。
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
和
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 时问题就出现了。然后它抱怨
import { Entity, PrimaryGeneratedColumn, Column, OneToMany, Index, PrimaryColumn, ColumnType, ColumnOptions } 来自“typeorm”; ^^^^^^
SyntaxError: Cannot use import statement outside a module
如果我删除 globalSetup 和 globalTearDown 而只是在我的测试文件中使用 beforeAll 和 afterAll 则一切正常。
【问题讨论】:
-
您能描述一下您用来运行测试的命令吗?
标签: node.js typescript npm jestjs typeorm