我还没有找到关于SO,博客甚至Angular问题的答案。我有其他使用$http
和$resource
的服务和控制器,他们的单元测试使用$httpBackend.when()
来模拟API,$httpBackend.flush()
返回响应。
不过,我对这条指令没有运气。
我根据AngularJS docs中的示例代码创建了一个异步验证器。我已经确认$http.get()
在使用$httpBackend.flush()
console.log()
之前被调用。但是,我得到了#34;没有待处理的冲洗请求#34;为$httpBackend.flush()
。顺便说一句,我也试过$httpBackend.expectGET()
,期望失败。
指令代码
'use strict';
angular.module('myApp')
.directive('myServerValidate', function ($q, $http) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attributes, ngModel) {
ngModel.$asyncValidators.server = function (modelValue, viewValue) {
return $http.get('http://myserver/api/System/ValidateField', {
params: {
field: scope.validationConfig.field,
value: '' + (modelValue || viewValue)
}
}).
then(function (successData) {
if (angular.isEmpty(successData) || angular.isEmpty(successData.Status)) {
return $q.reject();
} else if (!successData.Status) {
return $q.reject(successData.Message || '');
} else if (successData.Status) {
return $q.resolve(successData.Message || '');
}
}, function (rejectionData) {
return $q.reject(rejectionData);
});
};
}
};
});
单元测试
'use strict';
describe('Directive: myServerValidate', function () {
beforeEach(module('myApp'));
var form,
scope,
$httpBackend;
afterEach(function () {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
beforeEach(inject(function ($rootScope, $injector, $compile) {
scope = $rootScope.$new();
$httpBackend = $injector.get('$httpBackend');
$httpBackend.
when('GET', /ValidateField/).
respond(function () {
if (form.num === '1') {
return [200, {Status: true, Message: ''}, {}];
} else if (form.num === '2') {
return [200, {Status: false, Message: 'Invalid'}, {}];
} else {
return [404, {}, {}];
}
});
var element = angular.element('<form name="form">' +
'<input type="text" name="num" ng-model="model.num" hc-server-validate>' +
'</form>');
scope.model = {
num: null
};
scope.validationConfig = {
field: 'num'
};
$compile(element)(scope);
form = scope.form;
}));
it('should validate numeric value against server API', function () {
form.num.$setViewValue('1');
scope.$digest();
$httpBackend.flush();
expect(scope.model.num).toEqual('1');
expect(form.num.$valid).toBeTruthy();
});
});
我希望scope.$digest()
启动验证(它会这样做),然后会调用$http.get()
(发生这种情况),但是$httpBackend
某种程度上没有检测到呼叫,或可能$http
没有生成GET请求。