简体   繁体   中英

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.

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();
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM