TypeORMError and Jest: No connection options were found in any orm configuration files

Viewed 268

this is my ormconfig.json file that is in my project root.

[
  {
    "name": "default",
    "type": "postgres",
    "host": "localhost",
    "port": 5432,
    "username": "postgres",
    "password": "",
    "database": "dev",
    "synchronize": true,
    "logging": true,
    "migrationsRun": true,
    "entities": ["src/db/entities/**/*.ts"],
    "migrations": ["src/db/migrations/**/*.ts"],
    "cli": {
      "entitiesDir": "src/db/entities",
      "migrationsDir": "src/db/migrations"
    }
  },
  {
    "name": "test",
    "type": "postgres",
    "host": "localhost",
    "port": 5432,
    "username": "postgres",
    "password": "",
    "database": "test",
    "dropSchema": true,
    "logging": true,
    "synchroize": true,
    "migrationsRun": true,
    "entities": ["src/db/entities/**/*.ts"],
    "migrations": ["src/db/migrations/**/*.ts"]
  }
]

As you can see I have a "test" connection that is supposed to be used in testing.

This is my jest.config.js file:

module.exports = {
  preset: "ts-jest",
  testEnvironment: "node",
  roots: ["<rootDir>/src", "<rootDir>/tests"],
  testMatch: ["**/__tests__/**/*.+(ts|js)", "**/?(*.)+(spec|test).+(ts|js)"],
  setupFilesAfterEnv: ["<rootDir>/tests/setup.ts"],
};

In the tests/setup.ts file i connect to db and clear the db before each test:

import { createConnection, getConnection, getConnectionOptions } from "typeorm";

beforeAll(async () => {
  await createConnection("test");
});

beforeEach(async () => {
  const conn = getConnection("test");
  const entities = conn.entityMetadatas;

  entities.forEach(async (entity) => {
    const repo = conn.getRepository(entity.name);
    await repo.query(`DELETE FROM ${entity.tableName}`);
  });
});

afterAll(async () => {
  await getConnection("test").close();
});

But I give this error:

TypeORMError: No connection options were found in any orm configuration files.

I found some github issues about this error but their problem was solved by putting ormconfig.json in the project root. But my ormconfig.json file is in the project root (at the same level as package.json). So why TypeORM can't find configurations?

1 Answers

I had the same problem, in my case I had an empty ormconfig.env file with no environment variables inside it, (left over from when I had ported over into my main .env file.)

Deleting the ormconfig.env file resolved the issue for me. I would suggest checking for multiple configurations that might be present.

Both files were located in the root directory too, at a guess I would say, typeorm picked up the ormconfig.env before the .env file when creating the connection upon running a test.

Related