0

I am trying to unit-test the controllers of a Sails.js project with mocha. Since I have a different security policies I cannot use suptertest or similar testing frameworks to test the controllers, by actually calling the url. I would have to make sure the parameters of the call would pass all policies.

Instead I am trying to call the methods of the controllers directly with sails.controllers.[controller].[methods](req, res) like suggested here, and spy on the res object with sinon.

But whenever I call a controller method e.g. sails.controllers.booking.approve(req, res) I get the error message TypeError: sails.controllers.booking.approve(...) is not a function. How can I call the controller method instead?

Lando-L
  • 843
  • 6
  • 19
  • To the best of my knowledge aren't only models and services exposed in the global sails object ? https://sailsjs.com/documentation/concepts/globals – UchihaItachi Nov 13 '17 at 13:18
  • Yes, only models and services are exposed as global variables. This means there is no global e.g. `RabbitController`, but you can still access the controllers using the global `sails` object like `sails.controllers.rabbit.[action]`. – Lando-L Nov 14 '17 at 11:55

1 Answers1

1

NPM to install Mocha, Grunt Mocha Test, Sinon and the Assert library

I modified the Gruntfile.js at the root of the project to use Grunt Mocha Tests,

grunt.initConfig({

mochaTest: {
  test: {
    options: {
      reporter: 'spec'
    },
    src: ['tests/**/*.spec.js']
  }
},

...
});

Then add and register the task to run the test:

grunt.loadNpmTasks('grunt-mocha-test');
grunt.registerTask('test', ['mochaTest']);

Example: AboutController.js

module.exports = {

  index: function (req, res) {
    return res.view();
  },

  _config: {}
};

test inside tests/controllers and name it about.spec.js

var AboutController = require('../../api/controllers/AboutController'),
sinon = require('sinon'),
assert = require('assert');
describe('The About Controller', function () {
  describe('when we load the about page', function () {
    it ('should render the view', function () {
        var view = sinon.spy();
        AboutController.index(null, {
            view: view
        });
        assert.ok(view.called);
       });
  });
});
PRADEEP Kumar
  • 232
  • 1
  • 7
  • Thank you for the detailed explanation. Strange enough always when I put a `req` Object to the method call, like `AboutController.index(req, res)`, I get a `AboutController.index(...) is not a function` error. – Lando-L Nov 14 '17 at 11:20
  • Yes it is working now! Thank you for the addition of the mocha-grunt task. I was just using mocha with should.js. – Lando-L Nov 14 '17 at 14:23