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 ?
AFAIK, you can try 2 approaches:
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
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.
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With