We have just seen how to test a service in Angular application. Now, let's discuss testing an Angular component. Perform the following steps to create AppComponent for the application:
- Create a file named app.component.ts.
- Import modules such as Component, TodoService, and Todo that are necessary for the AppComponent, as shown:
import { Component } from '@angular/core'; import { Todo } from './todo'; import { TodoService } from './todo.service';
- Define the AppComponent class, as demonstrated:
export class AppComponent {}
- Decorate the AppComponent class by the @Component attribute with the selector, providers and templateUrl metadata:
@Component({ selector: 'my-app', templateUrl: './app.component.html', providers: [TodoService] }) export class AppComponent { }
- Declare the todos, todoService, newTodoText, and title variables:
todos: Array<Todo>; todoService: TodoService; newTodoText = ''; title = 'Test My Todo App';
- Define the constructor with todoService injected, as follows. Note that the constructor updates the todos with the todos returned from todoService:
constructor(todoService: TodoService)
{ this.todoService = todoService; this.todos = todoService.todos; }
- Introduce the addTodo() function that calls the add() method of TodoService by passing the description of new todo, as illustrated:
addTodo()
{ if (this.newTodoText.trim().length)
{ this.todoService.add(this.newTodoText); this.newTodoText = ''; } }
- Introduce the remove() function that calls the remove() method of TodoService by passing a todo object to remove, as shown:
remove(todo: Todo)
{ this.todoService.remove(todo); }
- Introduce the removeCompleted() function that calls the removeCompleted() method of TodoService to remove all the completed todo items:
removeCompleted()
{ this.todoService.removeCompleted(); }
- Introduce the toggleCompletion() function that calls the toggleCompletion() method of TodoService that toggles the value of the completed status of a todo item:
toggleCompletion(todo: Todo)
{ todo.completed = !todo.completed; }
The complete code snippet of AppComponent is this:
import { Component } from '@angular/core'; import { Todo } from './todo'; import { TodoService } from './todo.service'; @Component({ selector: 'my-app', templateUrl: './app.component.html', providers: [TodoService] }) export class AppComponent { todos: Array<Todo>; todoService: TodoService; newTodoText = ''; title = 'Test My Todo App'; constructor(todoService: TodoService) { this.todoService = todoService; this.todos = todoService.todos; } removeCompleted() { this.todoService.removeCompleted(); } toggleCompletion(todo: Todo) { this.todoService.toggleCompletion(todo); } remove(todo: Todo) { this.todoService.remove(todo); } addTodo() { if (this.newTodoText.trim().length) { this.todoService.add(this.newTodoText); this.newTodoText = ''; } } }
We have the AppComponent in place now. The template for this AppComponent is defined in a template file, app.component.html.