Sunday, 12 March 2017

Mocha async multiple tests (it) in a single description does not work with grunt-mocha-test

I have the following simple situation. Use mocha to run two tests (two its) for an API call with the async request method.

describe('My API', function() {
    describe('GET /api/customer', function() {
        it('should return "success"', function(done) {
            request('http://localhost:3000/api/customer', function(err, response, body) {
                var data = JSON.parse(body);
                assert(data.success, "Success is false");
                done();
            });
        });
        it('should return "rows"', function(done) {
            request('http://localhost:3000/api/customer', function(err, response, body) {
                var data = JSON.parse(body);
                assert(Array.isArray(data.rows), "No array returned");
                done();
            });
        });
    });
});

The code above works fine, but does two requests for a single purpose. Though I'd change this to do one request before the describe, so I changed the code to this:

describe('My API', function() {
    request('http://localhost:3000/api/customer', function(err, response, body) {
        var data = JSON.parse(body);
        describe('GET /api/customer', function() {
            it('should return "success"', function(done) {
                assert(data.success, "Success is false");
                done();
            });
            it('should return "rows"', function(done) {
                assert(Array.isArray(data.rows), "No array returned");
                done();
            });
        });
    });
});

When I tested with mocha from the CLI (with npm test) it works just fine. The problem with the code above (single request at the beginning) is that when run from grunt with grunt-mocha-test, the tests do not run at all. grunt-mocha-test just skips the whole describe block.

There are other describe blocks on the same file that do work fine from within grunt. The tests above work fine with grunt-mocha-test only if I use the 1st version of code with request from inside it blocks.

I could use two assert statements on the same it block but would lke to clarify what is going wrong here. What I am doing wrong here? Thank you.



via lexan

No comments:

Post a Comment