Advertisement
  1. Code
  2. JavaScript
  3. Angular

Testing Components in Angular Using Jasmine: Part 2, Services

Scroll to top
This post is part of a series called Testing Components in Angular Using Jasmine.
Testing Components in Angular Using Jasmine: Part 1
Final product imageFinal product imageFinal 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. 

Overview

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 tutorialHigh level overview of things weve discussed in the previous tutorial and things we will be discussing in this tutorialHigh 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. 

1
  it('should display the `create Paste` button', () => {
2
     //There should a create button in view

3
      expect(element.innerText).toContain("create Paste");
4
  });
5
6
  it('should not display the modal unless the button is clicked', () => {
7
      //source-model is an id for the modal. It shouldn't show up unless create button is clicked

8
      expect(element.innerHTML).not.toContain("source-modal");
9
  })
10
11
  it('should display the modal when `create Paste` is clicked', () => {
12
13
      let createPasteButton = fixture.debugElement.query(By.css("button"));
14
      //triggerEventHandler simulates a click event on the button object

15
      createPasteButton.triggerEventHandler('click',null);
16
      fixture.detectChanges();
17
      expect(element.innerHTML).toContain("source-modal");
18
     
19
  })
20
21
})

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:

1
<!--- add-paste.component.html -->
2
3
<div class="add-paste">
4
    <button> create Paste </button>
5
  <div  id="source-modal" class="modal fade in">
6
    <div class="modal-dialog" >
7
      <div class="modal-content">
8
        <div class="modal-header"></div>
9
        <div class="modal-body"></div>
10
         <div class="modal-footer"></div>
11
     </div>
12
    </div>
13
  </div>
14
</div>

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.

1
 it('should not display the modal unless the button is clicked', () => {
2
   
3
   //source-model is an id for the modal. It shouldn't show up unless create button is clicked

4
    expect(element.innerHTML).not.toContain("source-modal");
5
6
   //Component's showModal property should be false at the moment

7
    expect(component.showModal).toBeFalsy("Show modal should be initially false");
8
 })
9
10
 it('should display the modal when `create Paste` is clicked',() => {
11
   
12
    let createPasteButton = fixture.debugElement.query(By.css("button"));
13
    //create a spy on the createPaste  method

14
    spyOn(component,"createPaste").and.callThrough();
15
    
16
    //triggerEventHandler simulates a click event on the button object

17
    createPasteButton.triggerEventHandler('click',null);
18
    
19
    //spy checks whether the method was called

20
    expect(component.createPaste).toHaveBeenCalled();
21
    fixture.detectChanges();
22
    expect(component.showModal).toBeTruthy("showModal should now be true");
23
    expect(element.innerHTML).toContain("source-modal");
24
 })

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

1
<!--- add-paste.component.html -->
2
3
<div class="add-paste">
4
  <button (click)="createPaste()"> create Paste </button>
5
  <div *ngIf="showModal" id="source-modal" class="modal fade in">
6
    <div class="modal-dialog" >
7
      <div class="modal-content">
8
        <div class="modal-header"></div>
9
        <div class="modal-body"></div>
10
         <div class="modal-footer"></div>
11
     </div>
12
    </div>
13
  </div>
14
</div>
1
/* add-paste.component.ts */
2
3
export class AddPasteComponent implements OnInit {
4
5
  showModal: boolean = false;
6
  // Languages imported from Pastebin class

7
  languages: string[] = Languages;
8
  
9
  constructor() { }
10
  ngOnInit() { }
11
  
12
  //createPaste() gets invoked from the template. 

13
  public createPaste():void {
14
  	this.showModal = true;
15
  }
16
}

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. 

1
public addPaste(pastebin: Pastebin): Promise<any> {
2
    return this.http.post(this.pastebinUrl, JSON.stringify(pastebin), {headers: this.headers})
3
	   .toPromise()
4
 	   .then(response =>response.json().data)
5
 	   .catch(this.handleError);
6
}

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.

1
import { TestBed, inject } from '@angular/core/testing';
2
import { Pastebin, Languages } from './pastebin';
3
import { PastebinService } from './pastebin.service';
4
import { AppModule } from './app.module';
5
import { HttpModule } from '@angular/http';
6
7
let testService: PastebinService;
8
let mockPaste: Pastebin;
9
let responsePropertyNames, expectedPropertyNames;
10
11
describe('PastebinService', () => {
12
  beforeEach(() => {
13
   TestBed.configureTestingModule({
14
      providers: [PastebinService],
15
      imports: [HttpModule]
16
    });
17
    
18
    //Get the injected service into our tests

19
    testService= TestBed.get(PastebinService);
20
    mockPaste = { id:999, title: "Hello world", language: Languages[2], paste: "console.log('Hello world');"};
21
22
  });
23
});

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

1
  it('#getPastebin should return an array with Pastebin objects',async() => {
2
     
3
    testService.getPastebin().then(value => {
4
      //Checking the property names of the returned object and the mockPaste object

5
      responsePropertyNames = Object.getOwnPropertyNames(value[0]);
6
      expectedPropertyNames = Object.getOwnPropertyNames(mockPaste);
7
     
8
      expect(responsePropertyNames).toEqual(expectedPropertyNames);
9
      
10
    });
11
  });

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:

1
  it('#addPaste should return async paste', async() => {
2
    testService.addPaste(mockPaste).then(value => {
3
      expect(value).toEqual(mockPaste);
4
    })
5
  })

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

1
  it('#updatePaste should update', async() => {
2
    //Updating the title of Paste with id 1
3
    mockPaste.id = 1;
4
    mockPaste.title = "New title"
5
    testService.updatePaste(mockPaste).then(value => {
6
      expect(value).toEqual(mockPaste);
7
    })
8
  })
9
10
  it('#deletePaste should return null', async() => {
11
    testService.deletePaste(mockPaste).then(value => {
12
      expect(value).toEqual(null);
13
    })
14
  })

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

1
//update a paste

2
public updatePaste(pastebin: Pastebin):Promise<any> {
3
	const url = `${this.pastebinUrl}/${pastebin.id}`;
4
	return this.http.put(url, JSON.stringify(pastebin), {headers: this.headers})
5
		.toPromise()
6
		.then(() => pastebin)
7
		.catch(this.handleError);
8
}
9
//delete a paste

10
public deletePaste(pastebin: Pastebin): Promise<void> {
11
	const url = `${this.pastebinUrl}/${pastebin.id}`;
12
	return this.http.delete(url, {headers: this.headers})
13
		.toPromise()
14
		.then(() => null )
15
		.catch(this.handleError);
16
}

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.

1
describe('AddPasteComponent', () => {
2
  .
3
  .
4
  .
5
  describe("AddPaste Modal", () => {
6
  
7
    let inputTitle: HTMLInputElement;
8
    let selectLanguage: HTMLSelectElement;
9
    let textAreaPaste: HTMLTextAreaElement;
10
    let mockPaste: Pastebin;
11
    let spyOnAdd: jasmine.Spy;
12
    let pastebinService: PastebinService;
13
    
14
    beforeEach(() => {
15
      
16
      component.showModal = true;
17
      fixture.detectChanges();
18
19
      mockPaste = { id:1, title: "Hello world", language: Languages[2], paste: "console.log('Hello world');"};
20
      //Create a jasmine spy to spy on the addPaste method

21
      spyOnAdd = spyOn(pastebinService,"addPaste").and.returnValue(Promise.resolve(mockPaste));
22
      
23
    });
24
  
25
  });
26
});

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. 

1
  it("should accept input values", () => {
2
      //Query the input selectors

3
      inputTitle = element.querySelector("input");
4
      selectLanguage = element.querySelector("select");
5
      textAreaPaste = element.querySelector("textarea");
6
      
7
      //Set their value

8
      inputTitle.value = mockPaste.title;
9
      selectLanguage.value = mockPaste.language;
10
      textAreaPaste.value = mockPaste.paste;
11
      
12
      //Dispatch an event

13
      inputTitle.dispatchEvent(new Event("input"));
14
      selectLanguage.dispatchEvent(new Event("change"));
15
      textAreaPaste.dispatchEvent(new Event("input"));
16
17
      expect(mockPaste.title).toEqual(component.newPaste.title);
18
      expect(mockPaste.language).toEqual(component.newPaste.language);
19
      expect(mockPaste.paste).toEqual(component.newPaste.paste);
20
    });

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:

1
    newPaste: Pastebin = new Pastebin();

And update the template with the following code:

1
<!--- add-paste.component.html -->
2
<div class="add-paste">
3
  <button type="button" (click)="createPaste()"> create Paste </button>
4
  <div *ngIf="showModal"  id="source-modal" class="modal fade in">
5
    <div class="modal-dialog" >
6
      <div class="modal-content">
7
        <div class="modal-header">
8
           <h4 class="modal-title"> 
9
        	 <input  placeholder="Enter the Title" name="title" [(ngModel)] = "newPaste.title" />
10
          </h4>
11
        </div>
12
        <div class="modal-body">
13
      	 <h5> 
14
      		<select name="category"  [(ngModel)]="newPaste.language" >
15
      			<option  *ngFor ="let language of languages" value={{language}}> {{language}} </option>
16
        	</select>
17
         </h5>     	
18
      	 <textarea name="paste" placeholder="Enter the code here" [(ngModel)] = "newPaste.paste"> </textarea>
19
      	</div>
20
      <div class="modal-footer">
21
        <button type="button" (click)="onClose()">Close</button>
22
        <button type="button" (click) = "onSave()">Save</button>
23
      </div>
24
     </div>
25
    </div>
26
  </div>
27
</div>

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.

1
 it("should submit the values", async() => {   
2
   component.newPaste = mockPaste;
3
   component.onSave();
4
    fixture.detectChanges();
5
    fixture.whenStable().then( () => {
6
        fixture.detectChanges();
7
        expect(spyOnAdd.calls.any()).toBeTruthy();
8
    });
9
10
 });
11
 
12
 it("should have a onClose method", () => {
13
    component.onClose();
14
    fixture.detectChanges();
15
    expect(component.showModal).toBeFalsy();
16
  })

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.

1
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
2
import { Pastebin, Languages } from '../pastebin';
3
import { PastebinService } from '../pastebin.service';
4
5
@Component({
6
  selector: 'app-add-paste',
7
  templateUrl: './add-paste.component.html',
8
  styleUrls: ['./add-paste.component.css']
9
})
10
export class AddPasteComponent implements OnInit {
11
12
  @Output() addPasteSuccess: EventEmitter<Pastebin> = new EventEmitter<Pastebin>();
13
  showModal: boolean = false;
14
  newPaste: Pastebin = new Pastebin();
15
  languages: string[] = Languages;
16
17
  constructor(private pasteServ: PastebinService) { }
18
19
  ngOnInit() {  }
20
  //createPaste() gets invoked from the template. This shows the Modal

21
  public createPaste():void {
22
    this.showModal = true;
23
    
24
  }
25
  //onSave() pushes the newPaste property into the server

26
  public onSave():void {
27
    this.pasteServ.addPaste(this.newPaste).then( () => {
28
      console.log(this.newPaste);
29
        this.addPasteSuccess.emit(this.newPaste);
30
        this.onClose();
31
    });
32
  }
33
  //Used to close the Modal

34
  public onClose():void {
35
    this.showModal=false;
36
  }
37
}

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. 

1
 describe("AddPaste Modal", () => {
2
   
3
    beforeEach(() => {
4
    .
5
    .
6
   //Subscribe to the event emitter first

7
   //If the emitter emits something, responsePaste will be set

8
   component.addPasteSuccess.subscribe((response: Pastebin) => {responsePaste = response},)
9
      
10
    });
11
    
12
    it("should accept input values", async(() => {
13
    .
14
    .
15
      component.onSave();
16
      fixture.detectChanges();
17
      fixture.whenStable().then( () => {
18
        fixture.detectChanges();
19
        expect(spyOnAdd.calls.any()).toBeTruthy();
20
        expect(responsePaste.title).toEqual(mockPaste.title);
21
      });
22
    }));
23
  
24
  });
25

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:

1
<app-add-paste (addPasteSuccess)= 'onAddPaste($event)'> </app-add-paste> 

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

1
 //This will be invoked when the child emits addPasteSuccess event

2
 public onAddPaste(newPaste: Pastebin) {
3
    this.pastebin.push(newPaste);
4
  }

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:

1
import { BrowserModule } from '@angular/platform-browser';
2
import { NgModule } from '@angular/core';
3
4
//Components

5
import { AppComponent } from './app.component';
6
import { PastebinComponent } from './pastebin/pastebin.component';
7
import { AddPasteComponent } from './add-paste/add-paste.component';
8
//Service for Pastebin

9
10
import { PastebinService } from "./pastebin.service";
11
12
//Modules used in this tutorial

13
import { HttpModule }    from '@angular/http';
14
import { FormsModule } from '@angular/forms';
15
16
//In memory Web api to simulate an http server

17
import { InMemoryWebApiModule } from 'angular-in-memory-web-api';
18
import { InMemoryDataService }  from './in-memory-data.service';
19
20
@NgModule({
21
  declarations: [
22
    AppComponent,
23
    PastebinComponent,
24
    AddPasteComponent,
25
  ],
26
  
27
  imports: [
28
    BrowserModule, 
29
    HttpModule,
30
    FormsModule,
31
    InMemoryWebApiModule.forRoot(InMemoryDataService),
32
  ],
33
  providers: [PastebinService],
34
  bootstrap: [AppComponent]
35
})
36
export class AppTestingModule { }

Now you can replace:

1
 beforeEach(async(() => {
2
    TestBed.configureTestingModule({
3
      declarations: [ AddPasteComponent ],
4
      imports: [ HttpModule, FormsModule ],
5
      providers: [ PastebinService ],
6
    })
7
    .compileComponents();
8
}));

with:

1
beforeEach(async(() => {
2
    TestBed.configureTestingModule({
3
      imports: [AppTestingModule]
4
    })
5
    .compileComponents();
6
  }));

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 modeMock design of the ViewPasteComponent in edit modeMock design of the ViewPasteComponent in edit mode
Edit mode
Mock design of the ViewPasteComponent in view modeMock design of the ViewPasteComponent in view modeMock 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. 

1
 it('should show a button with text View Paste', ()=> {
2
    expect(element.textContent).toContain("View Paste");
3
  });
4
5
  it('should not display the modal until the button is clicked', () => {
6
      expect(element.textContent).not.toContain("source-modal");
7
  });

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. 

1
beforeEach(()=> {
2
      //Set showPasteModal to true to ensure that the modal is visible in further tests
3
      component.showPasteModal = true;
4
      mockPaste = {id:1, title:"New paste", language:Languages[2], paste: "console.log()"};
5
      
6
      //Inject PastebinService
7
      pastebinService = fixture.debugElement.injector.get(PastebinService);
8
      
9
      //Create spies for deletePaste and updatePaste methods
10
      spyOnDelete = spyOn(pastebinService,'deletePaste').and.returnValue(Promise.resolve(true));
11
      spyOnUpdate = spyOn(pastebinService, 'updatePaste').and.returnValue(Promise.resolve(mockPaste));
12
     
13
      //component.paste is an input property 
14
      component.paste = mockPaste;
15
      fixture.detectChanges();
16
     
17
    })

Here are the tests.

1
 it('should display the modal when the view Paste button is clicked',() => {
2
    
3
    fixture.detectChanges();
4
    expect(component.showPasteModal).toBeTruthy("Show should be true");
5
    expect(element.innerHTML).toContain("source-modal");
6
})
7
8
it('should display title, language and paste', () => {
9
    expect(element.textContent).toContain(mockPaste.title, "it should contain title");
10
    expect(element.textContent).toContain(mockPaste.language, "it should contain the language");
11
    expect(element.textContent).toContain(mockPaste.paste, "it should contain the paste");
12
});

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. 

1
it('should have all the buttons',() => {
2
      expect(element.innerHTML).toContain('Edit Paste');
3
      expect(element.innerHTML).toContain('Delete');
4
      expect(element.innerHTML).toContain('Close');
5
});

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

1
<!--- view-paste.component.html -->
2
<div class="view-paste">
3
    <button class="text-primary button-text"  (click)="showPaste()"> View Paste </button>
4
  <div *ngIf="showPasteModal" id="source-modal" class="modal fade in">
5
    <div class="modal-dialog">
6
      <div class="modal-content">
7
        <div class="modal-header">
8
          <button type="button" class="close" (click)='onClose()' aria-hidden="true">&times;</button>
9
          <h4 class="modal-title">{{paste.title}} </h4>
10
        </div>
11
        <div class="modal-body">
12
      	  <h5> {{paste.language}} </h5>     	
13
      	  <pre><code>{{paste.paste}}</code></pre>
14
        </div>
15
        <div class="modal-footer">
16
          <button type="button" class="btn btn-default" (click)="onClose()" data-dismiss="modal">Close</button>
17
          <button type="button" *ngIf="!editEnabled" (click) = "onEdit()" class="btn btn-primary">Edit Paste</button>
18
           <button type = "button"  (click) = "onDelete()" class="btn btn-danger"> Delete Paste </button>
19
        </div>
20
      </div>
21
    </div>
22
  </div>
23
</div>
24
       
1
/* view-paste.component.ts */
2
3
export class ViewPasteComponent implements OnInit {
4
5
  @Input() paste: Pastebin;
6
  @Output() updatePasteSuccess: EventEmitter<Pastebin> = new EventEmitter<Pastebin>();
7
  @Output() deletePasteSuccess: EventEmitter<Pastebin> = new EventEmitter<Pastebin>();
8
9
  showPasteModal:boolean ;
10
  readonly languages = Languages;
11
  
12
  constructor(private pasteServ: PastebinService) { }
13
14
  ngOnInit() {
15
      this.showPasteModal = false;
16
  }
17
  //To make the modal window visible

18
  public showPaste() {
19
  	this.showPasteModal = true;
20
  }
21
  //Invoked when edit button is clicked

22
  public onEdit() { }
23
  
24
  //invoked when save button is clicked

25
  public onSave() { }
26
  
27
  //invoked when close button is clicked

28
  public onClose() {
29
  	this.showPasteModal = false;
30
  }
31
  
32
  //invoked when Delete button is clicked

33
  public onDelete() { }
34
  
35
}

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. 

1
it('and clicking it should make the paste editable', () => {
2
3
    component.onEdit();
4
    fixture.detectChanges();
5
    expect(component.editEnabled).toBeTruthy();
6
    //Now it should have a save button

7
    expect(element.innerHTML).toContain('Save');
8
      
9
});

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.

1
  <div *ngIf="showPasteModal" id="source-modal" class="modal fade in" >
2
3
    <div class="modal-dialog">
4
      <div class="modal-content">
5
        <!---View mode -->
6
        <ng-container *ngIf="!editEnabled">
7
        
8
          <div class="modal-header">
9
            <button type="button" class="close" (click)='onClose()' data-dismiss="modal" aria-hidden="true">&times;</button>
10
            <h4 class="modal-title"> {{paste.title}} </h4>
11
          </div>
12
          <div class="modal-body">
13
              <h5> {{paste.language}} </h5>
14
      		  <pre><code>{{paste.paste}}</code>
15
            </pre>
16
      	
17
      	  </div>
18
          <div class="modal-footer">
19
            <button type="button" class="btn btn-default" (click)="onClose()" data-dismiss="modal">Close</button>
20
            <button type="button" (click) = "onEdit()" class="btn btn-primary">Edit Paste</button>
21
            <button type = "button"  (click) = "onDelete()" class="btn btn-danger"> Delete Paste </button>
22
23
          </div>
24
        </ng-container>
25
        <!---Edit enabled mode -->
26
        <ng-container *ngIf="editEnabled">
27
          <div class="modal-header">
28
             <button type="button" class="close" (click)='onClose()' data-dismiss="modal" aria-hidden="true">&times;</button>
29
             <h4 class="modal-title"> <input *ngIf="editEnabled" name="title" [(ngModel)] = "paste.title"> </h4>
30
          </div>
31
          <div class="modal-body">
32
            <h5>
33
                <select name="category"  [(ngModel)]="paste.language">
34
                  <option   *ngFor ="let language of languages" value={{language}}> {{language}} </option>
35
                </select>
36
            </h5>
37
38
           <textarea name="paste" [(ngModel)] = "paste.paste">{{paste.paste}} </textarea>
39
          </div>
40
          <div class="modal-footer">
41
             <button type="button" class="btn btn-default" (click)="onClose()" data-dismiss="modal">Close</button>
42
             <button type = "button" *ngIf="editEnabled" (click) = "onSave()" class="btn btn-primary"> Save Paste </button>
43
             <button type = "button"  (click) = "onDelete()" class="btn btn-danger"> Delete Paste </button>      
44
          </div>
45
        </ng-container>
46
      </div>
47
    </div>
48
  </div>

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. 
1
it('should take input values', fakeAsync(() => {
2
      component.editEnabled= true;
3
      component.updatePasteSuccess.subscribe((res:any) => {response = res},)
4
      fixture.detectChanges();
5
6
      inputTitle= element.querySelector("input");
7
      inputTitle.value = mockPaste.title;
8
      inputTitle.dispatchEvent(new Event("input"));
9
      
10
      expect(mockPaste.title).toEqual(component.paste.title);
11
    
12
      component.onSave();
13
       //first round of detectChanges()

14
      fixture.detectChanges();
15
16
      //the tick() operation. Don't forget to import tick

17
      tick();
18
19
      //Second round of detectChanges()

20
      fixture.detectChanges();
21
      expect(response.title).toEqual(mockPaste.title);
22
      expect(spyOnUpdate.calls.any()).toBe(true, 'updatePaste() method should be called');
23
      
24
}))

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.

1
it('should delete the paste', fakeAsync(()=> {
2
      
3
      component.deletePasteSuccess.subscribe((res:any) => {response = res},)
4
      component.onDelete();
5
      fixture.detectChanges();
6
      tick();
7
      fixture.detectChanges();
8
      expect(spyOnDelete.calls.any()).toBe(true, "Pastebin deletePaste() method should be called");
9
      expect(response).toBeTruthy();
10
}))
11
    

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

1
/*view-paste.component.ts*/
2
export class ViewPasteComponent implements OnInit {
3
4
  @Input() paste: Pastebin;
5
  @Output() updatePasteSuccess: EventEmitter<Pastebin> = new EventEmitter<Pastebin>();
6
  @Output() deletePasteSuccess: EventEmitter<Pastebin> = new EventEmitter<Pastebin>();
7
8
  showPasteModal:boolean ;
9
  editEnabled: boolean;
10
  readonly languages = Languages;
11
  
12
  constructor(private pasteServ: PastebinService) { }
13
14
  ngOnInit() {
15
      this.showPasteModal = false;
16
  	  this.editEnabled = false;
17
  }
18
  //To make the modal window visible

19
  public showPaste() {
20
  	this.showPasteModal = true;
21
  }
22
  //Invoked when the edit button is clicked

23
  public onEdit() {
24
  	this.editEnabled=true;
25
  }
26
  //Invoked when the save button is clicked

27
  public onSave() {
28
 	this.pasteServ.updatePaste(this.paste).then( () => {
29
  		this.editEnabled= false;
30
        this.updatePasteSuccess.emit(this.paste);
31
  	})
32
  }
33
 //Invoked when the close button is clicked

34
  public onClose() {
35
  	this.showPasteModal = false;
36
  }
37
 
38
 //Invoked when the delete button is clicked

39
  public onDelete() {
40
	  this.pasteServ.deletePaste(this.paste).then( () => {
41
        this.deletePasteSuccess.emit(this.paste);
42
 	    this.onClose();
43
 	  })
44
  }
45
  
46
}

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

1
/*pastebin.component.ts */
2
  public onUpdatePaste(newPaste: Pastebin) {
3
    this.pastebin.map((paste)=> { 
4
       if(paste.id==newPaste.id) {
5
         paste = newPaste;
6
       } 
7
    })
8
  }
9
10
  public onDeletePaste(p: Pastebin) {
11
   this.pastebin= this.pastebin.filter(paste => paste !== p);
12
   
13
  }

Here's the updated pastebin.component.html:

1
<tbody>
2
    	<tr *ngFor="let paste of pastebin">
3
			<td> {{paste.id}} </td>
4
			<td> {{paste.title}} </td>
5
			<td> {{paste.language}} </td>
6
			
7
			<td> <app-view-paste [paste] = paste (updatePasteSuccess)= 'onUpdatePaste($event)' (deletePasteSuccess)= 'onDeletePaste($event)'> </app-view-paste></td> 
8
		</tr>
9
	</tbody>
10
	<app-add-paste (addPasteSuccess)= 'onAddPaste($event)'> </app-add-paste> 

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). 

1
import { RouterModule, Routes } from '@angular/router';

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

1
const appRoutes :Routes = [
2
  { path: '', component: PastebinComponent },
3
  { path: 'about', component: AboutComponent },
4
  { path: 'contact', component: ContactComponent},
5
  ];
6
 
7
 imports: [
8
    BrowserModule, 
9
    FormsModule,
10
    HttpModule,
11
    InMemoryWebApiModule.forRoot(InMemoryDataService),
12
    RouterModule.forRoot(appRoutes),
13
   
14
  ],

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.

1
{provide: APP_BASE_HREF, useValue: '/'}

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

1
<nav class="navbar navbar-inverse">
2
   <div class="container-fluid">
3
       <div class="navbar-header">
4
      	   <div class="navbar-brand" >{{title}}</div>
5
      </div>
6
   	  <ul class="nav navbar-nav bigger-text">
7
    	  <li>
8
	    	 <a routerLink="" routerLinkActive="active">Pastebin Home</a>
9
	      </li>
10
	      <li>
11
	     	 <a routerLink="/about" routerLinkActive="active">About Pastebin</a>
12
	      </li>
13
	      <li>
14
	     	 <a routerLink="/contact" routerLinkActive="active"> Contact </a>
15
	       </li>
16
	  </ul>
17
   </div>
18
</nav>
19
  <router-outlet></router-outlet>
20
21

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.

1
describe('AppComponent', () => {
2
  beforeEach(async(() => {
3
    TestBed.configureTestingModule({
4
      imports: [AppTestingModule],
5
      
6
    }).compileComponents();
7
  }));
8
9
10
  it(`should have as title 'Pastebin Application'`, async(() => {
11
    const fixture = TestBed.createComponent(AppComponent);
12
    const app = fixture.debugElement.componentInstance;
13
    expect(app.title).toEqual('Pastebin Application');
14
  }));
15
16
17
  it('should go to url',
18
    fakeAsync((inject([Router, Location], (router: Router, location: Location) => {
19
      let anchorLinks,a1,a2,a3;
20
    let fixture = TestBed.createComponent(AppComponent);
21
    fixture.detectChanges();
22
     //Create an array of anchor links

23
     anchorLinks= fixture.debugElement.queryAll(By.css('a'));
24
     a1 = anchorLinks[0];
25
     a2 = anchorLinks[1];
26
     a3 = anchorLinks[2];
27
     
28
     //Simulate click events on the anchor links

29
     a1.nativeElement.click();
30
     tick();
31
     
32
     expect(location.path()).toEqual("");
33
34
     a2.nativeElement.click();
35
     tick()
36
     expect(location.path()).toEqual("/about");
37
38
      a3.nativeElement.click();
39
      tick()
40
      expect(location.path()).toEqual("/contact");
41
    
42
  }))));
43
});

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

Screenshot of Karma test runner on Chrome displaying the final test resultsScreenshot of Karma test runner on Chrome displaying the final test resultsScreenshot 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. 

1
ng serve

Summary

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!

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.