我正在使用 jasmine 对 angularjs 控制器进行单元测试,该控制器将范围上的变量设置为调用返回 promise 对象的服务方法的结果:
var MyController = function($scope, service) {
$scope.myVar = service.getStuff();
}
服务内部:
function getStuff() {
return $http.get( 'api/stuff' ).then( function ( httpResult ) {
return httpResult.data;
} );
}
这在我的 angularjs 应用程序的上下文中工作正常,但在 jasmine 单元测试中不起作用。我已经确认“then”回调正在单元测试中执行,但 $scope.myVar 承诺永远不会设置为回调的返回值。
我的单元测试:
describe( 'My Controller', function () {
var scope;
var serviceMock;
var controller;
var httpBackend;
beforeEach( inject( function ( $rootScope, $controller, $httpBackend, $http ) {
scope = $rootScope.$new();
httpBackend = $httpBackend;
serviceMock = {
stuffArray: [{
FirstName: "Robby"
}],
getStuff: function () {
return $http.get( 'api/stuff' ).then( function ( httpResult ) {
return httpResult.data;
} );
}
};
$httpBackend.whenGET( 'api/stuff' ).respond( serviceMock.stuffArray );
controller = $controller( MyController, {
$scope: scope,
service: serviceMock
} );
} ) );
it( 'should set myVar to the resolved promise value',
function () {
httpBackend.flush();
scope.$root.$digest();
expect( scope.myVar[0].FirstName ).toEqual( "Robby" );
} );
} );
此外,如果我将控制器更改为以下单元测试通过:
var MyController = function($scope, service) {
service.getStuff().then(function(result) {
$scope.myVar = result;
});
}
为什么在单元测试中 promise 回调结果值没有被传播到 $scope.myVar?有关完整的工作代码,请参见以下 jsfiddle http://jsfiddle.net/s7PGg/5/