我为我的角度应用程序编写了一个茉莉花测试。但是我在ngOninit()上遇到了错误
TypeError: Cannot read property 'cStations' of undefined
我的代码如下:-
public ngOnInit(): void {
if (this.sResult.cStations) {
this.cStations = this.sResult.cStations;
} else if (this.sResult.rs) {
this.cStations = this.sResult.rs.length > 0 ? this.sResult.rs[0].cStations : undefined;
}
}
我的单元测试如下:-
describe('BarChartHorizontalComponent', () => {
let component: BarChartHorizontalComponent;
let fixture: ComponentFixture<BarChartHorizontalComponent>;
let cStations: CStation;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ BarChartHorizontalComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(BarChartHorizontalComponent);
component = fixture.componentInstance;
component.cStations = [];
fixture.detectChanges();
});
afterEach(() => {
fixture.destroy();
});
it('should have input value', () => {
expect(component.cStations).toBeTruthy();
});
});
问题是如何在测试中定义或初始化ngOninit函数的属性
任何解决方案?
答案 0 :(得分:0)
替换
component.cStations = [];
使用
component.sResult = {cStations: []};