Show List

Service Testing

Below is a service to return list of products. We are going to write unit tests for this service.

product.service.ts
import { Injectable } from '@angular/core';
import { Product } from './product';

@Injectable({
  providedIn: 'root'
})
export class ProductService {

  constructor() { }
  public getProducts: Product[] = [
    new Product(1, 'ProductA', 10),
    new Product(2, 'ProductB', 100),
    new Product(3, 'ProductC', 500),
    new Product(4, 'ProductC', 900),
    new Product(5, 'ProductC', 1200),
    new Product(6, 'ProductC', 1500),
    new Product(7, 'ProductC', 5000),
  ]
}


With Product class defined as below
export class Product {
    constructor(productID: number, name: string, price: number) {
      this.productID = productID;
      this.name = name;
      this.price = price;
    }
 
    productID: number;
    name: string;
    price: number;
 
  }

Below is a sample suite to test the product service.

product.service.spec.ts
import { TestBed } from '@angular/core/testing';
import { Product } from './product';
import { ProductService } from './product.service';

describe('ProductService Test Suite', () => {
  let service: ProductService;

  beforeEach(() => {
    TestBed.configureTestingModule({});
    service = TestBed.inject(ProductService);
  });

  it('should return an Array', () => {
    expect(service.getProducts).toBeInstanceOf(Array);
  });

  it('Array length should be > 0', () => {
    expect(service.getProducts.length).toBeGreaterThan(0);
  });

  it('Array element should be instance of Product class', () => {
    expect(service.getProducts[0]).toBeInstanceOf(Product);
  });
});

Here we are using Angular TestBed to get the instance of ProductService. Angular provides dependency injection to create the service. So when a service has a dependency on another service, Angular creates the dependent service and injects it. 

In our example, ProductService does not have a dependent service but it is good idea to use TestBed as a practice. Test bed is helpful to :
  • Test the interaction of component with HTML template
  • Test with change detection
  • Test Dependency Injection
  • Test using NgModule
Source code
https://github.com/it-code-lab/angular-application

    Leave a Comment


  • captcha text