我在控制器内部发生了一些验证逻辑,我想对这个逻辑进行单元测试.
问题是我不知道如何模拟自动注入范围的表单控制器.
任何的想法 ?
AFAIK,您可以尝试两种方法:
使用该$compile服务,并使用适当的编译模板$scope($scope.$apply()编译后不要忘记co all ).Grunt的html2js是一个很好的工具,可以预处理模板,并在测试执行之前将它们添加到angular的$ templateCache中.请访问项目主页https://npmjs.org/package/grunt-html2js
使用该$controller服务,并手动进FormController给$scope.但是您还必须注入NgModelControllers模板中通常具有的所有内容.
如何模拟AngularJS表单然后测试表单$ dirty和$ valid状态:
// example usage of html form element
<form data-ng-submit="update()" name="optionsForm" novalidate="novalidate">
// example usage html button element
<button type="submit" ng-disabled="!canSave()">Update Options</button>
// Controller check if form is valid
$scope.canSave = function () {
return $scope.rideshareForm.$dirty && $scope.rideshareForm.$valid;
};
// Unit Test
// scope is injected in a beforeEach hook
it('$scope.canSave returns true if an options form is valid or false if non-valid', function() {
// mock angular form
scope.optionsForm = {};
// valid form
scope.optionsForm.$dirty = true;
scope.optionsForm.$valid = true;
expect(scope.canSave()).toBe(true);
// non-valid form
scope.rideshareForm.$dirty = true;
scope.rideshareForm.$valid = false;
expect(scope.canSave()).toBe(false);
});
Run Code Online (Sandbox Code Playgroud)