我的一个组件中有一块手表,用于监视服务中的变量(因此是主题)。 (我在这里得到了这个实现的想法:updating variable changes in components from a service with 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不是函数
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();
});
});
有谁知道如何修复该错误,以便我的测试实际上再次运行?
答案 0 :(得分: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'
。