Mocha tests, clean disk database before every file runs

本秂侑毒 提交于 2019-11-29 17:21:01

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();

});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!