Unit Testing Angular Components

Learn how to write and structure unit tests for an Angular component.

Introduction to testing in Angular

Angular provides a rich set of unit testing components that enable us to unit test all aspects of our application.

For the login component, we should write a set of unit tests that cover at least the basic logic flow of the form. We really need to test the following behaviors of the login component:

  • When the form is first presented, both the username and password fields should be blank.

  • If only the username field is filled in, then the “Login” button should be disabled.

  • If both the username and password fields are filled in, then the “Login” button should be enabled.

  • When the “Login” button is clicked, a domain event should be broadcast with the correct event key and data packet.

The Angular CLI will automatically generate a .spec.ts file for each component or service that we create using ng generate.

Examining the generated default file

Let’s now take a look at the default unit test that was generated for our component:

Get hands-on with 1200+ tech skills courses.