How to unit test your Angular 9 application using karma testing framework.

In this article I will offer the best tips and techniques for unit and integration testing your Angular 9 applications.

1 — Create a new Angular 9 application

First let’s create a simple Angular 9 application which we will use for the demonstration purposes of how to implement unit testing.

ng new UnitTestExample

2 — How to run the unit tests for your application

I would like to point out that by default when you create a new component in your application, Angular CLI will automatically create a “spec” file along with the other files needed for a component to be created unless you specifically tell it not to.

ng test
  • should render the title
  • should have a title ‘UnitTestExample’

3 — Create a new unit test for your component

Now that we know how to run our unit tests, lets create a new unit test and run it to see how it behaves.

<h1>{{title}}</h1>
<br>
<button (click)=’onClick()’>
Change Page Title to ‘Unit Test App”</button>
onClick(){
this.title = ‘Unit Test App’;
}
  1. Unit test to execute the button event and confirm that the new title is now “Unit Test App”
it(`should have as title ‘UnitTestExample’`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app.title).toEqual(‘UnitTestExample’);
});
it(‘should change title to Unit Test App’, async(() => {
const fixture = TestBed.createComponent(AppComponent);
fixture.nativeElement.querySelector(‘button’).click();
fixture.detectChanges();
expect(fixture.nativeElement.querySelector(‘h1’)
.textContent).toEqual('Unit Test App');
}));

4 — Run newly created unit tests

Let’s run the unit tests by running the following command in VScode:

ng test

5 — Fail unit test case

Now I will show you what it is like to have a failed spec. We will purposely create a scenario so that we can see at least one of the specs fail.

6 — Conclusion

The goal of unit testing is to segregate each part of the program and test that the individual parts are working correctly. It isolates the smallest piece of testable software from the remainder of the code and determines whether it behaves exactly as you expect.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store