我正在为角度7组件创建单元测试用例。我有一个组件 包含ngOnInit()来调用该组件的getUser数据函数。
组件文件:
ngOnInit() {
this.getUserDetails(); // If commented test runs successfully
}
getUserDetails() {
this.guestUserService.getData().subscribe(
result => {
this.profileForm = this.fb.group({
firstName: [result['data']['firstname'], Validators.compose([Validators.required, Validators.pattern('^[a-zA-Z ]+$')])],
lastName: [result['data']['lastname'], Validators.compose([Validators.required, Validators.pattern('^[a-zA-Z ]+$')])],
username: [{ value: result['data']['username'], disabled: true }, Validators.compose([Validators.required, Validators.email])]
});
this.imageURL = result['data']['imageFile'];
}
);
}
为函数getUserDetails()创建了单元测试用例
let guestUserService: any;
let guestUserServiceSpy: any;
TestBed.configureTestingModule({
providers: [
{ provide: GuestUserService, useValue: guestUserService }]
})
it('should get user data and create profile form when getUserDetails called', () => {
guestUserServiceSpy = guestUserService.getData.and.returnValue(of({
data: { firstname: 'ABC', lastname: 'XYZ', username: 'ABC@XYZ', imageFile: 'http://imagefile.XYZ.com' }
}
));
spyOn(component, 'getUserDetails').and.callThrough();
component.getUserDetails();
fixture.detectChanges();
expect(guestUserService).toBeDefined();
expect(guestUserServiceSpy).toBeDefined();
expect(component.getUserDetails).toHaveBeenCalledTimes(1);
expect(guestUserServiceSpy).toHaveBeenCalledTimes(1);
expect(component.profileForm.valid).toBeTruthy();
expect(component.profileForm.controls['username'].value).toEqual('ABC@XYZ');
});
在运行ng测试以运行该测试用例时,首先调用组件的ngOnInit并给出错误消息:
TypeError:无法读取已被调用一次的未定义的预期间谍GuestUserService.getData的属性“ subscribe”。被称为2 时间。
如果我删除对函数“ getUserDetails()”的调用,则测试用例将成功运行。
答案 0 :(得分:1)
调用两次,因为测试用例中有component.getUserDetails()
和fixture.detectChanges()
。
fixture.detectChanges()
将触发ngOnInit()
,并且您已经在方法中添加了getUserDetails()
。