user3221287 user3221287 - 3 months ago 13
Node.js Question

Jasmine Testing Node.js Async modules

I\m trying to write unit tests for some code I wrote, the problem I'm running into is I expect my mock callback to be called after executing the function but my test fails as it is never called.

describe("Asynchronous specs", function() {

var mockNext;

beforeEach(function() {
mockNext = jasmine.createSpy('mockNext');
var res;
parallelRequests.APICall(testObject[0], null, mockNext);
});

it("callback spy should be called", function () {
expect(mockNext).toHaveBeenCalled();
});
});


The function being tested is quite simple:

function APICall(options, res, next) {
request(options, callback);
function callback(error, response, body) {
if (error) {
if (error.code === 'ETIMEDOUT') {
return logger.error('request timed out: ', error);
next(error);
}
logger.error('request failed: ', error);
next(error);
}
next(null);
}
}


The issue I suspect is jasmine testing the expectation before the mock callback is executed in API Call due to request's async nature. I've tried using what others suggest of using done() and flags but with no luck. Would appreciate some guidance in this matter.

Answer

Your beforeEach code is asynchronous. You have to tell yasmin when your beforeEach logic is done. You can solve this by the callback method done, that is passed to each test. Try this:

describe("Asynchronous specs", function() {

    var mockNext;        

    beforeEach(function(done) {

        parallelRequests.APICall(testObject[0], null, function(){
            mockNext = jasmine.createSpy('mockNext');
            mockNext();
            done();
        });
    });

    it("callback spy should be called", function () {
        expect(mockNext).toHaveBeenCalled();
    });
});