Angular JS Jasmine 测试 - Chained Promise 中变量值的多次变化

Angular JS Jasmine Testing - Multiple Changes in Variable Value in Chained Promise

我有一个链式承诺,如下所示:

myService.methodOne().then(function(){
    $scope.myVariable = true;
    return myService.methodTwo();
})
.then(function(){
    $scope.myVariable = false;
});

我如何测试 myVariable 首先分配给 true 然后分配给 false

如果我错了请纠正我,但我假设您正在测试控制器 $scope 上的函数,

例如$scope.someFunction = function () { myService.methodOne().then(function(){ $scope.myVariable = true; return myService.methodTwo(); }) .then(function(){ $scope.myVariable = false; }); };

您可以将 $q(和必要的服务)注入到您的测试中:

beforeEach(function () {
    angular.mock.module('module.with.service');
    angular.mock.module('module.with.controller');

    inject(function (_$rootScope_, _$controller_, _$q_, _myService_) {
        $rootScope = _$rootScope_;
        $controller = _$controller_;
        $q = _$q_;

        myService = _myService_;
        $scope = $rootScope.$new();
    });
});

对于您的实际测试,创建两个单独的承诺:

var deferred_methodOne = $q.defer(), deferred_methodTwo = $q.defer();

然后在 myService 上放置两个间谍(每个方法一个间谍),returns promise 对应于方法:

spyOn(myService, 'methodOne').and.returnValue(deferred_methodOne.promise); spyOn(myService, 'methodTwo').and.returnValue(deferred_methodTwo.promise);

初始设置后,初始化您的控制器并调用您正在测试的函数:

$controller('TestController', { $scope: $scope, myService: myService }); $scope.someFunction();

然后你可以单独触发promise,并测试每个触发的结果(注意你需要触发一个digest cycle 才能让promise的resolve()或reject()在$q中生效):

deferred_methodOne.resolve(); // resolve the first promise
$rootScope.$apply(); // trigger a digest cycle  
expect($scope.myVariable).toBe(true); // test the first condition

deferred_methodTwo.resolve(); // resolve the second promise
$rootScope.apply(); // trigger a digest cycle 
expect($scope.myVariable).toBe(false); // test the second condition