Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/436.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么这个单元测试失败了?(与Jasmine/AngularJS的承诺)_Javascript_Angularjs_Unit Testing_Jasmine_Angular Strap - Fatal编程技术网

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

Javascript 为什么这个单元测试失败了?(与Jasmine/AngularJS的承诺),javascript,angularjs,unit-testing,jasmine,angular-strap,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 d

指令的单元测试,其中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();

    });

}

第一个spy通过了,但是init_data spy失败了。就我个人而言,我无法理解这一点。

所以真正的问题是modal的$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();

    });

}

所以真正的问题是,modal的$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();

    });

}

如果从代码中调用
调试器
会发生什么?仍然失败。我将调试器放入以查看承诺是否正在解决。不是:(如果从代码中调用
调试器
会发生什么?仍然失败。我将调试器放入以查看承诺是否正在解决。不是:(