Getting Jest global setup and global teardown to work in a typescript project

Viewed 4887

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.

2 Answers

The typescript environment is not yet defined when globalSetup and globalTeardown are run, which is why jest is failing.

A workaround is to create the environment manually by requiring ts-node in those files.

Here is an example:

require('ts-node/register');

const setup = (): void => {
  // whatever you need to set up globally
};

export default setup;

Try to use require statements instead of import statements in your teardown and setup files like so:

//globalTearDown.ts

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

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

Do the same with your teardown file.

Related