Jasmine Testing Node.js异步模块

时间:2016-08-16 14:50:01

标签: node.js unit-testing asynchronous jasmine requestjs

我正在尝试为我编写的一些代码编写单元测试,我遇到的问题是我希望在执行函数后调用我的模拟回调,但我的测试失败,因为它从未被调用过。

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

正在测试的功能非常简单:

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

我怀疑的问题是由于请求的异步性质,在API调用中执行模拟回调之前测试期望的茉莉花。我尝试过使用其他建议使用done()和标志,但没有运气。在这件事上会有一些指导。

1 个答案:

答案 0 :(得分:3)

您的beforeEach代码是异步的。你必须在完成beforeEach逻辑时告诉yasmin。您可以通过回调方法done来解决这个问题,该方法将传递给每个测试。试试这个:

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