Cleaning database after tests in node.js

You can wrap your test into transaction:

beforeEach(() => {
    return connection.query('START TRANSACTION');
});
afterEach(() => {
    return connection.query('ROLLBACK');
});

It will be much faster to run tests this way, compared to cleaning, or even worse dropping/recreating schema after each test.

If using it with pooled connections (new Pool()), it will be necessary to limit number of connections to 1: new Pool({min:1, max:1}) - transactions must span single connection.

This won't work however if code being tested uses transactions too. It's possible to do nested transactions with savepoints but can get bit more complicated.


There's a good package, check it out: https://github.com/emerleite/node-database-cleaner/