如何使用jasmine在单元测试角度类中为类构造函数注入http?

时间:2017-11-13 21:28:56

标签: angular unit-testing jasmine angular-unit-test

我有一个名为logPublisher的抽象类。以下是代码:

  export abstract class LogPublisher {
    location: string;

    abstract log(record: LogEntry): Observable<boolean>;
    abstract clear(): Observable<boolean>;
}

类LogWebApi扩展了LogPublisher:

export class LogWebApi extends LogPublisher {

    constructor(private http: Http) {
        super();
        this.location = "http://localhost:59143/api/v1/Log";
    }

    log(record: LogEntry): Observable<boolean> {
        let ret: boolean = false;
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });

        let values: LogEntry[];

        return this.http.post(this.location, record, options)
            .map(response => response.json)
            .catch(this.handleErrors);
    }

    clear(): Observable<boolean> {
        //TODO: call webapi to clear all log entries
        return Observable.of(true);
    }

    private handleErrors(error: any): Observable<any> {
      console.log("Error while logging: " + error);
      return Observable.throw(error);
    }
}

现在我在LogWebApi类的单元测试中,我将如何注入“http”? 我正在使用茉莉花编写单元测试。

任何代码段都会有所帮助。

提前致谢。

1 个答案:

答案 0 :(得分:0)

在测试具有HttpClientTestingModule作为依赖项的服务时,可以使用HttpTestingControllerHttpClient。您可以在Testing Http Request部分的官方角度文档中找到有关上帝的解释。

import {TestBed} from '@angular/core/testing';
import {HttpClientTestingModule, HttpTestingController} from '@angular/common/http/testing';
import { LogWebApi } from 'path-to-your-service';

describe('ChannelRecsService tests', () => {
  let service: LogWebApi;
  let httpMock: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [LogWebApi]
    });

    service = TestBed.get(LogWebApi);
    httpMock = TestBed.get(HttpTestingController);
  });

  afterEach(() => {
    httpMock.verify();
  });

  describe('#log tests', () => {
    it('Shpould make a http POST request to the given url', () => {
      const logrecord = {put the object you want to pass in here};
      const mockResponse = //create a mock response object;
      service.log(logrecord).subscribe((res) => {
        expect(res).toEqual(mockResponse);
      });

      const req = httpMock.expectOne('http://localhost:59143/api/v1/Log');
      expect(req.request.method).toBe('POST');
      req.flush(mockResponse);
    });
  });
});