Ivan Matveev
Ivan Matveev

Reputation: 235

How to test Sequelize migrations?

Is it necessary to cover Sequelize migrations with unit tests, or even functional tests to check how they affect DB structure? If so, how to do it?

Upvotes: 6

Views: 2314

Answers (2)

Bartosz Walusiak
Bartosz Walusiak

Reputation: 51

I found myself with a similar problem.

In my case I was making changes in a migration that didn't match my models and this was affecting the code in production (could not save model because created_at was actually createdAt or something stupid like that.) and our unit test were not catching this issue because we used await sequelize.sync(); in our setup.js.

What worked for us was:


import { up as createUsersMigration } from '../database/migrations/20220426100249-create_users.js';
// Repeat for each migration...
export const performDatabaseMigrations = async (sequelize, Sequelize) => {
  await createUsersMigration(sequelize.getQueryInterface(), Sequelize);
  // Repeat for each migration...
};

... and invoking this function in our setup.js instead of syncing the models.

This allows us to test that the migrations work, but just like @simon.ro said we don't test the migrations, just that the models match the database.

UPDATE: Eventually we settled on the following:

export const performDatabaseMigrations = async (sequelize, Sequelize) => {
  const files = readdirSync('database/migrations');

  for (const file of files) {
    if (file === 'package.json') continue;
    const migration = await import(`database/migrations/${file}`);
    await migration.up(sequelize.getQueryInterface(), Sequelize);
  }
};

Upvotes: 1

simon.ro
simon.ro

Reputation: 3312

Imho testing migrations is not necessary. Neither for sequelize nor any other decent ORM.

  1. Migrations describe how your database must be altered to become compliant with the current state of the application that uses it. In a sense they are therefore not part of the application itself. Therefore no testing required.
  2. Migrations typically don't implement any custom logic. They just call a bunch of methods of the migration library. And the library used should itself be thoroughly unit tested. Therefore no additional testing required.

Upvotes: 3

Related Questions