NestJS + Sequelize: Managing Migrations and Test Data for E2E Tests
End-to-end (E2E) testing is a crucial part of any robust testing strategy. It ensures that all components of your application—from the API to the database—work together as expected. But writing E2E tests isn’t just about firing up some HTTP requests. You also need a reliable way to manage your database state: apply migrations, seed test data, and clean up after tests.
If you're using NestJS with Sequelize, this guide will walk you through best practices for handling migrations and test data in your E2E test setup for Sequelize.
Why Migrations and Test Data Matter
When running E2E tests, the database must be in a known state. This means:
The schema is up-to-date (migrations).
The data is predictable (test data).
Each test starts fresh (clean state).
By managing these correctly, you avoid flaky tests and mysterious bugs caused by leftover data or schema drift.
Tools We’re Using
NestJS – Modular framework for building scalable server-side apps.
Sequelize – Promise-based Node.js ORM for Postgres, MySQL, etc.
sequelize-cli – Command-line tool for running migrations and seeders.
Jest – Test runner used by default in NestJS apps.
Project Structure Overview
Here’s a basic structure we’ll assume, users module taken for example:
Make sure the sync your models changes to the testing database, run the following command to do so.
NODE_ENV=test sequelize db:migrate
Running test cases:
Before running below command, create test cases Create test files named as follows: <file-name>-e2e-spec.ts inside the test directory at root of the project.
npx test jest --config ./test/jest-e2e.json
Troubleshooting
If running test command is unable to find test files,Make sure your jest-e2e.json file looks similar to below code snippet.
If you are getting errors related to file imports or not found, make sure to use relative file paths while importing files in the your nestjs application.
For example: importing files like 'src/users/users.module' might give errors while running test case even if it is working correctly for the app.
So to avoid this error, import files like '../users/users.module' relative to the file which is importing other file.