Unit tests for service in an Angular app using the Jasmine framework and karma

In this article, we discuss how to write a unit test for the service for the angular application. In the last article, we discuss how to write unit tests for the component.
Let’s start the new application for the write unit test for the service.
Setting Up an Angular App
First, we need to create a new project to start.


ng new unittest-angular

The above command creating the application will take a few minutes to download all of the necessary dependencies. after creating the application you need browse the created application folder example ” cd unittest-angular”. Open that project in the visual studio code just write the “code .”
Let’s create a Service to write unit tests to generate service run below command.


ng generate s shared/post

After running the above command, we have got the following files:


app/shared/post.service.spec.ts //testing file

app/shared/post.service.ts



In post-service, we use free REST API from JSONPlaceholder, thanks to them for providing such a beautiful collection of REST APIs.
Let’s import the service in “app.module.ts” also need to HttpClientModule to import for post service.


import { HttpClientModule } from '@angular/common/http';
import { PostService } from './shared/post.service';
@NgModule({
  declarations: [...],
  imports: [
......,
    HttpClientModule
  ],
  providers: [PostService],
  bootstrap: [...]
})

export class AppModule { }

Let’s fetch data from the server “post.service.ts”, In these service API we created the function getPosts() method and returns post list Observable and we subscribe to get the data. Need to write the below code in your service file.


import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';

export interface Post {
  userId: number;
  id: number;
  title: string;
  body: string;
}

@Injectable({
  providedIn: 'root'
})

export class PostService {
  REST_API: string = 'https://jsonplaceholder.typicode.com/posts';

  constructor(private http: HttpClient) { }

  getPosts(): Observable {
    return this.http.get(`${this.REST_API}`)
  }
}

Let’s open the testing file “post.service.spec.ts”. In that we use the HttpTestingController service are beneficial in mocking the HTTP requests.Display in below code how to write the unit test for service


import { async, inject  , TestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { PostService } from './post.service';

describe('PostService', () => {
  let service: PostService;
  let httpMock: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule,
      ],
      providers: [
        PostService
      ],
    });
    service = TestBed.get(PostService);
    httpMock = TestBed.get(HttpTestingController);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });

  it(`should fetch posts as an Observable`, async(inject([HttpTestingController, PostService],
    (httpClient: HttpTestingController, postService: PostService) => {

      const postItem = [
        {
          "userId": 1,
          "id": 1,
          "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
          "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
        },
        {
          "userId": 1,
          "id": 2,
          "title": "qui est esse",
          "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
        },
        {
          "userId": 1,
          "id": 3,
          "title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
          "body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
        }
      ];

      postService.getPosts()
        .subscribe((posts: any) => {
          expect(posts.length).toBe(3);
        });

      let req = httpMock.expectOne('https://jsonplaceholder.typicode.com/posts');
      expect(req.request.method).toBe("GET");

      console.log(req);
      req.flush(postItem);
      httpMock.verify();

    })));

});



HttpClientTestingModule and HttpTestingController and inject inside the TestBed
import { HttpClientTestingModule, HttpTestingController } from ‘@angular/common/http/testing’;
We need to run the below command to testing an Angular service.

 ng test

You can see the chrome browser option with the debug. display in the below video.

Download the Code from the below link.
Download Code

Spread the love
  •  
  •  
  •  
  •  
  • 1
  • 2
  •  
  •