Ad

Karma/Jasmine Test Cases For Angular2 Service

api-connector.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { ErrorObservable } from 'rxjs/observable/ErrorObservable';
import { Observable } from 'rxjs/Observable';
import {environment} from '../../../environments/environment';
import { catchError } from 'rxjs/operators/catchError';


@Injectable()
export class ApiConnectorService {

  constructor(private http: HttpClient) { }

 private  getQueryString(params): string {
    const queryString = Object.keys(params).map(key => key + '=' + params[key]).join('&');
    console.log('QUERY STRING', queryString);
    return ('?' + queryString);
  }

  private formatErrors(error: any) {
    return new ErrorObservable(error.error);
  }

  get(path: string, payload: Object = {}): Observable<any> {

    return this.http.get(`${environment.base_url}${path}` + this.getQueryString(payload))
      .pipe(catchError(this.formatErrors));
  }

  put(path: string, body: Object = {}): Observable<any> {
    return this.http.put(
      `${environment.base_url}${path}`,
      body
    ).pipe(catchError(this.formatErrors));
  }

  post(path: string, body: Object): Observable<any> {
    // console.log('API SERVICE BODY', body)
    return this.http.post(
      `${environment.base_url}${path}`,
      body
    ).pipe(catchError(this.formatErrors));
  }

  delete(path): Observable<any> {
    return this.http.delete(
      `${environment.base_url}${path}`
    ).pipe(catchError(this.formatErrors));
  }

}

login.contract.ts

export interface LoginRequest {
    env?: string;
    userid: string;
    password: string;
    newpassword: string;
}

export interface LoginResponse {
    token: string;
}

I am pretty new to Angular and as well Karma/Jasmine also.

I have created a simple login component and login service. While writing test cases for that purpose, I followed some docs and angular.io site. I have written some of the test cases for login component with help of docs, but I didn't manage to write test cases for login service.

How to write test cases for login service?

Here is my login.service.ts file

import { Injectable } from '@angular/core';
import { ApiConnectorService } from '../api-handlers/api-connector.service';
import { LoginRequest, LoginResponse } from './login.contract';
import { Observable } from 'rxjs/Observable';
import { map } from 'rxjs/operators';

@Injectable()
export class LoginService {

  constructor(private apiConnector: ApiConnectorService) { }

  login(payload: LoginRequest): Observable<LoginResponse> {
    console.log('Login payload ', payload);
    return this.apiConnector.post('/api/login', payload)
      .pipe(
        map((data: LoginResponse) => data)
      )
  }

}
Ad

Answer

Having had a think about it this is how I would approach testing your service. I can't do the exact details for the last test as I don't have details on your ApiConnectorService or LoginResponse object but I'm sure you'll get the idea.

import { TestBed, inject } from '@angular/core/testing';

import { LoginService } from './login.service';
import { LoginResponse, LoginRequest } from './login.contract';
import { Observable, of } from 'rxjs';
import { ApiConnectorService } from './api-connector.service';

class ApiConnectorServiceStub {

  constructor() { }

  post(address: string, payload: LoginRequest): Observable<LoginResponse> {
    return  of(new LoginResponse());
  }
}

describe('LoginService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [LoginService,
        {provide: ApiConnectorService, useClass: ApiConnectorServiceStub }]
    });
  });

  it('should be created', inject([LoginService], (service: LoginService) => {
    expect(service).toBeTruthy();
  }));

  it('should call post on apiConnectorService with right parameters when login is called',
                                          inject([LoginService], (service: LoginService) => {
    const apiConnectorStub = TestBed.get(ApiConnectorService);
    const spy = spyOn(apiConnectorStub, 'post').and.returnValue(of(new LoginResponse()));

    const loginRequest = of(new LoginRequest());
    service.login(loginRequest);

    expect(spy).toHaveBeenCalledWith('/api/login', loginRequest);
  }));

  it('should map data correctly when login is called', inject([LoginService], (service: LoginService) => {
    const apiConnectorStub = TestBed.get(ApiConnectorService);

    // Set you apiConnector output data here
    const apiData = of('Test Data');
    const spy = spyOn(apiConnectorStub, 'post').and.returnValue(apiData);

    const result = service.login(of(new LoginRequest()));
    // Set your expected LoginResponse here.
    const expextedResult = of(new LoginResponse());

    expect(result).toEqual(expextedResult);
  }));
});
Ad
source: stackoverflow.com
Ad