Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS : How to mock a FormController injected in scope?

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 ?

like image 789
Florian F Avatar asked Jun 14 '13 10:06

Florian F


2 Answers

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.

like image 196
g00fy Avatar answered Oct 03 '22 11:10

g00fy


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

});
like image 23
Rudi Starcevic Avatar answered Oct 03 '22 10:10

Rudi Starcevic