【发布时间】:2020-02-04 10:26:17
【问题描述】:
我正在使用 jest 和 jasmine 作为测试配置进行 Angular8 项目。
.ts
// all imports are done correctly
@Component({
selector: 'app-xyz',
templateUrl: './xyz.component.html',
styleUrls: ['./xyz.component.scss']
})
export class XYZComponent implements OnInit {
public info;
public number;
constructor(private InfoService: infoService ) {
}
ngOnInit() {
this.getInfo();
}
public getInfo() {
this.info = this.infoService.getData();
this.number = this.info.list[0].number;
}
}
.spec
// all imports are done
describe('XYZComponent', () => {
let component: XYZComponent;
let fixture: ComponentFixture<XYZComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ //imports done ],
declarations: [ XYZComponent],
schemas: [ NO_ERRORS_SCHEMA ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(XYZComponent);
component = fixture.componentInstance;
component.info = {
'list':
[
{
'fName':'Eddy',
'lName':'He',
'number: 123
}
]
};
component.ngOnInIt();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
当在 .spec 文件中调用 ngOnInit() 时,它会抛出如下错误:
● XYZComponent › 应该创建
TypeError: Cannot read property 'list' of undefined
43 | this.info = this.infoService.getData();
> 44 | this.number = this.info.list[0].number;
| ^
46 | }
【问题讨论】:
-
可以把
this.infoService.getData()的内容加进去吗?我认为问题可能就在那里。 -
是的,我可以,但是我应该在 .spec 文件中的哪个位置添加您能指导我完成吗?
-
哦,我的意思只是方法的内容,作为单独的代码sn-p。等nvm,发现错误,写个回复。