【问题标题】:Why does this unit test fail? (Promises with Jasmine/AngularJS)为什么这个单元测试会失败? (与 Jasmine/AngularJS 的承诺)
【发布时间】:2015-07-09 16:36:01
【问题描述】:

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

我也尝试使用 $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 间谍失败。对于我的生活,我无法弄清楚这一点。

【问题讨论】:

  • 如果您从代码中取出 debugger 调用会发生什么?
  • 仍然失败。我把调试器放进去看看promise是否正在解决。不是:(

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


【解决方案1】:

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

这是“修复”测试的重构。

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();

    });

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多