How to test controller using mocha in Sails?

南楼画角 提交于 2019-12-05 10:46:02

I'm using supertest to call controllers as a user, to do so, first lift the sails in the before function so it can be used as the server by supertest.

before(function (done) {
 Sails.lift({
        // configuration for testing purposes
        log: {
            //level: 'silly'
            level: 'silent'
        },
        hooks: {
            grunt: false,
        },
    }, function (err, sails) {
done(err, sails);
        });
}

Then initialize supertest with the url of your sails app

request = require('supertest');
agent = request.agent(appurl);

You can now write test to post / get data to test your controller from frontend as would a client.



it('should do the post and return whatever', function (done) {
    agent.post('/controller/function')
    .send(the_post_object_with_params)
    .end(function (err, res) {
        if (err) {
            console.log(err);
        }
        console.log(res.body); // the content 
        done();
    });
}
Murilo

I think the main thing is to include sails application into your testcase. I also found no examples with controllers tests but some with models:

Is it possible to use the Mocha Framework against a model in Sails.js?

Cannot unit test my model in sailsjs

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