Elias
Elias

Reputation: 4122

Create a separate (in memory) database for each test

It is possible to create a in memory database for each test?

I currently use the following code, which works if I only run one test file or use the --run-in-band option.

import _useDb from "@/useDb";
import { mocked } from "ts-jest/utils";
import { createConnection, getConnection } from "typeorm";

const useDb = mocked(_useDb);

jest.mock("@/useDb");

beforeEach(async () => {
  useDb.mockImplementation(async (action) => {
    const db = await createConnection({
      type: "sqlite",
      database: ":memory:",
      dropSchema: true,
      entities: [Entity],
      synchronize: true,
      logging: false,
    });

    await action(db);
  });
});

afterEach(async () => {
  const con = getConnection();

  await con.close();
});

But as soon as I run multiple tests at the same time I get:

CannotExecuteNotConnectedError: Cannot execute operation on "default" connection because connection is not yet established.

I think I could provide a name attribute with a random uuid, like they suggested in How to create separate in memory database for each test? But is this really the way to go? Isn't there some kind of parameter that tells TypeORM "please don't create connections indexed by name" (or whatever it is doing)?

Upvotes: 5

Views: 7542

Answers (1)

Elias
Elias

Reputation: 4122

So I got it to work, now sure how, but maybe this helps someone in the future. This is my beforeEach and afterEach:

beforeEach(async () => {
  const con = await createConnection({
    type: "sqlite",
    database: ":memory:",
    dropSchema: true,
    entities: [],
    synchronize: true,
    logging: false,
  });

  mockGetDbConnection.mockResolvedValue(con);
});

afterEach(async () => {
  const con = getConnection();

  await con.close();
});

mockGetDbConnection is the function where services get the DB handle. If you don't have that you most likely just want to use getConnection provided by TypeORM.

I also have this in jest setupFilesAfterEnv and it seems to work like a charm.

Upvotes: 4

Related Questions