Testing Components in Angular Using Jasmine: Part 2, Services

Testing Components in Angular Using Jasmine: Part 2, Services

Final product image
What You'll Be Creating

This is the second installment of the series on testing in Angular using Jasmine. In the first part of the tutorial, we wrote basic unit tests for the Pastebin class and the Pastebin component. The tests, which initially failed, were made green later. 


Here is an overview of what we will be working on in the second part of the tutorial.

High level overview of things weve discussed in the previous tutorial and things we will be discussing in this tutorial

In this tutorial, we will be:

  • creating new components and writing more unit tests
  • writing tests for the component's UI
  • writing unit tests for the Pastebin service
  • testing a component with inputs and outputs
  • testing a component with routes

Let's get started!

Adding a Paste (continued)

We were halfway through the process of writing unit tests for the AddPaste component. Here's where we left off in part one of the series. 

As previously mentioned, we won't be writing rigorous UI tests. Instead, we will write some basic tests for the UI and look for ways to test the component's logic. 

The click action is triggered using the DebugElement.triggerEventHandler() method, which is a part of the Angular testing utilities. 

The AddPaste component is essentially about creating new pastes; hence, the component's template should have a button to create a new paste. Clicking the button should spawn a 'modal window' with an id 'source-modal' which should stay hidden otherwise. The modal window will be designed using Bootstrap; therefore, you might find lots of CSS classes inside the template.

The template for the add-paste component should look something like this:

The second and third tests do not give any information about the implementation details of the component. Here's the revised version of add-paste.component.spec.ts.

The revised tests are more explicit in that they perfectly describe the component's logic. Here's the AddPaste component and its template.

The tests should still fail because the spy on addPaste fails to find such a method in the PastebinService. Let's go back to the PastebinService and put some flesh on it. 

Writing Tests for Services

Before we proceed with writing more tests, let's add some code to the Pastebin service. 

addPaste() is the service's method for creating new pastes.  http.post returns an observable, which is converted into a promise using the toPromise() method. The response is transformed into JSON format, and any runtime exceptions are caught and reported by handleError().

Shouldn't we write tests for services, you might ask? And my answer is a definite yes. Services, which get injected into Angular components via Dependency Injection(DI), are also prone to errors. Moreover, tests for Angular services are relatively easy. The methods in PastebinService ought to resemble the four CRUD operations, with an additional method to handle errors. The methods are as follows:

  • handleError()
  • getPastebin()
  • addPaste()
  • updatePaste()
  • deletePaste()

We've implemented the first three methods in the list. Let's try writing tests for them. Here's the describe block.

We've used TestBed.get(PastebinService) to inject the real service into our tests. 

getPastebin returns an array of Pastebin objects. TypeScript's compile-time type checking can't be used to verify that the value returned is indeed an array of Pastebin objects. Hence, we've used Object.getOwnPropertNames() to ensure that both the objects have the same property names.

The second test follows:

Both the tests should pass. Here are the remaining tests.

Revise pastebin.service.ts with the code for the updatePaste() and deletePaste() methods.

Back to Components

The remaining requirements for the AddPaste component are as follows:

  • Pressing the Save button should invoke the Pastebin service's addPaste() method.
  • If the addPaste operation is successful, the component should emit an event to notify the parent component.
  • Clicking the Close button should remove the id 'source-modal' from the DOM and update the showModal property to false.

Since the above test cases are concerned with the modal window, it might be a good idea to use nested describe blocks.

Declaring all the variables at the root of the describe block is a good practice for two reasons. The variables will be accessible inside the describe block in which they were declared, and it makes the test more readable. 

The above test uses the querySelector() method to assign inputTitle, SelectLanguage and textAreaPaste their respective HTML elements (<input>, <select>, and <textArea>). Next, the values of these elements are replaced by the mockPaste's property values. This is equivalent to a user filling out the form via a browser. 

element.dispatchEvent(new Event("input")) triggers a new input event to let the template know that the values of the input field have changed. The test expects that the input values should get propagated into the component's newPaste property.

Declare the newPaste property as follows:

And update the template with the following code:

The extra divs and classes are for the Bootstrap's modal window. [(ngModel)] is an Angular directive that implements two-way data binding. (click) = "onClose()" and (click) = "onSave()" are examples of event binding techniques used to bind the click event to a method in the component. You can read more about different data binding techniques in Angular's official Template Syntax Guide

If you encounter a Template Parse Error, that's because you haven't imported the FormsModule into the AppComponent. 

Let's add more specs to our test.

component.onSave() is analogous to calling triggerEventHandler() on the Save button element. Since we have added the UI for the button already, calling component.save() sounds more meaningful. The expect statement checks whether any calls were made to the spy. Here's the final version of the AddPaste component.

If the onSave operation is successful, the component should emit an event signaling the parent component (Pastebin component) to update its view. addPasteSuccess, which is an event property decorated with a @Output decorator, serves this purpose. 

Testing a component that emits an output event is easy. 

The test subscribes to the addPasteSuccess property just as the parent component would do. The expectation towards the end verifies this. Our work on the AddPaste component is done. 

Uncomment this line in pastebin.component.html:

And update pastebin.component.ts with the below code.

If you run into an error, it's because you haven't declared the AddPaste component in Pastebin component's spec file. Wouldn't it be great if we could declare everything that our tests require in a single place and import that into our tests? To make this happen, we could either import the AppModule into our tests or create a new Module for our tests instead. Create a new file and name it app-testing-module.ts:

Now you can replace:


The metadata that define providers and declarations  have disappeared and instead, the AppTestingModule gets imported. That's neat!  TestBed.configureTestingModule() looks sleeker than before. 

View, Edit, and Delete Paste

The ViewPaste component handles the logic for viewing, editing, and deleting a paste. The design of this component is similar to what we did with the AddPaste component. 

Mock design of the ViewPasteComponent in edit mode
Edit mode
Mock design of the ViewPasteComponent in view mode
View mode

The objectives of the ViewPaste component are listed below:

  • The component's template should have a button called View Paste.
  • Clicking the View Paste button should display a modal window with id 'source-modal'. 
  • The paste data should propagate from the parent component to the child component and should be displayed inside the modal window.
  • Pressing the edit button should set component.editEnabled to true (editEnabled is  used to toggle between edit mode and view mode)
  • Clicking the Save button should invoke the Pastebin service's updatePaste() method.
  • A click on the Delete button should invoke the Pastebin service's deletePaste() method.
  • Successful update and delete operations should emit an event to notify the parent component of any changes in the child component. 

Let's get started! The first two specs are identical to the tests that we wrote for the AddPaste component earlier. 

Similar to what we did earlier, we will create a new describe block and place the rest of the specs inside it. Nesting describe blocks this way makes the spec file more readable and the existence of a describe function more meaningful.  

The nested describe block will have a beforeEach() function where we will initialize two spies, one for the updatePaste() method and the other for the deletePaste() method. Don't forget to create a mockPaste object since our tests rely on it. 

Here are the tests.

The test assumes that the component has a paste property that accepts input from the parent component. Earlier, we saw an example of how events emitted from the child component can be tested without having to include the host component's logic into our tests. Similarly, for testing the input properties, it's easier to do so by setting the property to a mock object and expecting the mock object's values to show up in the HTML code.

The modal window will have lots of buttons, and it wouldn't be a bad idea to write a spec to guarantee that the buttons are available in the template. 

Let's fix up the failing tests before taking up more complex tests.

Being able to view the paste is not enough. The component is also responsible for editing, updating, and deleting a paste. The component should have an editEnabled property, which will be set to true when the user clicks on the Edit paste button. 

Add editEnabled=true; to the onEdit() method to clear the first expect statement. 

The template below uses the ngIf directive to toggle between view mode and edit mode. <ng-container> is a logical container that is used to group multiple elements or nodes.

The component should have two Output() event emitters, one for updatePasteSuccess property and the other for deletePasteSuccess. The test below verifies the following:

  1. The component's template accepts input.
  2. The template inputs are bound to the component's paste property.
  3. If the update operation is successful, updatePasteSuccess emits an event with the updated paste. 

The obvious difference between this test and the previous ones is the use of the fakeAsync function. fakeAsync is comparable to async because both the functions are used to run tests in an asynchronous test zone. However, fakeAsync makes your look test look more synchronous. 

The tick() method replaces fixture.whenStable().then(), and the code is more readable from a developer's perspective. Don't forget to import fakeAsync and tick from @angular/core/testing.

Finally, here is the spec for deleting a paste.

We're nearly done with the components. Here's the final draft of the ViewPaste component.

The parent component (pastebin.component.ts) needs to be updated with methods to handle the events emitted by the child component.

Here's the updated pastebin.component.html:

Setting Up Routes

To create a routed application, we need a couple more stock components so that we can create simple routes leading to these components. I've created an About component and a Contact component so that we can fit them inside a navigation bar. AppComponent will hold the logic for the routes. We will write the tests for routes after we're finished with them. 

First, import RouterModule and Routes into AppModule (and AppTestingModule). 

Next, define your routes and pass the route definition to the RouterModule.forRoot method.

Any changes made to the AppModule should also be made to the AppTestingModule. But if you run into a No base href set error while executing the tests, add the following line to your AppTestingModule's providers array.

Now add the following code to app.component.html.

routerLink is a directive that is used to bind an HTML element with a route. We've used it with the HTML anchor tag here.  RouterOutlet is another directive that marks the spot in the template where the router's view should be displayed. 

Testing routes is a bit tricky since it involves more UI interaction. Here's the test that checks whether the anchor links are working.

If everything goes well, you should see something like this.

Screenshot of Karma test runner on Chrome displaying the final test results

Final Touches

Add a nice-looking Bootstrap design to your project, and serve your project if you haven't done that already. 


We wrote a complete application from scratch in a test-driven environment. Isn't that something? In this tutorial, we learned:

  • how to design a component using the test first approach
  • how to write unit tests and basic UI tests for components
  • about Angular's testing utilities and how to incorporate them into our tests
  • about using async() and fakeAsync() to run asynchronous tests
  • the basics of routing in Angular and writing tests for routes

I hope you enjoyed the TDD workflow. Please get in touch via the comments and let us know what you think!

Our final result

Source: Tuts Plus

About the Author