Simplified Angular unit testing

In this article, we will learn how to write (simple) unit tests for your Angular modeling blocks (service, component, async task, etc).

0shares

Introduction

In this article, we will learn how to write (simple) unit tests for your Angular modeling blocks (service, component, async task, etc). We will be using a simple Quotes application to demonstrate how you can write a unit test for your project. I assume you already have an understanding of how to use Angular 2+. If you are a beginner or you have interest in Angular, you can find more here.

Why do you need to test your application?

Have you been looking for a way to test what you have built based on user behavior? I really don’t expect you to test each behavior one at a time, as this method does not only waste your time but is also ineffective. Writing tests for different coupling blocks in your application will help demonstrate how these blocks behave. The Quotes application we will be looking at has a service, a component and an async task to simulate data being fetched from the server.

One of the easiest ways to test the strengths of these blocks is writing a test for each of them. You don’t necessarily need to wait until your users complain how the input field behaves when the button is clicked. Writing a test for your blocks (components, services etc) can easily detect when there is a break.

A simple Quote application

How do you set up an Angular test ?

When you create a new project with the cli (ng new appName), a default component and test file are added. Also, for those that always like a shortcut method like me, a test script is always created alongside any component module (service, component) you create using angular cli(Command Line Interface).

This test script which ends with .spec.ts is always added. Let’s take a look at the initial test script file which is the app.component.spec.ts :

You might be wondering, how can we simulate a user behavior by simply writing a test, even though the project is being rendered in a browser? As we proceed, I will demonstrate how we can simulate the app running on a browser.

By default, Angular runs on Karma which is a test runner that runs the unit tests snippet like the above app.component.spec.ts file. Karma also ensures the result of the test is printed out either in the console or in file log. Other test runners are mocha, jasmine etc.

How does the test run?

The testing package has some utilities (TestBed, async). TestBed is the main Angular utility package.

flow of running test

The describe container contains different blocks (it, beforeEach, xitetc). The beforeEach runs before any other block while others do not depend on each other to run.

From the app.component.spec.ts file, the first block is the beforeEach inside the container (describe). This is the only block that runs before any other block (it). The declaration of the app module in app.module.ts file is simulated (declared) in the beforeEach block. The component (AppComponent) declared in the beforeEach block is the main component we want to have in this testing environment. The same logic applies to other test declaration.

The compileComponents object is called to compile your component’s resources like the template, styles etc. You might not necessarily compile your component if you are using webpack:

The third block demonstrates how you can have access to the properties of the created component(AppComponent). The only property added by default is the title. You can easily check if the title you set has changed or not from the instance of the component (AppComponent) created:

The fourth block demonstrates how the test behaves in the browser environment. After creating the component, an instance of the created component (detectChanges) to simulate running on the browser environment is called. Now that the component has been rendered, you can have access to its child element by accessing the nativeElelment object of the rendered component (fixture.debugElement.nativeElement):

Now that you have familiarized yourself with the basics of testing a component. Let’s test theQuote application.

Overview of Quote application

How to test a service(QuoteService)

Services often depend on other services that Angular injects into the constructor. In many cases, it easy to create and inject these dependencies by adding providedIn: root to the injectable object which makes it accessible by any component or service:

The first two blocks in the describe container run consecutively. In the first block, the FormsModule is imported into the configure test. This ensures the forms related directives like ngModel can be used.

Also, the QuotesComponent is declared in the configTestMod similarly to how the components are declared in ngModule residing in the appModule file. The second block creates a QuoteComponent and its instance which would be used by the other blocks:

The injected service handles the manipulation of all operations (add, remove, fetch). The quoteService variable holds the injected service (QuoteService). At this point, the component is yet to be rendered until the detectChangesmethod is called:

Now let’s test if we can successfully create a post. The properties of the component can be accessed upon instantiation, so the component rendered detects the new changes when a value is passed into the quoteText model. The nativeElement object gives access to the HTML element rendered which makes it easier to check if the quote added is part of the texts rendered:

Just like the way we access an element with its CSS property, we can also access an element by its class name. Multiple classes can be accessed at the same time using By e.g By.css(‘.className.className’) .

The button clicks are simulated by calling the triggerEventHandler . The event type must be specified which ,in this case, is click. A quote displayed is expected to be deleted from the quoteList when clicked on:

spyOn objects simulate how fetchQuotesFromServer method works. It accepts two argument quoteService which is injected into the component and the method fetchQuotesFromServer . fetchQuotesFromServer is expected to return a promise. spyOn chains the method using and with a fake promise call which is returned using returnValue . Since we want to fake how the fetchQuotesFromServer works, we need to pass a promise that will resolve with a list of quotes.

Just as we have done before, the detectChanges method is called to get the updated changes. whenStable allows access to results of all async tasks when they are done:

LogRocket is a frontend logging tool that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.

In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single page apps.