Angular2服务的Karma / Jasmine测试用例

时间:2018-07-15 08:23:19

标签: javascript angular unit-testing typescript karma-jasmine

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;
}

我对Angular以及Karma / Jasmine还是陌生的。

我创建了一个简单的登录组件和登录服务。为此目的编写测试用例时,我遵循了一些文档和angular.io网站。我已经在文档的帮助下为登录组件编写了一些测试用例,但是我没有设法为登录服务编写测试用例。

如何为登录服务编写测试用例?

这是我的 login.service.ts 文件

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)
      )
  }

}

1 个答案:

答案 0 :(得分:1)

对此进行了思考,这就是我将如何测试您的服务的方法。我无法提供上次测试的确切详细信息,因为我没有有关您的ApiConnectorService或LoginResponse对象的详细信息,但我确定您会明白的。

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);
  }));
});