Reputation: 13821
I am writing integration tests for a Node.JS project that uses Sequelize + Postgres. I would like to ensure that the test database is completely reset before tests are run.
I have a pretest
script that runs:
NODE_ENV=test yarn migrate
I believe db:drop
and db:create
do not work in postgres.
In Rails I might use db:migrate:reset
I know Sequelize has db:migrate:undo:all
but I believe that rolls back each migration individually, which feels like a waste of time if my intent is simply to drop all tables.
How do I most effectively accomplish the goal of running migrations on the test database from a clean slate?
Upvotes: 3
Views: 13909
Reputation: 49
try this solution:
using jest hook pretest and multiples steps together
"pretest": "NODE_ENV=test sequelize db:migrate:undo:all && NODE_ENV=test sequelize db:drop && NODE_ENV=test sequelize db:create && NODE_ENV=test sequelize db:migrate,
"test": "NODE_ENV=test jest"
Upvotes: 2
Reputation: 102607
You should use Sequelize Command-Line Interface (CLI), then you can use db:create
and db:drop
no matter what RDBMS you are using.
Here is usage, I test it using postgres:9.6
:
☁ node-sequelize-examples [master] npx sequelize-cli db:drop
Sequelize CLI [Node: 10.16.2, CLI: 5.5.1, ORM: 5.21.3]
Loaded configuration file "src/config/config.js".
Using environment "development".
Executing (default): DROP DATABASE "node-sequelize-examples"
Database node-sequelize-examples dropped.
☁ node-sequelize-examples [master] npx sequelize-cli db:create
Sequelize CLI [Node: 10.16.2, CLI: 5.5.1, ORM: 5.21.3]
Loaded configuration file "src/config/config.js".
Using environment "development".
Executing (default): CREATE DATABASE "node-sequelize-examples"
Database node-sequelize-examples created.
src/config/config.js
:
module.exports = {
development: {
username: process.env.POSTGRES_USER,
password: process.env.POSTGRES_PASSWORD,
database: process.env.POSTGRES_DB,
host: process.env.POSTGRES_HOST,
port: process.env.POSTGRES_PORT,
dialect: 'postgres',
logging: console.log,
},
test: {
username: process.env.POSTGRES_USER,
password: process.env.POSTGRES_PASSWORD,
database: process.env.POSTGRES_DB,
host: process.env.POSTGRES_HOST,
port: process.env.POSTGRES_PORT,
dialect: 'postgres',
},
production: {
username: process.env.POSTGRES_USER,
password: process.env.POSTGRES_PASSWORD,
database: process.env.POSTGRES_DB,
host: process.env.POSTGRES_HOST,
port: process.env.POSTGRES_PORT,
dialect: 'postgres',
},
};
Check the database using psql
:
# psql -U testuser node-sequelize-examples
psql (9.6.11)
Type "help" for help.
node-sequelize-examples=# \d
No relations found.
Upvotes: 4