This is a comprehensive tutorial designed to guide you through the process of testing services in Angular. Services in Angular are key elements that help us maintain clean and DRY code. They provide a way to keep data across the life of an application, i.e., data is persistent and consistent.
By the end of this tutorial, you will:
Prerequisites:
Testing is an integral part of software development. Angular uses Jasmine, a behavior-driven development framework for testing JavaScript code, and Karma, a spectacular test runner.
2.1 Creating a Service
Use the Angular CLI command to generate a service.
ng generate service MyService
2.2 Testing a Service
To test a service, you create a spec file which contains the test cases. Angular CLI automatically creates this file when you generate a service. The file will be named my-service.service.spec.ts
.
Let's start with a simple service.
my-service.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class MyServiceService {
constructor() { }
addNumbers(num1: number, num2: number): number {
return num1 + num2;
}
}
In this service, we have a method addNumbers()
that takes two numbers and returns their sum. Now, let's create a test for this service.
my-service.service.spec.ts
import { TestBed } from '@angular/core/testing';
import { MyServiceService } from './my-service.service';
describe('MyServiceService', () => {
let service: MyServiceService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(MyServiceService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('should return the sum of two numbers', () => {
const result = service.addNumbers(1, 2);
expect(result).toBe(3);
});
});
In the test file, describe
functions are used for grouping tests and it
functions are used for individual test cases. In our example, the first test case checks if the service is created and the second test case checks if the addNumbers()
function gives the correct output.
To run the tests, use the command ng test
.
We've covered the basics of creating and testing Angular services. You've learned how to generate services, write tests, and use Jasmine and Karma for executing the tests.
To further enhance your skills, explore asynchronous testing and mocking dependencies in Angular.
Exercise 1: Create a service 'MathService' with a method subNumbers()
that takes two numbers and returns their difference. Write a test for this function.
Exercise 2: Modify the 'MathService' to include a mulNumbers()
function that multiplies two numbers. Write tests to verify your function's behavior.
Exercise 3: Create a 'StringService' with a method concatStrings()
that concatenates two strings. Write tests for this function.
As you work through these exercises, remember the importance of thorough testing in maintaining robust, reliable code. Happy coding!