我在模拟数据服务承诺时遇到问题。
我使用AngularJS和Jasmine 2.2.0
我的代码是:
控制器
app.controller('homeController', ['$scope', 'ngAppSettings', 'homeViewModel', 'storageService', 'homeService',
function ($scope, ngAppSettings, homeViewModel, storageService, homeService) {
$scope.applicationName = ngAppSettings.applicationName;
$scope.model = homeViewModel;
storageService.getStorageAuth().then(function (data) {
$scope.model.userName= data.name;
}, function (err) {
alert(err.errors[0].message);
});
}]);
服务
app.service('storageService', ['$q', 'ngAppSettings', 'localStorageService',
function ($q, ngAppSettings, localStorageService) {
this.getStorageAuth = function () {
var deferred = $q.defer();
var userAuth = localStorageService.get(ngAppSettings.storageUser);
if (userAuth) {
data = userAuth;
}
deferred.resolve(data);
return deferred.promise;
};
}]);
测试规范
describe('Controllers: homeController', function () {
var $rootScope;
var $scope;
var ctrl;
var $q;
var deferred;
var storageService;
beforeEach(module('IspFrontEndTemplateApp'));
beforeEach(inject(function (_$q_, _storageService_) {
$q = _$q_;
storageService = _storageService_;
deferred = $q.defer();
spyOn(storageService, "getStorageAuth").and.returnValue(deferred.promise);
}));
beforeEach(inject(function (_$rootScope_, $controller) {
$rootScope = _$rootScope_;
$scope = $rootScope.$new();
ctrl = $controller('homeController', { $scope: $scope });
}));
it('UserName is: UsuarioTeste', function () {
deferred.resolve({
isAuth: true,
userName: "UsuarioTeste",
name: "UsuarioTeste"
});
expect($scope.model.userName).toBe('UsuarioTeste');
});
});
错误是:预期''成为' UsuarioTeste'。
我需要在控制器中测试我的模型属性,但该值不会刷新
答案 0 :(得分:0)
您需要再次$digest
进行测试:
$scope.$digest();
expect($scope.model.userName).toBe('UsuarioTeste'); // will work
原因是promises是异步解析的,因为promise永远不会在其创建的$apply
内调用其成功或错误回调,即使它已被解析。如果你在函数的开头创建一个promise,那么代码可能很难阅读,并且已解决的promise的效果在几行后就已经可以观察到了。