Description
I'm having some issues connecting with a database (mysql) while executing tests. At first I had problems while executing several tests at once, some test would create the same primary key for some entity and end up with a duplicate key exception, I'm using --runInBand
jest option to execute tests sequentially and try to avoid that issue in particular.
After executing tests sequentially I still had some issues with duplicate key exceptions. So I edited test/utils/database.ts
to wait some time before and after migrating, that seems to work fine but I understand its not ideal.
Are there some limitations I'm not aware of or am I setting up something wrong? I'm using version 3.2.0 of express-typescript-boilerplate
. I hope I'm not being too vague describing the problem.
// test/utils/database.ts
import { Container } from 'typedi';
import { Connection, createConnection, useContainer } from 'typeorm';
import { env } from '../../src/env';
import {sleep} from '../../src/lib/misc';
declare type LoggerOptions = boolean | 'all' | Array<('query' | 'schema' | 'error' | 'warn' | 'info' | 'log' | 'migration')>;
export const createDatabaseConnection = async (): Promise<Connection> => {
await sleep(3000);
useContainer(Container);
const connection = await createConnection({
type: env.db.type as any, // See createConnection options for valid types
host: env.db.host,
port: env.db.port,
username: env.db.username,
password: env.db.password,
database: env.db.database,
synchronize: env.db.synchronize,
logging: env.db.logging as LoggerOptions,
entities: env.app.dirs.entities,
migrations: env.app.dirs.migrations,
});
return connection;
};
export const synchronizeDatabase = async (connection: Connection) => {
await connection.dropDatabase();
return connection.synchronize(true);
};
export const migrateDatabase = async (connection: Connection) => {
await sleep(400);
await connection.dropDatabase();
const migrations = await connection.runMigrations();
await sleep(400);
return migrations;
};
export const closeDatabase = (connection: Connection) => {
return connection.close();
};
I'm setting my connections to the database just like in the examples.
// -------------------------------------------------------------------------
// Setup up
// -------------------------------------------------------------------------
let settings: BootstrapSettings;
beforeAll(async () => settings = await prepareServer({ migrate: true }));
beforeEach(async () => await migrateDatabase(settings.connection));
afterAll(async () => await closeDatabase(settings.connection));
This error also appears from time to time when a new class with jest tests starts executing.
console.error node_modules/jest-jasmine2/build/jasmine/Env.js:157
Unhandled error
console.error node_modules/jest-jasmine2/build/jasmine/Env.js:158
Error: Connection is not established with mysql database