10

I'm using 'sails-memory' as the database for my Sails unit tests and ideally would like to clear the entire database after individual tests. Is there a way I can drop the entire database?

HolySamosa
  • 9,011
  • 14
  • 69
  • 102
  • This post proved useful to me, with a solution for both the in-memory case and for an actual SQL DB: https://www.ultrasaurus.com/2016/06/sailsjs-testing-patterns-trunctate-database/. – Tomty Aug 01 '19 at 17:36

2 Answers2

7

I found another method which seems to work. This emits an event which tells the orm hook to reload before each test. If using the memory db, or the disk db with the 'drop' migrate option, it accomplishes the desired.

beforeEach((done) => {
  "use strict";
  // Drops database between each test.  This works because we use
  // the memory database
  sails.once('hook:orm:reloaded', done);
  sails.emit('hook:orm:reload');
});
Russ Egan
  • 3,568
  • 1
  • 24
  • 12
3

You could lift your sails app before each test, rebuilding your database (migrate: 'drop'). Here is an example:

Sails = require('sails/lib/app');
app = Sails();

var testConfig = {
    environment: 'test',
    port: 1337,
    log: {
        level: 'error'
    },
    connections: {
        testDB: {
            adapter: 'sails-memory'
        }
    },
    connection: 'testDB',

    //wipe/drop ALL my data and rebuild models every time
    migrate: 'drop'
};

beforeEach(function (done) {
    // start sails app for tests
    app.lift(testConfig, function (err, sails) {
        done(err);
    });
});

//tests...
Victor
  • 5,043
  • 3
  • 41
  • 55
  • 2
    No need to `migrate: drop`; the memory adapter starts fresh each time! – sgress454 Sep 26 '14 at 18:42
  • I had wondered about this-- how expensive is the lift operation? At present I only have a few tests, but as the number of tests grow I wonder if the overhead add up to a slow running test suite. What's your experience? Thanks! – HolySamosa Sep 29 '14 at 17:58
  • Only in my integration tests i lift the server ```beforeEach``` test. Also i have some unit tests, where i'm using [sinon](http://sinonjs.org/) to mock the database access. In my unit tests i lift the server ```before``` all tests, just to initialize models, services, etc. Here are the numbers: 136 integration tests => ~8 seconds; 201 unit tests => ~3 seconds – Victor Sep 29 '14 at 18:30
  • 2
    Worth noting - I don't know if this is a recent change, or an idiosyncrasy - but in my config, I have to place the `connection` and `migrate` keys inside of a `models` object in the configuration to make it work, like this: `testConfig = { models: { connection: 'testDB', migrate: 'drop' }, ... }`. Try this if the above doesn't work. –  Dec 10 '14 at 04:21