12

我在控制器内部发生了一些验证逻辑,我想对这个逻辑进行单元测试。

问题是我不知道如何模拟自动注入范围的表单控制器。

任何想法 ?

4

2 回答 2

5

模拟 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);

});
于 2013-11-06T05:04:47.137 回答
5

AFAIK,您可以尝试两种方法:

  1. 使用该$compile服务,并以适当的方式编译您的模板$scope(编译后不要忘记 co all $scope.$apply())。Grunt 的 html2js 是一个很好的工具,可以预处理你的模板,并在测试执行之前将它们添加到 angular 的 $templateCache 中。查看项目主页https://npmjs.org/package/grunt-html2js

  2. 使用该$controller服务,并手动注入FormController$scope. 但是您还必须注入NgModelControllers您通常在模板中拥有的所有内容。

于 2013-06-16T01:16:19.303 回答