I want to run a function that opens db connection before running tests (global setup) and another function that closes db connection after tests are run (global tear down). Currently I have the following config:
package.json:
//...
"jest": {
"testEnvironment": "node",
"globalSetup": "./src/jest/globalSetUp.ts",
"globalTeardown": "./src/jest/globalTearDown.ts",
"moduleFileExtensions": [
"js",
"ts"
],
"transform": {
"\\.(ts|tsx)$": "ts-jest"
}
}
and my globalSetUp.ts:
import { initDB } from "../dbUtils"
module.exports = async () => {
await initDB();
}
globalTearDown.ts:
import { closeDB } from "../dbUtils"
module.exports = async () => {
await closeDB();
}
But when I run my tests I get 2 main errors.
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: Cannot execute operation on "default" connection because connection is not yet established.
This means that the global setup function was not run. Note I am using typeORM.
How do i properly set things up so this will work?
Edit: My initDB function:
export async function initDB() {
console.log("inside intiDB");
await createConnection().then(async connection => {
console.log("connected to db");
}).catch(error => console.log(error));
}
when I run tests I see inside initDB but I don't see connected to db. I think createConnection() looks through my entities dir and the issue rised when it hits Table1.ts. Then it complains that
import { Entity, PrimaryGeneratedColumn, Column, OneToMany, Index, PrimaryColumn, ColumnType, ColumnOptions } from "typeorm"; ^^^^^^
SyntaxError: Cannot use import statement outside a module
If I remove globalSetup and globalTearDown and instead just use a beforeAll and afterAll inside my test file then everything works.