Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cleaning database after tests in node.js

How I can clean database after each it?

In rails I use https://github.com/bmabey/database_cleaner, but I did't find something similar for node.js

node.js (v0.10.26), PostgreSQL (9.3.3), mocha, restify and knex.

like image 308
frootloops Avatar asked Mar 05 '14 12:03

frootloops


1 Answers

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.

like image 181
Ski Avatar answered Oct 23 '22 20:10

Ski