Is it feasible to create an in-memory database for each test scenario?
My current approach involves using the code snippet below, which functions properly when running one test file or utilizing 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();
});
However, running multiple tests simultaneously triggers the following error:
CannotExecuteNotConnectedError: Cannot execute operation on "default" connection because connection is not yet established.
I am aware of a suggestion in this Stack Overflow post to include a name attribute with a random uuid. But I wonder if there is an alternative method to instruct TypeORM not to index connections by name. Is there a parameter that can achieve this functionality?