I am using Sails 1.x.
Is it possible to reset the Sails.js database before each test file runs? I want it to be in state after sails.lift()
completes before each run. I followed the docs here - https://sailsjs.com/documentation/concepts/testing - but did not end up with any solution like this.
The only solution I'm having right now is to change the lifecyle.test.js
before
and after
to run beforeEvery
and afterEvery
- https://sailsjs.com/documentation/concepts/testing - so this is lifting everytime before test. But it takes a long time to lift.
This is very simple to do. You just need to specify to add test connection in your connections on datasourses (depends on the version of Sails.js), setup it as active during the test and provide migration strategy 'drop'
which is just rebuild your DB every time on startup
models: {
connection: 'test',
migrate: 'drop'
},
My connections Sails.js 0.12.14
module.exports.connections = {
prod: {
adapter: 'sails-mongo',
host: 'localhost',
port: 27017,
database: 'some-db'
},
test: {
adapter: 'sails-memory'
},
};
My simplified lifecycle.test.js
let app;
// Before running any tests...
before(function(done) {
// Lift Sails and start the server
const Sails = require('sails').constructor;
const sailsApp = new Sails();
sailsApp.lift({
models: {
connection: 'test',
migrate: 'drop'
},
}, function(err, sails) {
app = sails;
return done(err, sails);
});
});
// After all tests have finished...
after(async function() {
// here you can clear fixtures, etc.
// (e.g. you might want to destroy the records you created above)
try {
await app.lower()
} catch (err) {
await app.lower()
}
});
In Sails 1 it's even simpler
const sails = require('sails');
before((done) => {
sails.lift({
datastores: {
default: {
adapter: 'sails-memory'
},
},
hooks: { grunt: false },
models: {
migrate: 'drop'
},
}, (err) => {
if (err) { return done(err); }
return done();
});
});
after(async () => {
await sails.lower();
});
I'm using this in my bootstrap test file to make the database clean.
const sails = require('sails');
before((done) => {
sails.lift({
log: {
level: 'silent'
},
datastores: {
default: {
adapter: 'sails-disk',
inMemoryOnly: true
}
},
models: {
migrate: 'drop',
archiveModelIdentity: false
}
}, function (err, sails) {
if (err) return done(err);
done(err, sails);
});
});
after(async () => {
await sails.lower();
});
beforeEach((done) => {
sails.once('hook:orm:reloaded', done);
sails.emit('hook:orm:reload');
});