javascript - Angular2 服务的 Karma/Jasmine 测试用例

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

}

最佳答案

考虑过这就是我测试您的服务的方式。我无法提供上次测试的确切细节,因为我没有关于您的 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);
  }));
});

关于javascript - Angular2 服务的 Karma/Jasmine 测试用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51346614/

相关文章:

javascript - jQuery,在脚本完成之前禁止加载页面

Angular 2 : get FormGroup by FormControl

c# - 测试用于 ASP 成员资格的自定义用户配置文件

javascript - 从 DOM 中分离对象内容,添加其他内容,然后 append 到 DOM

javascript - 防止在 HTML 中选择

javascript - 如何让输入字段在提交后添加文本

javascript - 了解angular2中的依赖注入(inject)

Angular 2 : Is one time binding for *ngIf available?

java - 如何为不同的测试上下文重用 JUnit 测试方法?

java - Spock 如何为 Java 类模拟同一个类的方法