javascript - Jasmine 单元测试模拟一个 promise

标签 javascript angularjs unit-testing jasmine karma-jasmine

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

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

下面是我要测试的实际代码:

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

最佳答案

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

关于javascript - Jasmine 单元测试模拟一个 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27839842/

相关文章:

javascript - 如何使用 jquery.dirtyforms?

javascript - 嵌套 View 在 Ionic 中变为空白

java - PowerMock + TestNg | PowerMock + TestNg | PowerMock + TestNg预期异常不起作用

unit-testing - 单元测试 Angular 右键单击指令

javascript - 如何跟踪是否使用 javascript 选择了文件?

javascript - 如果每个字符都在 0-9 范围内,则去掉所有前导零

javascript - 如何使用for循环在javascript中创建多个文本框?

javascript - 我可以将类属性传递给 angularJS 中的指令模板吗?

javascript - 通过 ng-repeat 中的键过滤对象

c# - 没有 DI 的单元测试遗留代码