DEV Community

Discussion on: Tests with Jest and TypeORM

Collapse
 
kentbull profile image
Kent Bull

I ended up putting a separate call to testConn.create() in a module called my Jest Global setup hook so I could instruct Jest to refresh the database at the start of the test run by dropping the schema and recreating it from migrations by passing in dropSchema: true

Example:

async create(dropSchema: boolean) {
    return await createConnection({
      name: 'default',
      type: 'postgres',
      host: 'localhost',
      port: 5432,
      username: 'postgres',
      password: 'postgres',
      database: 'mydb_localtest',
      dropSchema: dropSchema,
      migrationsRun: dropSchema,
      entities: [__dirname + '/../entity/*.*'],
      migrations: [__dirname + '/../migration/*.*'],
    });
  },
Enter fullscreen mode Exit fullscreen mode

Then, if using TypeScript, add globalSetup and globalTeardown to your jest.config.js file like so (at bottom):

module.exports = {
  globals: {
    'ts-jest': {
      diagnostics: false,
      isolatedModules: true,
    },
  },
  preset: 'ts-jest',
  testEnvironment: 'node',
  testMatch: [
    "**/__tests__/**/*.spec.ts"
  ],
  setupFiles: ['./src/helpers/envSetup.ts'],
  roots: ['./__tests__/'],
  globalSetup: "./__tests__/globalSetup.js",
  globalTeardown: "./__tests__/globalTeardown.js"
};
Enter fullscreen mode Exit fullscreen mode

Then, in globalSetup.js you can call your TypeScript setup module by doing the following:

require("ts-node/register");
// using WillAvudim's solution: https://github.com/facebook/jest/issues/5164#issuecomment-376006851

const  { setup } = require( '../src/testing/MyTestLifecycle');
module.exports = async function globalSetup() {
  await setup();
  return null;
}
Enter fullscreen mode Exit fullscreen mode

The MyTestLifecycle module (in Typescript) just calls testConn.create(true) so that the schema is dropped at the start of all my tests and then re-created by running the migrations:

import { testConn } from './testConn';

export async function setup() {
  await testConn.create(true);
}
Enter fullscreen mode Exit fullscreen mode

Let me know when this is useful you!