Search code examples
node.jssails.jsmocha.jssupertest

How to write unit test for sailsjs controller in mocha


I am new with sailsjs, nodejs and mocha unit test. Anyone can give me some guidance in how I can write unit test for the following controller?

getdata : function(req, res) {
    User.findOne(req.id.query).populateAll()
        .exec(function(err, res) {
            if(err) { console.log(err); }
            req.id = res;
            return res.send(req.id);
    });
},

config/route.js

module.exports.routes = {
  'get /list/item':  'manager.getdata',
}

Solution

  • Ok, firstly create test folder inside root of app. Add any kind of folder structure you prefer... Here is a screenshot from one of mine projects:

    enter image description here

    I use supertest and should... So if you want to generally copy paste things I'll type here please install (together with mocha of course):

    npm install supertest
    npm install should
    

    Next, inside bootstrap.test.js (check image above to see where to put it for example) add configuration like:

    var Sails = require('sails');
    
    before(function (done) {
        process.env.NODE_ENV = 'test';
        process.env.PORT = 9999;
    
        Sails.lift({
            models: {
                connection: 'localDiskDb',
                migrate: 'drop'
            }
        }, function (err, server) {
            sails = server;
            if (err) return done(err);
    
            sails.log.info('***** Starting tests... *****');
            console.log('\n');
    
            done(null, sails);
        });
    });
    
    after(function (done) {
        sails.lower(done);
    });
    

    Now, add your first test... In your example I would put it inside test/integration/controllers/MyController.test.js

    This is demo code you could use for your test:

    var request = require('supertest'),
        should = require('should');
    
    
    describe('My controller', function () {
    
        before(function (done) {
            done(null, sails);
        });
    
    
        it('should get data', function (done) {
            request(sails.hooks.http.app)
                .get('/list/item')
                .send({id: 123, someOtherParam: "something"})
                .expect(200)
                .end(function (err, res) {
                    if (err) return done(err);
    
                    should.exist(res.body);
    
                    done();
                });
        });
    });
    

    Now, open mocha.opts file (if you are confused look at screenshot above) and add something like this:

    --bail
    --timeout 20s
    test/bootstrap.test.js
    test/integration/controllers/**/*.test.js
    

    Finally, type mocha in terminal from inside your root folder to run tests!

    You can also add script to package.json like this:

      "scripts": {
        "test": "mocha"
      },
    

    And then simply run: npm test