Angular 无法读取属性';名称';在规范中未定义的
我正在从事Angular8项目,使用jest和jasmine作为测试配置 .tsAngular 无法读取属性';名称';在规范中未定义的,angular,testing,jasmine,Angular,Testing,Jasmine,我正在从事Angular8项目,使用jest和jasmine作为测试配置 .ts // all imports are done correctly @Component({ selector: 'app-xyz', templateUrl: './xyz.component.html', styleUrls: ['./xyz.component.scss'] }) export class XYZComponent implements OnInit { public in
// 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();
});
});
即使你正在做:
component.info = {
'list':
[
{
'fName':'Eddy',
'lName':'He',
'number: 123
}
]
};
在调用component.ngOnInit()
之前,这是不够的,因为在ngOnInit()
方法中,您正在执行this.info=this.infoService.getData()代码>,覆盖您的信息
属性
我相信在这个规范上下文中,这个方法返回undefined
更好的方法是模拟服务,提供一个假getData
方法,返回您希望组件处理的数据
或者您可以将this.info=this.infoService.getData()
移动到构造函数中,因为它不依赖于输入数据,这将使重写正常工作。您可以添加this.infoService.getData()的内容吗?我认为问题可能存在。是的,我可以,但是我应该在.spec文件中添加到哪里?你能指导我吗?哦,我指的是方法的内容,作为一个单独的代码片段。等等,nvm,我发现了错误,正在写回复。好的,我将尝试第一种方法来模拟服务,并为其提供一个假呼叫。。。你能帮我举一些关于如何模拟服务的例子吗?参见,搜索“MockUserService”。
component.info = {
'list':
[
{
'fName':'Eddy',
'lName':'He',
'number: 123
}
]
};