在角度形式指令的单元测试中设置视图值和输入字段 [英] Setting view value an input field in a unit test of an angular form directive
问题描述
我有一个构建表单的指令:
I have a directive that builds a form:
app.directive('config', function() {
return {
restrict: 'E',
scope: {
data: '='
},
template: '<form name="configForm">' +
'<input type="number" max="10" ng-model="config.item" name="configItem"/>' +
'<div class="form-error" ng-show="configForm.$error.max">Error</div>' +
'</form>',
controller: 'ConfigDirectiveController',
};
});
我想要做的是通过单元测试验证错误消息会在给出一些输入的情况下显示出来.使用 angular 1.2 我可以修改 $scope.config.item 并且它会更新视图值并显示错误.
What I want to do is validate via a unit test that the error message will show up given some input. With angular 1.2 I could modify $scope.config.item and it would update the view value and show the error.
据我所知,使用 angular 1.3,如果模型未通过验证,则视图值不会更新...因此我需要修改视图值以确保显示错误消息.
As near as I can tell, with angular 1.3, if the model does not pass validation the view value does not get updated...so I need to modify the view value to make sure the error message shows up.
如何访问configItem"输入,以便设置视图值以确保显示错误消息?
How can I get access to the "configItem" input so that I can set the view value to ensure that the error message will show up?
编辑以显示单元测试
我看到该值已正确设置,但该错误仍然对标签应用了 ng-hide.当我查看页面并手动更改输入值时,ng-hide 将被删除,如果我输入大于 10 的内容,则会显示错误.
I see that the value is set properly, but the error still has an ng-hide applied to the tag. When I am viewing the page and manually changing the input value, the ng-hide will be removed and the error will display if I enter in something greater than 10.
beforeEach(inject(function($compile, $rootScope) {
element = angular.element('<config data="myData"></config>');
$scope = $rootScope.$new();
$scope.myData = {};
element = $compile(element)($scope);
}));
it('should warn that we have a large number', function() {
var input = element.find('[name="configItem"]')[0];
$scope.$apply(function() {
angular.element(input).val('9000000001');
});
errors = element.find('[class="form-error ng-binding"]');
expect(errors.length).toBe(1);
})
推荐答案
以下是我对基于输入的指令进行单元测试的方式(为了清楚起见省略了大量代码!)您所追求的重要一行是:
Here's how I've been unit testing my input-based directives (Lots of code omitted for clarity!) The important line you are after is:
angular.element(dirElementInput).val('Some text').trigger('input');
这是完整的单元测试:
it('Should show a red cross when invalid', function () {
dirElement = angular.element('<ng-form name="dummyForm"><my-text-entry ng-model="name"></my-text-entry></ng-form>');
compile(dirElement)(scope);
scope.$digest();
// Find the input control:
var dirElementInput = dirElement.find('input');
// Set some text!
angular.element(dirElementInput).val('Some text').trigger('input');
scope.$apply();
// Check the outcome is what you expect! (in my case, that a specific class has been applied)
expect(dirElementInput.hasClass('ng-valid')).toEqual(true);
});
这篇关于在角度形式指令的单元测试中设置视图值和输入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!