javascriptjestjssequelize.jssequelize-cli

Sequelize migration with testing


I published my application couple months ago. Now I got idea to extend functionality, but I need add column to table. Database was initialized by command

sequelize.sync()

Of course I understand sequelize-cli, I could use script something like

...
queryInterface.addColumn('Person', 'petName', { type: DataTypes.STRING })
...

It wouldn't be a problem if I didn't deal with testing as well. So far I have reinitialized the entire database before each test

beforeEach(async () => {
   await sequelizeConn.sync({ force: true })
})

The combination of migration and testing could also appear simple if I didn't use sync method from the very beginning. Is there some way how to combine "additional migration"(contain only changes like addColumn, but not initialization db, like create tables) with testing? Part of my tests is whether those migrations were performed correctly.


Solution

  • To catch up with the original migration, which was originally performed by "sequelizeConn.sync()" method, you can create init migration script which would under normal circumstances create tables, but this tables already exists, so it only create migration table "SequelizeMeta". Because "queryInterface.createTable" is translated into

    CREATE TABLE IF NOT EXISTS ...
    

    The key is "IF NOT EXISTS". By this way, you can test your migrations, even when you init your app with sync method.