【问题标题】:jasmine unit test mock a promise茉莉花单元测试模拟一个承诺
【发布时间】:2015-01-08 12:10:08
【问题描述】:

我在测试我的 Promise 单元测试时遇到问题。

我提出了一个名为“expect(scope.test).toBe(12);”的断言。 这是在承诺中,然后在我的代码中返回。

以下是我正在尝试测试的实际代码:

$scope.getBudgets = function(){
    BudgetService.getBudgets().then(function(response) {
        $scope.test = 12;

    }, function(response) {

    });
}

下面是我的单元测试:

describe('budgetOverviewCtrl tests', function() {

beforeEach(module('app'));
beforeEach(module('ngRoute'));

var ctrl, scope, deferred;

describe('budgetOverviewCtrl with test', function() {
    beforeEach(inject(function($controller, _$rootScope_) {

        scope = _$rootScope_.$new();

        ctrl = $controller('budgetOverviewCtrl', {
            $scope: scope
        });         
    }));

    it('Should check if getBudgets service promise exists and returns as expected', inject(function($injector, $q, BudgetService) { 

        BudgetService = $injector.get("BudgetService");         

        deferred = $q.defer();
        deferred.resolve({"Hello": "World"});   

        spyOn(BudgetService, 'getBudgets').and.callFake(function() {
            return deferred.promise;
        }); 

        scope.getBudgets();

        expect(BudgetService.getBudgets).toHaveBeenCalled();

        **//Below line isnt called - this is inside the promise then.**
        expect(scope.test).toBe(12);
    }));
});
});

【问题讨论】:

    标签: javascript angularjs unit-testing jasmine karma-jasmine


    【解决方案1】:

    在测试中调用scope.getBudgets() 之后,您似乎错过了对$rootScope.$apply() 的调用。在 Angular 中,promise 成功和错误回调作为摘要循环的一部分运行,必须从测试中手动触发。

    猜你喜欢
    • 2023-03-27
    • 2016-04-02
    • 2021-05-25
    • 1970-01-01
    • 1970-01-01
    • 2017-09-27
    • 1970-01-01
    • 2015-08-25
    相关资源
    最近更新 更多