
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.

In this tutorial, we will be:
Let's get started!
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.
it('should display the `create Paste` button', () => {
//There should a create button in view
expect(element.innerText).toContain("create Paste");
});
it('should not display the modal unless the button is clicked', () => {
//source-model is an id for the modal. It shouldn't show up unless create button is clicked
expect(element.innerHTML).not.toContain("source-modal");
})
it('should display the modal when `create Paste` is clicked', () => {
let createPasteButton = fixture.debugElement.query(By.css("button"));
//triggerEventHandler simulates a click event on the button object
createPasteButton.triggerEventHandler('click',null);
fixture.detectChanges();
expect(element.innerHTML).toContain("source-modal");
})
})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:
<!--- add-paste.component.html -->
<div class="add-paste">
<button> create Paste </button>
<div id="source-modal" class="modal fade in">
<div class="modal-dialog" >
<div class="modal-content">
<div class="modal-header"></div>
<div class="modal-body"></div>
<div class="modal-footer"></div>
</div>
</div>
</div>
</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.
it('should not display the modal unless the button is clicked', () => {
//source-model is an id for the modal. It shouldn't show up unless create button is clicked
expect(element.innerHTML).not.toContain("source-modal");
//Component's showModal property should be false at the moment
expect(component.showModal).toBeFalsy("Show modal should be initially false");
})
it('should display the modal when `create Paste` is clicked',() => {
let createPasteButton = fixture.debugElement.query(By.css("button"));
//create a spy on the createPaste method
spyOn(component,"createPaste").and.callThrough();
//triggerEventHandler simulates a click event on the button object
createPasteButton.triggerEventHandler('click',null);
//spy checks whether the method was called
expect(component.createPaste).toHaveBeenCalled();
fixture.detectChanges();
expect(component.showModal).toBeTruthy("showModal should now be true");
expect(element.innerHTML).toContain("source-modal");
})The revised tests are more explicit in that they perfectly describe the component's logic. Here's the AddPaste component and its template.
<!--- add-paste.component.html -->
<div class="add-paste">
<button (click)="createPaste()"> create Paste </button>
<div *ngIf="showModal" id="source-modal" class="modal fade in">
<div class="modal-dialog" >
<div class="modal-content">
<div class="modal-header"></div>
<div class="modal-body"></div>
<div class="modal-footer"></div>
</div>
</div>
</div>
</div>/* add-paste.component.ts */
export class AddPasteComponent implements OnInit {
showModal: boolean = false;
// Languages imported from Pastebin class
languages: string[] = Languages;
constructor() { }
ngOnInit() { }
//createPaste() gets invoked from the template.
public createPaste():void {
this.showModal = true;
}
}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.
Before we proceed with writing more tests, let's add some code to the Pastebin service.
public addPaste(pastebin: Pastebin): Promise<any> {
return this.http.post(this.pastebinUrl, JSON.stringify(pastebin), {headers: this.headers})
.toPromise()
.then(response =>response.json().data)
.catch(this.handleError);
}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:
We've implemented the first three methods in the list. Let's try writing tests for them. Here's the describe block.
import { TestBed, inject } from '@angular/core/testing';
import { Pastebin, Languages } from './pastebin';
import { PastebinService } from './pastebin.service';
import { AppModule } from './app.module';
import { HttpModule } from '@angular/http';
let testService: PastebinService;
let mockPaste: Pastebin;
let responsePropertyNames, expectedPropertyNames;
describe('PastebinService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [PastebinService],
imports: [HttpModule]
});
//Get the injected service into our tests
testService= TestBed.get(PastebinService);
mockPaste = { id:999, title: "Hello world", language: Languages[2], paste: "console.log('Hello world');"};
});
});We've used TestBed.get(PastebinService) to inject the real service into our tests.
it('#getPastebin should return an array with Pastebin objects',async() => {
testService.getPastebin().then(value => {
//Checking the property names of the returned object and the mockPaste object
responsePropertyNames = Object.getOwnPropertyNames(value[0]);
expectedPropertyNames = Object.getOwnPropertyNames(mockPaste);
expect(responsePropertyNames).toEqual(expectedPropertyNames);
});
});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:
it('#addPaste should return async paste', async() => {
testService.addPaste(mockPaste).then(value => {
expect(value).toEqual(mockPaste);
})
})
Both the tests should pass. Here are the remaining tests.
it('#updatePaste should update', async() => {
//Updating the title of Paste with id 1
mockPaste.id = 1;
mockPaste.title = "New title"
testService.updatePaste(mockPaste).then(value => {
expect(value).toEqual(mockPaste);
})
})
it('#deletePaste should return null', async() => {
testService.deletePaste(mockPaste).then(value => {
expect(value).toEqual(null);
})
})Revise pastebin.service.ts with the code for the updatePaste() and deletePaste() methods.
//update a paste
public updatePaste(pastebin: Pastebin):Promise<any> {
const url = `${this.pastebinUrl}/${pastebin.id}`;
return this.http.put(url, JSON.stringify(pastebin), {headers: this.headers})
.toPromise()
.then(() => pastebin)
.catch(this.handleError);
}
//delete a paste
public deletePaste(pastebin: Pastebin): Promise<void> {
const url = `${this.pastebinUrl}/${pastebin.id}`;
return this.http.delete(url, {headers: this.headers})
.toPromise()
.then(() => null )
.catch(this.handleError);
}
The remaining requirements for the AddPaste component are as follows:
addPaste() method.addPaste operation is successful, the component should emit an event to notify the parent component.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.
describe('AddPasteComponent', () => {
.
.
.
describe("AddPaste Modal", () => {
let inputTitle: HTMLInputElement;
let selectLanguage: HTMLSelectElement;
let textAreaPaste: HTMLTextAreaElement;
let mockPaste: Pastebin;
let spyOnAdd: jasmine.Spy;
let pastebinService: PastebinService;
beforeEach(() => {
component.showModal = true;
fixture.detectChanges();
mockPaste = { id:1, title: "Hello world", language: Languages[2], paste: "console.log('Hello world');"};
//Create a jasmine spy to spy on the addPaste method
spyOnAdd = spyOn(pastebinService,"addPaste").and.returnValue(Promise.resolve(mockPaste));
});
});
});
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.
it("should accept input values", () => {
//Query the input selectors
inputTitle = element.querySelector("input");
selectLanguage = element.querySelector("select");
textAreaPaste = element.querySelector("textarea");
//Set their value
inputTitle.value = mockPaste.title;
selectLanguage.value = mockPaste.language;
textAreaPaste.value = mockPaste.paste;
//Dispatch an event
inputTitle.dispatchEvent(new Event("input"));
selectLanguage.dispatchEvent(new Event("change"));
textAreaPaste.dispatchEvent(new Event("input"));
expect(mockPaste.title).toEqual(component.newPaste.title);
expect(mockPaste.language).toEqual(component.newPaste.language);
expect(mockPaste.paste).toEqual(component.newPaste.paste);
});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:
newPaste: Pastebin = new Pastebin();
And update the template with the following code:
<!--- add-paste.component.html -->
<div class="add-paste">
<button type="button" (click)="createPaste()"> create Paste </button>
<div *ngIf="showModal" id="source-modal" class="modal fade in">
<div class="modal-dialog" >
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">
<input placeholder="Enter the Title" name="title" [(ngModel)] = "newPaste.title" />
</h4>
</div>
<div class="modal-body">
<h5>
<select name="category" [(ngModel)]="newPaste.language" >
<option *ngFor ="let language of languages" value={{language}}> {{language}} </option>
</select>
</h5>
<textarea name="paste" placeholder="Enter the code here" [(ngModel)] = "newPaste.paste"> </textarea>
</div>
<div class="modal-footer">
<button type="button" (click)="onClose()">Close</button>
<button type="button" (click) = "onSave()">Save</button>
</div>
</div>
</div>
</div>
</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.
it("should submit the values", async() => {
component.newPaste = mockPaste;
component.onSave();
fixture.detectChanges();
fixture.whenStable().then( () => {
fixture.detectChanges();
expect(spyOnAdd.calls.any()).toBeTruthy();
});
});
it("should have a onClose method", () => {
component.onClose();
fixture.detectChanges();
expect(component.showModal).toBeFalsy();
})
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.
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { Pastebin, Languages } from '../pastebin';
import { PastebinService } from '../pastebin.service';
@Component({
selector: 'app-add-paste',
templateUrl: './add-paste.component.html',
styleUrls: ['./add-paste.component.css']
})
export class AddPasteComponent implements OnInit {
@Output() addPasteSuccess: EventEmitter<Pastebin> = new EventEmitter<Pastebin>();
showModal: boolean = false;
newPaste: Pastebin = new Pastebin();
languages: string[] = Languages;
constructor(private pasteServ: PastebinService) { }
ngOnInit() { }
//createPaste() gets invoked from the template. This shows the Modal
public createPaste():void {
this.showModal = true;
}
//onSave() pushes the newPaste property into the server
public onSave():void {
this.pasteServ.addPaste(this.newPaste).then( () => {
console.log(this.newPaste);
this.addPasteSuccess.emit(this.newPaste);
this.onClose();
});
}
//Used to close the Modal
public onClose():void {
this.showModal=false;
}
}
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.
describe("AddPaste Modal", () => {
beforeEach(() => {
.
.
//Subscribe to the event emitter first
//If the emitter emits something, responsePaste will be set
component.addPasteSuccess.subscribe((response: Pastebin) => {responsePaste = response},)
});
it("should accept input values", async(() => {
.
.
component.onSave();
fixture.detectChanges();
fixture.whenStable().then( () => {
fixture.detectChanges();
expect(spyOnAdd.calls.any()).toBeTruthy();
expect(responsePaste.title).toEqual(mockPaste.title);
});
}));
});
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:
<app-add-paste (addPasteSuccess)= 'onAddPaste($event)'> </app-add-paste>
And update pastebin.component.ts with the below code.
//This will be invoked when the child emits addPasteSuccess event
public onAddPaste(newPaste: Pastebin) {
this.pastebin.push(newPaste);
}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:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
//Components
import { AppComponent } from './app.component';
import { PastebinComponent } from './pastebin/pastebin.component';
import { AddPasteComponent } from './add-paste/add-paste.component';
//Service for Pastebin
import { PastebinService } from "./pastebin.service";
//Modules used in this tutorial
import { HttpModule } from '@angular/http';
import { FormsModule } from '@angular/forms';
//In memory Web api to simulate an http server
import { InMemoryWebApiModule } from 'angular-in-memory-web-api';
import { InMemoryDataService } from './in-memory-data.service';
@NgModule({
declarations: [
AppComponent,
PastebinComponent,
AddPasteComponent,
],
imports: [
BrowserModule,
HttpModule,
FormsModule,
InMemoryWebApiModule.forRoot(InMemoryDataService),
],
providers: [PastebinService],
bootstrap: [AppComponent]
})
export class AppTestingModule { }Now you can replace:
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ AddPasteComponent ],
imports: [ HttpModule, FormsModule ],
providers: [ PastebinService ],
})
.compileComponents();
}));with:
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [AppTestingModule]
})
.compileComponents();
}));The metadata that define providers and declarations have disappeared and instead, the AppTestingModule gets imported. That's neat! TestBed.configureTestingModule() looks sleeker than before.
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.


The objectives of the ViewPaste component are listed below:
component.editEnabled to true (editEnabled is used to toggle between edit mode and view mode)updatePaste() method.deletePaste() method.Let's get started! The first two specs are identical to the tests that we wrote for the AddPaste component earlier.
it('should show a button with text View Paste', ()=> {
expect(element.textContent).toContain("View Paste");
});
it('should not display the modal until the button is clicked', () => {
expect(element.textContent).not.toContain("source-modal");
});
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.
beforeEach(()=> {
//Set showPasteModal to true to ensure that the modal is visible in further tests
component.showPasteModal = true;
mockPaste = {id:1, title:"New paste", language:Languages[2], paste: "console.log()"};
//Inject PastebinService
pastebinService = fixture.debugElement.injector.get(PastebinService);
//Create spies for deletePaste and updatePaste methods
spyOnDelete = spyOn(pastebinService,'deletePaste').and.returnValue(Promise.resolve(true));
spyOnUpdate = spyOn(pastebinService, 'updatePaste').and.returnValue(Promise.resolve(mockPaste));
//component.paste is an input property
component.paste = mockPaste;
fixture.detectChanges();
})Here are the tests.
it('should display the modal when the view Paste button is clicked',() => {
fixture.detectChanges();
expect(component.showPasteModal).toBeTruthy("Show should be true");
expect(element.innerHTML).toContain("source-modal");
})
it('should display title, language and paste', () => {
expect(element.textContent).toContain(mockPaste.title, "it should contain title");
expect(element.textContent).toContain(mockPaste.language, "it should contain the language");
expect(element.textContent).toContain(mockPaste.paste, "it should contain the paste");
});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.
it('should have all the buttons',() => {
expect(element.innerHTML).toContain('Edit Paste');
expect(element.innerHTML).toContain('Delete');
expect(element.innerHTML).toContain('Close');
});Let's fix up the failing tests before taking up more complex tests.
<!--- view-paste.component.html -->
<div class="view-paste">
<button class="text-primary button-text" (click)="showPaste()"> View Paste </button>
<div *ngIf="showPasteModal" id="source-modal" class="modal fade in">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" (click)='onClose()' aria-hidden="true">×</button>
<h4 class="modal-title">{{paste.title}} </h4>
</div>
<div class="modal-body">
<h5> {{paste.language}} </h5>
<pre><code>{{paste.paste}}</code></pre>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" (click)="onClose()" data-dismiss="modal">Close</button>
<button type="button" *ngIf="!editEnabled" (click) = "onEdit()" class="btn btn-primary">Edit Paste</button>
<button type = "button" (click) = "onDelete()" class="btn btn-danger"> Delete Paste </button>
</div>
</div>
</div>
</div>
</div>
/* view-paste.component.ts */
export class ViewPasteComponent implements OnInit {
@Input() paste: Pastebin;
@Output() updatePasteSuccess: EventEmitter<Pastebin> = new EventEmitter<Pastebin>();
@Output() deletePasteSuccess: EventEmitter<Pastebin> = new EventEmitter<Pastebin>();
showPasteModal:boolean ;
readonly languages = Languages;
constructor(private pasteServ: PastebinService) { }
ngOnInit() {
this.showPasteModal = false;
}
//To make the modal window visible
public showPaste() {
this.showPasteModal = true;
}
//Invoked when edit button is clicked
public onEdit() { }
//invoked when save button is clicked
public onSave() { }
//invoked when close button is clicked
public onClose() {
this.showPasteModal = false;
}
//invoked when Delete button is clicked
public onDelete() { }
}
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.
it('and clicking it should make the paste editable', () => {
component.onEdit();
fixture.detectChanges();
expect(component.editEnabled).toBeTruthy();
//Now it should have a save button
expect(element.innerHTML).toContain('Save');
});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.
<div *ngIf="showPasteModal" id="source-modal" class="modal fade in" >
<div class="modal-dialog">
<div class="modal-content">
<!---View mode -->
<ng-container *ngIf="!editEnabled">
<div class="modal-header">
<button type="button" class="close" (click)='onClose()' data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title"> {{paste.title}} </h4>
</div>
<div class="modal-body">
<h5> {{paste.language}} </h5>
<pre><code>{{paste.paste}}</code>
</pre>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" (click)="onClose()" data-dismiss="modal">Close</button>
<button type="button" (click) = "onEdit()" class="btn btn-primary">Edit Paste</button>
<button type = "button" (click) = "onDelete()" class="btn btn-danger"> Delete Paste </button>
</div>
</ng-container>
<!---Edit enabled mode -->
<ng-container *ngIf="editEnabled">
<div class="modal-header">
<button type="button" class="close" (click)='onClose()' data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title"> <input *ngIf="editEnabled" name="title" [(ngModel)] = "paste.title"> </h4>
</div>
<div class="modal-body">
<h5>
<select name="category" [(ngModel)]="paste.language">
<option *ngFor ="let language of languages" value={{language}}> {{language}} </option>
</select>
</h5>
<textarea name="paste" [(ngModel)] = "paste.paste">{{paste.paste}} </textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" (click)="onClose()" data-dismiss="modal">Close</button>
<button type = "button" *ngIf="editEnabled" (click) = "onSave()" class="btn btn-primary"> Save Paste </button>
<button type = "button" (click) = "onDelete()" class="btn btn-danger"> Delete Paste </button>
</div>
</ng-container>
</div>
</div>
</div>The component should have two Output() event emitters, one for updatePasteSuccess property and the other for deletePasteSuccess. The test below verifies the following:
paste property.updatePasteSuccess emits an event with the updated paste. it('should take input values', fakeAsync(() => {
component.editEnabled= true;
component.updatePasteSuccess.subscribe((res:any) => {response = res},)
fixture.detectChanges();
inputTitle= element.querySelector("input");
inputTitle.value = mockPaste.title;
inputTitle.dispatchEvent(new Event("input"));
expect(mockPaste.title).toEqual(component.paste.title);
component.onSave();
//first round of detectChanges()
fixture.detectChanges();
//the tick() operation. Don't forget to import tick
tick();
//Second round of detectChanges()
fixture.detectChanges();
expect(response.title).toEqual(mockPaste.title);
expect(spyOnUpdate.calls.any()).toBe(true, 'updatePaste() method should be called');
}))
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.
it('should delete the paste', fakeAsync(()=> {
component.deletePasteSuccess.subscribe((res:any) => {response = res},)
component.onDelete();
fixture.detectChanges();
tick();
fixture.detectChanges();
expect(spyOnDelete.calls.any()).toBe(true, "Pastebin deletePaste() method should be called");
expect(response).toBeTruthy();
}))
We're nearly done with the components. Here's the final draft of the ViewPaste component.
/*view-paste.component.ts*/
export class ViewPasteComponent implements OnInit {
@Input() paste: Pastebin;
@Output() updatePasteSuccess: EventEmitter<Pastebin> = new EventEmitter<Pastebin>();
@Output() deletePasteSuccess: EventEmitter<Pastebin> = new EventEmitter<Pastebin>();
showPasteModal:boolean ;
editEnabled: boolean;
readonly languages = Languages;
constructor(private pasteServ: PastebinService) { }
ngOnInit() {
this.showPasteModal = false;
this.editEnabled = false;
}
//To make the modal window visible
public showPaste() {
this.showPasteModal = true;
}
//Invoked when the edit button is clicked
public onEdit() {
this.editEnabled=true;
}
//Invoked when the save button is clicked
public onSave() {
this.pasteServ.updatePaste(this.paste).then( () => {
this.editEnabled= false;
this.updatePasteSuccess.emit(this.paste);
})
}
//Invoked when the close button is clicked
public onClose() {
this.showPasteModal = false;
}
//Invoked when the delete button is clicked
public onDelete() {
this.pasteServ.deletePaste(this.paste).then( () => {
this.deletePasteSuccess.emit(this.paste);
this.onClose();
})
}
}The parent component (pastebin.component.ts) needs to be updated with methods to handle the events emitted by the child component.
/*pastebin.component.ts */
public onUpdatePaste(newPaste: Pastebin) {
this.pastebin.map((paste)=> {
if(paste.id==newPaste.id) {
paste = newPaste;
}
})
}
public onDeletePaste(p: Pastebin) {
this.pastebin= this.pastebin.filter(paste => paste !== p);
}Here's the updated pastebin.component.html:
<tbody>
<tr *ngFor="let paste of pastebin">
<td> {{paste.id}} </td>
<td> {{paste.title}} </td>
<td> {{paste.language}} </td>
<td> <app-view-paste [paste] = paste (updatePasteSuccess)= 'onUpdatePaste($event)' (deletePasteSuccess)= 'onDeletePaste($event)'> </app-view-paste></td>
</tr>
</tbody>
<app-add-paste (addPasteSuccess)= 'onAddPaste($event)'> </app-add-paste> 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).
import { RouterModule, Routes } from '@angular/router';Next, define your routes and pass the route definition to the RouterModule.forRoot method.
const appRoutes :Routes = [
{ path: '', component: PastebinComponent },
{ path: 'about', component: AboutComponent },
{ path: 'contact', component: ContactComponent},
];
imports: [
BrowserModule,
FormsModule,
HttpModule,
InMemoryWebApiModule.forRoot(InMemoryDataService),
RouterModule.forRoot(appRoutes),
],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.
{provide: APP_BASE_HREF, useValue: '/'}Now add the following code to app.component.html.
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<div class="navbar-brand" >{{title}}</div>
</div>
<ul class="nav navbar-nav bigger-text">
<li>
<a routerLink="" routerLinkActive="active">Pastebin Home</a>
</li>
<li>
<a routerLink="/about" routerLinkActive="active">About Pastebin</a>
</li>
<li>
<a routerLink="/contact" routerLinkActive="active"> Contact </a>
</li>
</ul>
</div>
</nav>
<router-outlet></router-outlet>
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.
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [AppTestingModule],
}).compileComponents();
}));
it(`should have as title 'Pastebin Application'`, async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app.title).toEqual('Pastebin Application');
}));
it('should go to url',
fakeAsync((inject([Router, Location], (router: Router, location: Location) => {
let anchorLinks,a1,a2,a3;
let fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
//Create an array of anchor links
anchorLinks= fixture.debugElement.queryAll(By.css('a'));
a1 = anchorLinks[0];
a2 = anchorLinks[1];
a3 = anchorLinks[2];
//Simulate click events on the anchor links
a1.nativeElement.click();
tick();
expect(location.path()).toEqual("");
a2.nativeElement.click();
tick()
expect(location.path()).toEqual("/about");
a3.nativeElement.click();
tick()
expect(location.path()).toEqual("/contact");
}))));
});If everything goes well, you should see something like this.

Add a nice-looking Bootstrap design to your project, and serve your project if you haven't done that already.
ng serve
We wrote a complete application from scratch in a test-driven environment. Isn't that something? In this tutorial, we learned:
async() and fakeAsync() to run asynchronous testsI hope you enjoyed the TDD workflow. Please get in touch via the comments and let us know what you think!
The Best Small Business Web Designs by DesignRush
/
4Create Modern Vue Apps Using Create-Vue and Vite
/
8Pros and Cons of Using WordPress
/
-2How to Fix the “There Has Been a Critical Error in Your Website” Error in WordPress
/
1How To Fix The “There Has Been A Critical Error in Your Website” Error in WordPress
How to Create a Privacy Policy Page in WordPress
/
7WordPress Website Maintenance Guide For Beginners
/
8How Long Does it Take to Learn JavaScript
/
1The Best Way to Deep Copy an Object in JavaScript
/
-3
3
-6Adding and Removing Elements From Arrays in JavaScript
/
-2Create a JavaScript AJAX Post Request: With and Without jQuery
/
85 Real-Life Uses for the JavaScript reduce() Method
/
-8How to Enable or Disable a Button With JavaScript: jQuery vs. Vanilla
/
4How to Enable or Disable a Button With JavaScript: jQuery vs Vanilla
/
-3Confirm Yes or No With JavaScript
/
-5How to Change the URL in JavaScript: Redirecting
/
-215+ Best WordPress Twitter Widgets
/
-227 Best Tab and Accordion Widget Plugins for WordPress (Free & Premium)
/
1121 Best Tab and Accordion Widget Plugins for WordPress (Free & Premium)
/
-1130 HTML Best Practices for Beginners
/
-731 Best WordPress Calendar Plugins and Widgets (With 5 Free Plugins)
/
325 Ridiculously Impressive HTML5 Canvas Experiments
/
-4
1How to Implement Email Verification for New Members
/
3How to Create a Simple Web-Based Chat Application
/
730 Popular WordPress User Interface Elements
/
-3Top 18 Best Practices for Writing Super Readable Code
/
1Best Affiliate WooCommerce Plugins Compared
/
-1218 Best WordPress Star Rating Plugins
/
1410+ Best WordPress Twitter Widgets
/
320+ Best WordPress Booking and Reservation Plugins
/
5Working With Tables in React: Part Two
/
-3Best CSS Animations and Effects on CodeCanyon
/
-1730 CSS Best Practices for Beginners
/
5How to Create a Custom WordPress Plugin From Scratch
/
310 Best Responsive HTML5 Sliders for Images and Text… and 3 Free Options
/
-516 Best Tab and Accordion Widget Plugins for WordPress
/
-518 Best WordPress Membership Plugins and 5 Free Plugins
/
625 Best WooCommerce Plugins for Products, Pricing, Payments and More
/
110 Best WordPress Twitter Widgets
1 /
1212 Best Contact Form PHP Scripts for 2020
/
-420 Popular WordPress User Interface Elements
/
-410 Best WordPress Star Rating Plugins
/
-412 Best CSS Animations on CodeCanyon
/
-112 Best WordPress Booking and Reservation Plugins
/
120 Best WordPress Calendar Plugins and Widgets
/
-312 Elegant CSS Pricing Tables for Your Latest Web Project
/
824 Best WordPress Form Plugins for 2020
/
-214 Best PHP Event Calendar and Booking Scripts
/
-1Getting Started With Django: Newly Updated Course
/
-1Create a Blog for Each Category or Department in Your WooCommerce Store
/
28 Best WordPress Booking and Reservation Plugins
/
-15Best Exit Popups for WordPress Compared
/
19Best Exit Popups for WordPress Compared
/
-411 Best Tab & Accordion WordPress Widgets & Plugins
/
-1212 Best Tab & Accordion WordPress Widgets & Plugins
1 /
2New Course: Practical React Fundamentals
/
2Short Course: Better Angular App Architecture With Modules
/
3Preview Our New Course on Angular Material
/
5Build Your Own CAPTCHA and Contact Form in PHP
/
-1Object-Oriented PHP With Classes and Objects
/
1Best Practices for ARIA Implementation
/
-5Accessible Apps: Barriers to Access and Getting Started With Accessibility
/
-3Dramatically Speed Up Your React Front-End App Using Lazy Loading
/
1715 Best Modern JavaScript Admin Templates for React, Angular, and Vue.js
/
-1615 Best Modern JavaScript Admin Templates for React, Angular and Vue.js
/
319 Best JavaScript Admin Templates for React, Angular, and Vue.js
/
3New Course: Build an App With JavaScript and the MEAN Stack
/
11Hands-on With ARIA: Accessibility Recipes for Web Apps
/
710 Best WordPress Facebook Widgets
13Hands-on With ARIA: Accessibility for eCommerce
/
6New eBooks Available for Subscribers
/
-10Hands-on With ARIA: Homepage Elements and Standard Navigation
/
11
-4Site Accessibility: Getting Started With ARIA
/
5How Secure Are Your JavaScript Open-Source Dependencies?
/
-4New Course: Secure Your WordPress Site With SSL
/
-3Testing Components in React Using Jest and Enzyme
/
-9Testing Components in React Using Jest: The Basics
/
-515 Best PHP Event Calendar and Booking Scripts
/
-3Create Interactive Gradient Animations Using Granim.js
/
10How to Build Complex, Large-Scale Vue.js Apps With Vuex
1 /
-2Examples of Dependency Injection in PHP With Symfony Components
/
-5Set Up Routing in PHP Applications Using the Symfony Routing Component
1 /
8A Beginner’s Guide to Regular Expressions in JavaScript
/
9Introduction to Popmotion: Custom Animation Scrubber
/
-6Introduction to Popmotion: Pointers and Physics
/
-10New Course: Connect to a Database With Laravel’s Eloquent ORM
/
-5How to Create a Custom Settings Panel in WooCommerce
/
-14Building the DOM faster: speculative parsing, async, defer and preload
1 /
320 Useful PHP Scripts Available on CodeCanyon
3 /
51How to Find and Fix Poor Page Load Times With Raygun
/
1Introduction to the Stimulus Framework
/
-11Single-Page React Applications With the React-Router and React-Transition-Group Modules
/
1
712 Best Contact Form PHP Scripts
1 /
-3Getting Started With the Mojs Animation Library: The ShapeSwirl and Stagger Modules
/
1Getting Started With the Mojs Animation Library: The Shape Module
/
-3Getting Started With the Mojs Animation Library: The HTML Module
/
5Project Management Considerations for Your WordPress Project
/
-68 Things That Make Jest the Best React Testing Framework
/
2Creating an Image Editor Using CamanJS: Layers, Blend Modes, and Events
/
-1New Short Course: Code a Front-End App With GraphQL and React
/
2Creating an Image Editor Using CamanJS: Applying Basic Filters
/
-13Creating an Image Editor Using CamanJS: Creating Custom Filters and Blend Modes
/
-1Modern Web Scraping With BeautifulSoup and Selenium
/
1Challenge: Create a To-Do List in React
1 /
-2Deploy PHP Web Applications Using Laravel Forge
/
-3Getting Started With the Mojs Animation Library: The Burst Module
/
6
-910 Things Men Can Do to Support Women in Tech
/
-3A Gentle Introduction to Higher-Order Components in React: Best Practices
/
-5Challenge: Build a React Component
/
-4A Gentle Introduction to HOC in React: Learn by Example
/
2A Gentle Introduction to Higher-Order Components in React
/
-6Creating Pretty Popup Messages Using SweetAlert2
/
5Creating Stylish and Responsive Progress Bars Using ProgressBar.js
/
1818 Best Contact Form PHP Scripts for 2022
/
-3How to Make a Real-Time Sports Application Using Node.js
/
-2Creating a Blogging App Using Angular & MongoDB: Delete Post
/
-15Creating a Blogging App Using Angular & MongoDB: Show Post
/
10Creating a Blogging App Using Angular & MongoDB: Home
/
8
4Creating a Blogging App Using Angular & MongoDB: Login
/
11Creating Your First Angular App: Implement Routing
/
13Persisted WordPress Admin Notices: Part 4
/
-3Creating Your First Angular App: Components, Part 2
/
4Persisted WordPress Admin Notices: Part 3
/
4
8Persisted WordPress Admin Notices: Part 2
/
-2Create Your First Angular App: Storing and Accessing Data
/
5Persisted WordPress Admin Notices: Part 1
/
-4Error and Performance Monitoring for Web & Mobile Apps Using Raygun
/
5Using Luxon for Date and Time in JavaScript
7 /
-6How to Create an Audio Oscillator With the Web Audio API
/
-5How to Cache Using Redis in Django Applications
/
120 Essential WordPress Utilities to Manage Your Site
/
-6Introduction to API Calls With React and Axios
/
16Beginner’s Guide to Angular 4: HTTP
/
12Rapid Web Deployment for Laravel With GitHub, Linode, and RunCloud.io
/
10Beginners Guide to Angular 4: Routing
/
-9Beginner’s Guide to Angular 4: Components
/
3Creating a Drop-Down Menu for Mobile Pages
/
6Introduction to Forms in Angular 4: Writing Custom Form Validators
/
5Getting Started With Redux: Connecting Redux With React
/
15Getting Started With Redux: Learn by Example
/
14Getting Started With Redux: Why Redux?
/
11Understanding Recursion With JavaScript
/
-1How to Auto Update WordPress Salts
/
-3How to Download Files in Python
/
-3
-21Eloquent Mutators and Accessors in Laravel
1 /
15
-11
1210 Best HTML5 Sliders for Images and Text
/
8Site Authentication in Node.js: User Signup
/
-2Creating a Task Manager App Using Ionic: Part 2
/
3Creating a Task Manager App Using Ionic: Part 1
/
1Introduction to Forms in Angular 4: Reactive Forms
/
2
4Introduction to Forms in Angular 4: Template-Driven Forms
/
424 Essential WordPress Utilities to Manage Your Site
/
-325 Essential WordPress Utilities to Manage Your Site
/
-10Get Rid of Bugs Quickly Using BugReplay
1 /
-17Manipulating HTML5 Canvas Using Konva: Part 1, Getting Started
/
610 Must-See Easy Digital Downloads Extensions for Your WordPress Site
/
-322 Best WordPress Booking and Reservation Plugins
/
-4Understanding ExpressJS Routing
/
-615 Best WordPress Star Rating Plugins
/
11Creating Your First Angular App: Basics
/
-1Inheritance and Extending Objects With JavaScript
/
-9Introduction to the CSS Grid Layout With Examples
1 /
4
6Performant Animations Using KUTE.js: Part 5, Easing Functions and Attributes
/
-9Performant Animations Using KUTE.js: Part 4, Animating Text
/
-12Performant Animations Using KUTE.js: Part 3, Animating SVG
/
-8New Course: Code a Quiz App With Vue.js
/
-2Performant Animations Using KUTE.js: Part 2, Animating CSS Properties
/
2
9Performant Animations Using KUTE.js: Part 1, Getting Started
/
110 Best Responsive HTML5 Sliders for Images and Text (Plus 3 Free Options)
/
-3Single-Page Applications With ngRoute and ngAnimate in AngularJS
/
-13Deferring Tasks in Laravel Using Queues
/
-4
2Site Authentication in Node.js: User Signup and Login
/
11Working With Tables in React, Part Two
/
-17Working With Tables in React, Part One
/
3How to Set Up a Scalable, E-Commerce-Ready WordPress Site Using ClusterCS
/
-4New Course on WordPress Conditional Tags
/
3
-11Building With Vue.js 2 and Firebase
6 /
13
-8Best Unique Bootstrap JavaScript Plugins
/
-6
-2Essential JavaScript Libraries and Frameworks You Should Know About
/
6
2Vue.js Crash Course: Create a Simple Blog Using Vue.js
/
-13Build a React App With a Laravel RESTful Back End: Part 1, Laravel 5.5 API
/
3API Authentication With Node.js
/
-4Beginner’s Guide to Angular: HTTP
/
7Beginner’s Guide to Angular: Routing
/
-3Beginners Guide to Angular: Routing
/
-3Beginner’s Guide to Angular: Services
/
2Beginner’s Guide to Angular: Components
/
1How to Create a Custom Authentication Guard in Laravel
/
6Learn Computer Science With JavaScript: Part 3, Loops
/
-4Build Web Applications Using Node.js
/
1Learn Computer Science With JavaScript: Part 4, Functions
/
4Learn Computer Science With JavaScript: Part 2, Conditionals
/
12Create Interactive Charts Using Plotly.js, Part 5: Pie and Gauge Charts
/
-8Create Interactive Charts Using Plotly.js, Part 4: Bubble and Dot Charts
/
16Create Interactive Charts Using Plotly.js, Part 3: Bar Charts
/
-11Awesome JavaScript Libraries and Frameworks You Should Know About
/
-5Create Interactive Charts Using Plotly.js, Part 2: Line Charts
/
-8Bulk Import a CSV File Into MongoDB Using Mongoose With Node.js
/
-6Build a To-Do API With Node, Express, and MongoDB
/
-8Getting Started With End-to-End Testing in Angular Using Protractor
/
10TypeScript for Beginners, Part 4: Classes
/
-17Object-Oriented Programming With JavaScript
/
410 Best Affiliate WooCommerce Plugins Compared
/
5Stateful vs. Stateless Functional Components in React
/
8Make Your JavaScript Code Robust With Flow
/
-3Build a To-Do API With Node and Restify
/
7Testing Components in Angular Using Jasmine: Part 2, Services
/
2Testing Components in Angular Using Jasmine: Part 1
/
-1Creating a Blogging App Using React, Part 6: Tags
/
-9React Crash Course for Beginners, Part 3
/
3React Crash Course for Beginners, Part 2
/
6React Crash Course for Beginners, Part 1
/
2Set Up a React Environment, Part 4
1 /
9Set Up a React Environment, Part 3
/
-9New Course: Get Started With Phoenix
/
-9Set Up a React Environment, Part 2
/
1Command Line Basics and Useful Tricks With the Terminal
/
8How to Create a Real-Time Feed Using Phoenix and React
/
-3Build a React App With a Laravel Back End: Part 2, React
/
3Build a React App With a Laravel RESTful Back End: Part 1, Laravel 9 API
/
-5Creating a Blogging App Using React, Part 5: Profile Page
/
-3Pagination in CodeIgniter: The Complete Guide
/
22JavaScript-Based Animations Using Anime.js, Part 4: Callbacks, Easings, and SVG
JavaScript-Based Animations Using Anime.js, Part 3: Values, Timeline, and Playback
Learn to Code With JavaScript: Part 1, The Basics
/
510 Elegant CSS Pricing Tables for Your Latest Web Project
/
-8Getting Started With the Flux Architecture in React
/
-2Getting Started With Matter.js: The Composites and Composite Modules
/
2Getting Started With Matter.js: The Engine and World Modules
/
1410 More Popular HTML5 Projects for You to Use and Study
/
-22Understand the Basics of Laravel Middleware
/
-2Iterating Fast With Django & Heroku
/
9Creating a Blogging App Using React, Part 4: Update & Delete Posts
/
4Creating a jQuery Plugin for Long Shadow Design
/
-12How to Register & Use Laravel Service Providers
2 /
-13Unit Testing in React: Shallow vs. Static Testing
/
4Creating a Blogging App Using React, Part 3: Add & Display Post
/
14Creating a Blogging App Using React, Part 2: User Sign-Up
20 /
-5Creating a Blogging App Using React, Part 1: User Sign-In
/
69 More Popular HTML5 Projects for You to Use and Study
/
16Creating a Grocery List Manager Using Angular, Part 2: Managing Items
/
89 Elegant CSS Pricing Tables for Your Latest Web Project
/
-1Dynamic Page Templates in WordPress, Part 3
/
-3Angular vs. React: 7 Key Features Compared
/
6Creating a Grocery List Manager Using Angular, Part 1: Add & Display Items
/
2New eBooks Available for Subscribers in June 2017
/
6Create Interactive Charts Using Plotly.js, Part 1: Getting Started
/
10The 5 Best IDEs for WordPress Development (And Why)
/
-133 Popular WordPress User Interface Elements
/
2New Course: How to Hack Your Own App
/
-11How to Install Yii on Windows or a Mac
/
4What Is a JavaScript Operator?
/
-6How to Register and Use Laravel Service Providers
/
9
waly Good blog post. I absolutely love this…