0

我有一个名为 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”?我正在使用 jasmine 编写单元测试。

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

提前致谢。

4

1 回答 1

0

您可以在测试具有 a作为依赖项的服务时使用HttpClientTestingModuleand 。您可以在测试 Http 请求部分的官方 angular 文档中找到大神解释。HttpTestingControllerHttpClient

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);
    });
  });
});
于 2018-06-20T04:21:29.983 回答