使用takeUntil break单元测试取消订阅Angular Observable

时间:2017-06-19 19:06:56

标签: angular karma-jasmine

我正在尝试使用takeUntil()在我的Angular应用程序中正确取消订阅Observable,但它似乎打破了测试。

Chrome 58.0.3029 (Mac OS X 10.12.5) AppComponent should render title in a h1 tag FAILED
Failed: this.appService.getGuides(...).takeUntil is not a function
TypeError: this.appService.getGuides(...).takeUntil is not a function
    at AppComponent.Array.concat.AppComponent.ngOnInit (webpack:///src/app/app.component.ts:28:7 <- src/test.ts:53764:14)
    at checkAndUpdateDirectiveInline (webpack:///~/@angular/core/@angular/core.es5.js:10923:0 <- src/test.ts:11228:19)

这是代码:

  export class AppComponent implements OnDestroy, OnInit {
  private ngUnsubscribe: Subject<void> = new Subject<void>();

  title = 'app works!';
  guides: Guide[];

  constructor(private appService: AppService) {
  }

  ngOnInit(): void {
    this.appService.getGuides()
      .takeUntil(this.ngUnsubscribe)
      .subscribe(
        guides => this.setGuides(guides),
        error => this.onError(error)
      );
  }

  ngOnDestroy(): void {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }

这是服务实现:

@Injectable()
export class AppService {

  constructor(private http: Http) { }

  getGuides(): Observable<Guide[]> {
    return this.http.get(environment.apiUrl + '/guides')
      .map(this.extractData);
  }

  private extractData(res) {
    if (res.status < 200 || res.status >= 300) {
      throw new Error('Bad response status: ' + res.status);
    }
    return res.json();
  }
}

这是失败的测试:

class MockAppService extends AbstractMockObservableService {
  getGuides() {
    return this;
  }
}
describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [AppComponent]
    });

    TestBed.overrideComponent(AppComponent, {
      set: {
        providers: [
          { provide: AppService, useClass: MockAppService }
        ]
      }
    });
  }));
  it('should render title in a h1 tag', async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    const compiled = fixture.debugElement.nativeElement;
    expect(compiled.querySelector('h1').textContent).toContain('app works!');
  }));

3 个答案:

答案 0 :(得分:1)

试试这个:

class MockAppService extends AbstractMockObservableService {
  getGuides() {
    return Observable.of([]);
  }
}

我自己就是这个问题。就我而言,我正在使用这样的间谍:

spy = spyOn(someService, 'get')
    .and.returnValue([]);

我需要做的是:

spy = spyOn(someService, 'get')
    .and.returnValue(Observable.of([]));

模拟实现没有takeUntil方法,因为它没有返回可观察的(与实际实现不同)。

答案 1 :(得分:0)

getGuides()中的

MockAppService不应该返回this,而应该是可观察的。{/ p>

答案 2 :(得分:-1)

您需要在规范文件中导入它:

import 'rxjs/add/operator/takeUntil';