如何单元测试angularjs形式? [英] How to unit test angularjs form?
问题描述
我一直在学习AngularJS,关于单元测试的事情一直很顺利,但我已经达到了一个棘手的地方。
I have been learning AngularJS and things have been going pretty smoothly regarding unit testing, but I've reached a bit of a tricky spot.
假设我有一个简单形式,例如:
Suppose I have a simple form, for example:
<form name="form">
<input type="text" name="number" ng-pattern="/^d+$/">
</form>
如果我正在测试类似控制器的东西,我知道我会写这样的东西(使用Jasmine + Karma):
If I was testing something like a controller, I know that I would write it something like this (using Jasmine + Karma):
beforeEach(module('some.module'));
beforeEach(inject(/* services */) {
/* inject necessary services */
});
it('should be invalid when given bad input', function () {
form.number = 'Not a number';
expect(form.number.$valid).toBeFalsy();
expect(form.$valid).toBeFalsy();
});
但我不知道我需要注入哪些服务,而且我没有运气在 表格
指南或 ng-form
文档。
But I don't know which services I need to inject, and I haven't had any luck finding documentation on unit testing in either the forms
guide or the ng-form
documentation.
一个单位如何在Angular中测试表单?
How does one unit test a form in Angular?
推荐答案
我不相信这是对这样的东西进行单元测试的最好方法,但是在这个答案的帮助下在测试自定义角度指令和一些实验时,我想出了一种单元测试表单的方法。
I'm not convinced this is the best way to unit test something like this but with some help from this answer on testing custom angular directives and some experimentation, I figured out a way to unit test the form.
安装 karma-ng-html2js-preprocessor
并对其进行配置,我设法克和这样的工作单位测试:
After installing karma-ng-html2js-preprocessor
and configuring it, I managed to get a working unit test like this:
var scope, form;
beforeEach(function() {
module('my-module');
module('templates');
});
beforeEach(inject($rootScope, $controller, $templateCache, $compile) {
scope = $rootScope.$new()
ctrl = $controller('MyController'), {
"$scope": scope
}
templateHtml = $templateCache.get('path/to/my/template.html')
formElem = angular.element("<div>" + templateHtml + "</div>")
$compile(formElem)(scope)
form = scope.form
scope.$apply()
}
it('should not allow an invalid `width`', function() {
expect(form.$valid).toBeTruthy();
form.number.$setViewValue('BANANA');
expect(form.number.$valid).toBeFalsy()
});
这篇关于如何单元测试angularjs形式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!