首页 > 解决方案 > jasmine 测试用例,用于测试调用异步调用的函数

问题描述

    var count  = 0;
    function abc(){
        asyncService.getCount(function(response){
            count = response.data;
        }, function(error){
               console.log(error);
        });
    }

    it('check count', function(){
        asyncService.getCount.and.returnValue(Promise.resolve(2));
        ctrl.abc();
        expect(count).toBe(2);
    }

我想测试茉莉花中的计数值。请帮我解决一下这个。我找不到任何解决方案。我也嘲笑了这项服务。但它仍然给计数为 0

标签: angularjsjasmine

解决方案


使用 $q,您可以使用 $rootScope.$digest(); 自己解决它。

it('check count', function(){
    asyncService.getCount.and.returnValue($q.resolve(2));
    ctrl.abc();
    $rootScope.$digest();
    expect(count).toBe(2);
}

$q 是 Promise 的 AngularJS 包装器。


推荐阅读