2017-08-25 114 views
0

我有一個監視服務中的變量(因此是主題)的組件之一。 (我在這裏得到了這個實現的想法:updating variable changes in components from a service with angular2.但是,現在我在組件中的所有測試都失敗了,因爲我需要以某種方式嘲笑這個,但是我不知道如何以及我找不到任何答案,那是我的代碼:Angular2單元測試 - 測試主題(觀察服務變量)

組件在那裏我觀察的變量的構造函數中的變化:

constructor(private updateService: UpdateService) { 

    // check if intents are updated in the updateService through upload component, if yes update training status 
    this.intentsSubscription = updateService.intentsChange.subscribe((value) => this.initTrainingStatus()); 
    } 

服務所在的可變變化是觸發:

public intentsChange: Subject<object> = new Subject<object>(); 
    ..... 

    public updateIntents(appId: number) { 
     this.requestsService.getAllIntents(appId) 
      .subscribe(intents => { 
      this.setIntents(intents); 
      this.intentsChange.next(intents); 
      }); 
     } 
該組件個

測試正在失敗,因爲:

TypeError: updateService.intentsChange.subscribe is not a function

describe('TrainButtonComponent',() => { 
    let component: TrainButtonComponent; 
    let fixture: ComponentFixture<TrainButtonComponent>; 

    let mockUpdateService; 
    let intentsChange: Subject<object> = new Subject<object>(); 


    beforeEach(async(() => { 
     intentsChange() { 
     return Subject.of({}); 
     } 
    }; 
    TestBed.configureTestingModule({ 
     imports: [ ], 
     declarations: [ TrainButtonComponent ], 
     providers: [ 
     { provide: UpdateService, useValue: mockUpdateService } 
     ] 
    }) 
    .compileComponents(); 
    })); 

    beforeEach(() => { 
    fixture = TestBed.createComponent(TrainButtonComponent); 
    component = fixture.componentInstance; 
    mockUpdateService = fixture.debugElement.injector.get(UpdateService); 
    fixture.detectChanges(); 
    }); 

    it('should be created',() => { 
    expect(component).toBeTruthy(); 
    }); 

}); 

有誰知道如何解決這個錯誤,所以我的測試實際上通過再次運行?

回答

1

intentsChange你在beforeEach中聲明的什麼都不做。

所有你需要的是在每個前正確地嘲笑updateService

updateService = TestBed.get(UpdateService); // or somehow else, as you wish 
spyOn(updateService, 'intentsChange').and.returnValue(Observable.of(<SomeValueHere>)); // <-- here is main point 

現在檢查this.initTrainingStatus()被調用。這將工作。

不要忘了import 'rxjs/add/observable/of'頂部的某個地方。