为什么这个单元测试失败了? (对Jasmine / AngularJS的承诺)

时间:2015-07-09 16:36:01

标签: javascript angularjs unit-testing jasmine angular-strap

指令的单元测试,其中escope是隔离的范围

我也试过用$ rootScope引入$ rootScope。$ apply()和 $ rootScope。$ digest()init_data()不是从单元测试中调用的:(((。模态是angularStrap模态。

it('should open the dialog', function(){
    spyOn(escope.mainModal.$promise, "then").and.callFake(function() {
        var deferred = $q.defer();

         deferred.resolve(true);

        return deferred.promise;
    });

    spyOn(escope, 'init_data');

    escope.openDialog();
    escope.$apply();
    expect(escope.mainModal.$promise.then).toHaveBeenCalled();
    expect(escope.init_data).toHaveBeenCalled();
});

并在指令中......

$scope.openDialog = function() {

    $scope.mainModal.$promise.then(function(f) {
        debugger
        $scope.init_data();

    });

}

第一个间谍通过,但init_data间谍失败。对于我的生活,我无法解决这个问题。

1 个答案:

答案 0 :(得分:0)

所以真正的问题是模态的$ promise是一个对象,而不是一个函数调用,间谍期待。

以下是重构"修复"测试。

it('should open the dialog', function(){

    spyOn(escope, "getModal").and.returnValue($q.when({}));
    spyOn(escope, 'init_data');

    escope.openDialog();
    escope.$apply();

    expect(escope.init_data).toHaveBeenCalled();
});

指令改变如此:

$scope.getModal = function(){
    return $scope.mainModal.$promise;
}

$scope.openDialog = function() {

    $scope.getModal().then(function(f) {

        $scope.init_data();

    });

}