使用PouchDB服务承诺进行AngularJS单元测试

时间:2014-04-17 15:00:15

标签: javascript angularjs unit-testing angularjs-factory

我有一个工厂,我试图进行单元测试,注入PouchDB包装。我遇到的问题是我有模拟PouchDB服务返回一个promise并且当promise解析时(我可以在console.log中找到successCb并且它看起来是正确的),karma期望在successCb函数中的语句正确的控制台。日志输出是,没有运行。

我不确定为什么console.log输出工作正常但是期望语句没有执行,对此事的任何帮助都将不胜感激!

以下是代码的相关摘要:

[单元测试设置]

var mockCalendarsResource, mockPouchDB;
var mockPouchDB = function(name) {
    this.name = name;
    this.post = function(newCalendar, successCb, errorCb) {
        var promise = new Promise(function(successCb, errorCb) {
            newCalendar._id = 2;
            successCb(newCalendar);
        });
        return promise;
    };
}

beforeEach(function() {
    module(function($provide) {
        $provide.value('Pouch', mockPouchDB);
    });
    angular.mock.inject(function($injector) {
        mockCalendarsResource = $injector.get('Calendar');
    });
});

[Karma单元测试代码]

describe('The calendar resource function create', function() {
    it('should create a new calendar', inject(function(Calendar) {
        var result = mockCalendarsResource.create({
            name: "Testing"
        },
        function(response) {
            //console.log here works correctly //
            //These are the expect statements not functioning //
            expect(response._id).toBe(2);
            expect(response.name).toBe('Testing');
            // Could put any expectation here and it will pass or not be checked //
        }, function(err) {

        });
    }));
});

1 个答案:

答案 0 :(得分:2)

我相信您应该使用Jasmine 2.0's done()表示测试已完成。如果不这样,那么异步测试将无法完成。