Angular 4如何在Observable中进行单元测试订阅

时间:2018-06-19 19:51:09

标签: angular angular4-httpclient

我正在尝试测试用于Angular CLI项目的服务。我已经测试了其中的所有功能,但那些具有订阅功能的功能却使我麻烦。请帮忙。我应该如何测试此功能?

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { HttpClient } from '@angular/common/http';
import * as moment from 'moment';

@Injectable()
export class BuildService {

  constructor(private httpClient: HttpClient) { }

  index() {
    let o = new Observable( observer => {
      this.httpClient.get("/api/build").subscribe(builds => {
        this.setInitialResultsValue(builds);
        observer.next(builds);
        observer.complete();
      });
    });
    return o;
  }
}

当前尝试进行测试:

import { TestBed, inject } from '@angular/core/testing';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { MockBackend } from '@angular/http/testing';
import { XHRBackend, ResponseOptions } from '@angular/http';
import { BuildService } from './build.service';
import * as moment from 'moment';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';

describe('BuildService (MockBackend)', () => {
  let mock, service;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [ BuildService, {
        provide: XHRBackend, useClass: MockBackend
      }],
      imports: [ HttpClientTestingModule ]
    });
  });

  beforeEach(inject([BuildService, XHRBackend], (s, b) => {
    service = s;
    mock = b;
  }));

  it('should subscribe all values correctly', () => {
    let o = service.index();
    let response: any;
    spyOn(service, "index").and.returnValue(Observable.of(response));
    expect(response).toEqual(o);
  });

});

我收到的当前错误消息:

Expected undefined to equal Observable({ _isScalar: false, _subscribe: Function }).

任何帮助将不胜感激,谢谢

感谢Buczkowski和JB Nizet的最新答案

功能:

index() {
    return this.httpClient.get('/api/build').do(builds => this.setInitialResultsValue(builds));
  }

测试:

it('should subscribe all builds correctly', inject([HttpClient], (httpClient: HttpClient) => {
  spyOn(httpClient, "get").and.returnValue(Observable.of(builds));
  service.index().subscribe(response => {
    expect(response).toEqual(builds);
  });
}));

1 个答案:

答案 0 :(得分:4)

尝试一下:

['1st', '2nd', '3rd']

我们不是在监视要测试的方法,而是在监视HttpClient it('description', inject([HttpClient], (httpClient: HttpClient) => { spyOn(httpClient.get).and.returnValue(Observable.of([])); // Some array with builds objects? component.index().subscribe(builds => { expect(builds).toEqual([]); // Your expected builds array previously set in spy }); }); 方法。