Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
903 views
in Technique[技术] by (71.8m points)

unit testing - Mocha tests, clean disk database before every file runs

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...