2

ngFormController is created for you when you give a form a name.

<form name="accountForm"> will create $scope.accountForm and this allows you to do things like $scope.accountForm.$setPristine()

However, in my controller tests accountForm is undefined because I suppose it's created after the template is parsed and I'm not sure the template is even considered when testing the controller. How can I mock this up in the test?

1 Answer 1

2

I just had this same issue. What I ended up doing was using sinon.stub to make a fake form object. This object had these properties:

form = {$valid: true, $pristine: false, $dirty: true, $setPristine: function () {scope.newItemForm.$dirty = false, scope.newItemForm.$pristine = true;}};

I then set that fake to equal my scope's newItemForm.

scope.newItemForm = form;

I then tested to see if the behavior was correct, whether scope.newItemForm.$dirty = false and scope.newItemForm.$pristine = true when $setPristine was triggered and the opposite when it wasn't supposed to be triggered.

This doesn't mock all the behaviors of $setPristine, but I figure I just need to know if the method is triggered since I shouldn't be concerned about testing angular's functionality.

Sign up to request clarification or add additional context in comments.

1 Comment

What we wanted to test was a series of expectations on $setPristine, $dirty on input fields, for client and server error, validations etc. But it was getting messy in the controller. So we abandoned that idea and pushed the logic in a directive. From there it is arguably easier to get access to the formController because the ngModel on the input will register itself with the parent ^form.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.