AngularJS : How to mock a FormController injected in scope?

只愿长相守 提交于 2020-01-13 07:48:05

问题


I have some validation logic happening inside a controller and I'd like to unit test this logic.

The thing is I don't know how to mock the form controller that is automatically injected into the scope.

Any idea ?


回答1:


AFAIK, you can try 2 approaches:

  1. use the $compile service, and compile your template with appropriate $scope (don't forget co all $scope.$apply() after compiling). Grunt's html2js is a great tool to preprocess your templates and have them added to angular's $templateCache before test execution. See the project's homepage at https://npmjs.org/package/grunt-html2js

  2. use the $controller service, and manually inject FormController to the $scope. But you would have to also inject all NgModelControllers that you would normally have in your template.




回答2:


How about this for mocking an AngularJS form and then testing the form $dirty and $valid state:

// 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);

});


来源:https://stackoverflow.com/questions/17106201/angularjs-how-to-mock-a-formcontroller-injected-in-scope

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!