TypeORM createConnection hangs in Jest

Viewed 82

When I'm trying to create a TypeORM connection to a local postgres database in a beforeAll Jest hook, TypeORM's createConnection keeps hanging for indefinite amount of time.

I don't want to have it globally because the majority of the tests don't need this database connection.

jest.config.ts

/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
};

example.spec.ts

let conn;

describe('GET /healthz', () => {
  beforeAll(async () => {
    conn = await createConnection({
      name: 'default',
      type: 'postgres',
      host: 'localhost',
      port: 5433, // <- not a typo, I tested on both 5433 and 5432
      database: 'test-local',
      username: 'user',
      password: 'pwd',
      synchronize: true,
      logging: true,
    });
  });

  afterEach(async () => {
    // omitted, but truncates all tables after every test
  });

  afterAll(async () => {
    await conn.close();
  });

  it('should be true', () => {
    expect(true).toBe(true);
  });

});

Output of running jest with --detectOpenHandles: output

However when I copy exactly these connection options in my normal application, it works correctly without any errors. And also in my jest it doesn't throw any errors so I'm pretty lost on what's going on here. I tried it in globalSetup before, but even there it just hangs. It just doesn't get past the createConnection. Any ideas or suggestions is much appreciated!

1 Answers

Altough the --detectOpenHandle pointed at the createDbConnection of TypeORM, it was actually a totally different thing that hanged.

It was very misleading, but I started cronjobs somewhere in the express app, which were hanging instead of the TypeORM createConnection.

Related