我写了一个离子应用程序。我开始为它添加测试,我正面临$resources
的问题。在这种情况下,我有这样的控制器:如何处理成功或错误承诺
.controller('newAccountCtrl', function($scope, $window, $rootScope, API, $ionicPopup, $state) {
$scope.newData = {};
$scope.$on('$ionicView.enter', function() {
$scope.newData = {};
});
$scope.newInfo = function() {
API.newAccountInfo.update({
restCode: $scope.newData.restore_code
}, $scope.newData, function(res, header) {
$scope.comty = 'update';
$window.location.href = '#/login';
}, function(err) {
if (err.data == null)
$rootScope.popup("Error", "no connection");
else
$rootScope.popup('error', err.data.error);
});
}
})
而且在服务我使功能使用$resources
请求:
angular.module('starter.services', [])
.factory('API', function($rootScope, $resource, $ionicPopup, $ionicLoading, $window) {
return {
newAccountInfo: $resource(base + '/restoreinfo/:restCode', {
restCode: '@_restCode'
}, {
update: {
method: 'PUT'
}
}, {
stripTrailingSlashes: false
});
}
,并在我的测试如下代码:
describe('newAccountCtrl', function() {
var controller,
deferredLogup, window, scope,
$rootScope,
$q, store, API,
PROMISE = {
resolve: true,
reject: false
};
beforeEach(angular.mock.module('starter'));
beforeEach(module('starter.controllers'));
beforeEach(module('starter.services'));
beforeEach(module(function($provide, $urlRouterProvider) {
$provide.value('$ionicTemplateCache', function() {});
$urlRouterProvider.deferIntercept();
}));
beforeEach(inject(function($controller, _$rootScope_, $q, _API_, _$window_) {
$q = $q;
deferredLogup = $q.defer();
$rootScope = _$rootScope_;
spyOn($rootScope, 'popup')
scope = $rootScope.$new();
API = _API_;
window = _$window_;
spyOn(API.newAccountInfo, 'update').and.callThrough(function(callback) {
deferredLogup.promise.then(callback);
return deferredLogup.promise;
});
controller = $controller('newAccountCtrl', {
'$scope': scope,
'API': API,
'$window': window
});
}));
it('expect API.newAccountInfo to Have Been Called', function() {
scope.getloghist();
expect(API.newAccountInfo.upadate).toHaveBeenCalled();
})
it('on success ', function() {
scope.newInfo();
deferredLogup.resolve();
scope.$digest();
expect(scope.comty).toBeDefined();
});
it('on unsuccessful', function() {
scope.newInfo();
deferredLogup.reject();
scope.$digest()
expect($rootScope.popup).toHaveBeenCalled();
});
});
首先想到它通过,但第二个 “成功” 错误
回报 “预期未定义被定义”。
我是新来写单元测试。我在这里错过了什么?
你好,我用callFake代替callThread并且出现同样的错误**“期望undefined被定义”**。 –
我编辑了我的答案。不知道这是否能完全解决您的问题,但它应该让您更接近。 – jlogan
感谢那工作:-) –