...

/

Unit Testing Forms and Events

Unit Testing Forms and Events

Learn how to test a form using Angular's change detection routine, check form validity, and spy on an injected instance.

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:

Press + to interact
it('should set form fields correctly on startup', () => {
expect(component.loginForm).toBeDefined();
expect(component.loginForm?.value.username).toEqual("");
expect(component.loginForm?.value.password).toEqual("");
});

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 ...