【发布时间】:2019-05-28 13:50:36
【问题描述】:
在 Component.ts 中,
this.dataService.currentCity.subscribe(info => {
this.cities = info;
});
this.dataService.currentSelectedCity.subscribe(index => {
this.selectedCityIndex = index;
});
this.selectedCityInfo = this.cities[this.selectedCityIndex];
this.selectedCityWeatherList = this.selectedCityInfo.cityWeather.list;
我正在尝试在ngOnInit() 中测试这段代码。但我不确定如何测试这段代码。在这里,我的另一个组件使用我在该组件的`ngOnInit() 中订阅的行为主题向我发送一个对象数组以及所选项目的索引。并尝试访问所选对象中的 cityWeather 属性。
在 Spec.ts 中,我尝试过类似的方法,我确信这不是一种正确的测试方法。
it("should handle ngOnInit", async(() => {
let response;
const dataService = fixture.debugElement.injector.get(DataService);
spyOn(dataService, 'currentCity').and.returnValue(of(response));
component.ngOnInit();
expect(component.cities).toEqual(response);
}));
当我运行应用程序时,我得到了输出,但是当我测试 ngoninit 函数时,我没有从订阅中得到响应。我收到以下错误。 Failed: Cannot read property 'cityWeather' of undefined TypeError: Cannot read property 'cityWeather' of undefined
在data.service.ts中
private citySubject = new BehaviorSubject<any>('');
currentCity = this.citySubject.asObservable();
private selectedCity = new BehaviorSubject<any>('');
currentSelectedCity= this.selectedCitySubject.asObservable();
sendCityWeatherInfo(info,index) {
this.citySubject.next(info);
this.selectedCitySubject.next(index);
}
我在这样的组件中调用它(传递对象数组和索引)
this.dataService.sendCityWeatherInfo(this.cities, index);
【问题讨论】:
-
可以添加完整的组件代码吗?那么 spyOn spyOn(dataService, 'currentSelectedCity') 呢?你是否也返回了一个可观察的值?部分问题可能是 this.selectedCityIndex 仍未定义,因为 observable 尚未返回。
-
@HarijsDeksnis 我已经更新了我的代码。请检查一下。
标签: javascript angular typescript unit-testing