Unit Testing Forms and Events
Explore how to unit test Angular forms by verifying initial states, form validation, and user interactions. Learn to spy on service methods to ensure domain events trigger correctly when buttons are clicked.
We'll cover the following...
Testing the form
Now that the LoginComponent is being created correctly and has all of the services that it needs, we can focus on testing the form itself.
Let’s start with a test for the initial state of the form as follows:
Here, we have a test that is checking whether the form is created correctly when the form is first loaded. Remember that when we call the fixture.detectChanges function, this will trigger the Angular change detection routine, which will ensure that our component has been rendered to the DOM. Part of this change detection will call the ngOnInit function on our component, which in turn calls the buildForm
function to set up the form.
Our test on line 2 is making sure that the loginForm member variable has been initialized and on lines 3–4 ...