How use mocha test framework with node.js and sails.js

2,161 views
Skip to first unread message

Vadorequest Mini Vado

unread,
Feb 15, 2014, 9:33:18 AM2/15/14
to sai...@googlegroups.com
I just opened a new discussion at SO about mocha and tests using sails.js but it's an opened discussion about tests in node.js whith sails.js or not.

Chad McElligott

unread,
Feb 15, 2014, 7:45:38 PM2/15/14
to sai...@googlegroups.com
Because your question is sort of open-ended and doesn't really have 'one right answer', i don't feel like it lends very well to the stack exchange format, so i'll just give you my thoughts here.

The direction you are headed looks fine. I think you'll more than likely just need to try it out and see for yourself. We use mocha/chai/sinon to test our Sails stuff at work and it does a fine job of it, both client and server-side. 

Because of the way that Sails builds up your models and stuff for you, you may find the need to programmatically lift Sails to do your testing. You will probably end up writing a helper to handle this. One way to deal with this is to have a js file that registers a global before() mocha hook that lifts sails and a global after() hook that lowers sails. Then just make sure this file is included in your test suite, either through an explicit require() or some other mechanism.

Supertest is one easy way to perform API tests against your controllers. You can point supertest at the express app itself, which is located at sails.express.app. For example:

var req = require('supertest');

describe('when not authenticated', function () {
    describe('list', function () {
        it('returns 401 unauthorized and error json', function (done) {
            req(sails.express.app)
                .get(apiEndpoint)
                .expect(401)
                .expect('Content-Type', /json/, done);
        });
    });
});

We use Sinon with Mocha to provide spy/mock/stub support. This is really useful when you want to just check that your code is calling out to the right dependencies with correct parameters without it *actually* doing it. Sinon also has some built-in assertion methods as well. A good use-case for Sinon would be to test middleware/policies to ensure it is calling the right methods on the response, or calling the callback, in the appropriate circumstances.

We also use karma test runner to spin up our client-side mocha tests in actual browsers. 

Ambroise Dhenain

unread,
Feb 16, 2014, 3:49:41 AM2/16/14
to Chad McElligott, sai...@googlegroups.com
Thank you for the explanation, I think I should download the 0.10 and see how you implement your tests on sails to have a guideline. Do you have any documentation about tests?
--
Cordialement,

M. Ambroise Dhenain.
Reply all
Reply to author
Forward
0 new messages