Angular Testing Snippets: Component (1)

Testing Inputs and Outputs for Angular Components

Angular is all about components, right? Splitting up apps into small, re-usable pieces, then composing sophisticated user interfaces from them.

How can we make sure that our components work in every place of the application? What if we need to change one of the basic components that is being used in lots of places? Let’s say we wrote a color picker or a multi-select text field or a file upload. They’re probably used more than once or maybe even in multiple applications, if we distributed them in a library. When we find out the need to change one of these components, how can we make sure that we don’t break all our apps?

Well, obviously, writing good tests helps stabilizing a public API! Let’s see how we can do that for our Angular @Commponent()‘s!

Code by example: NumberComponent

First, here is an example for a component. A simple input for a number value, that has one @Input()and one @Output()property:

Test by pattern: assert inputs and outputs

Then, let’s write test specifications for the @Input() value: number and the @Output() onValueChanges: EventEmitter<number> property. Let the code tell its story:

Now, when running ng test with a reporter liker karma-mocha-reporter, we get a nicely formatted test report:

By reproducing this pattern, we can write small, atomic specifications for the public APIs of our Components! It will help you to keep our components stable and make sure we can distinguish ‘works as expected’ from ‘accidentally broken’.