在单元测试中,我正在测试以查看是否正在调用我的服务。我有一个名为loadUser()的函数。此函数使用服务getData从URL中检索所有用户。然后,它将用户ID和该特定用户的信息(名称,姓氏等)加载到表单中。从这里开始,允许用户编辑其凭据。此函数使用patchValue将数据显示到正确的表单字段。现在,我仅尝试测试是否调用了我的服务getData就是这样。运行测试时,出现以下错误:TypeError: Cannot read property 'patchValue' of undefined
。我想让我的测试说getData已被调用。这是我的测试,下面是我的功能(为简便起见,我仅发布了必要的代码)。我发布了设置,因为也许我在那儿丢失了什么?
规格:
fdescribe('User Component', () => {
let httpService: HttpService;
let userComponent: UserComponent
let fixture: ComponentFixture<UserComponent>
let debugElement: DebugElement;
beforeEach(async() => {
TestBed.configureTestingModule({
declarations: [
UserComponent,
],
imports: [HttpModule, FormsModule,ReactiveFormsModule],
providers: [
HttpService
],
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(UserComponent);
userComponent = fixture.componentInstance;
debugElement = fixture.debugElement;
httpService = debugElement.injector.get(HttpService);
fit('should have getUsers() call the service GetData()', inject([HttpService], fakeAsync((httpService) => {
let url = AppConfig.URL_UserById'
let getDataSpy= spyOn(httpService,'getData').and.returnValue(Observable.of(url));
userComponent.loadUser();
expect(getDataSpy).toHaveBeenCalled();
})))
})
组件:
loadUser() {
this.httpService.getData(AppConfig.URL_UserById + "?UserID=" + this.userId)
.catch((error: Response | any) => {
this.showAlertWindow(this.exceptionMessage);
console.error(error.message || error);
return Observable.throw(error.message || error);
})
.subscribe((res: any) => {
this.frmUser.patchValue({
FirstName: res.FirstName,
MiddleName: res.MiddleName,
EmailAddress: res.EmailAddress,
LastName: res.LastName
});
this.setUserAccess(res.UserAccessDetail)
});
现在,如果我注释掉this.frmUser.patchValue){FirstName...}
行,则测试通过并成功检查是否调用了getData()。所以我想我需要沿着这些思路启动patchValueor。谢谢。
答案 0 :(得分:0)
该问题的简单解决方案。在ngOnInit组件中,创建用户表单。我要做的只是做userComponent.ngOnInit()
,测试通过了。
用于工作测试的完整代码:
fit('should have getUsers() call the service GetData()', inject([HttpService], fakeAsync((httpService) => {
let url = AppConfig.URL_UserById + "?UserID=" + this.userId
let getDataSpy= spyOn(httpService, 'getData').and.returnValue(Observable.of(url));
userComponent.ngOnInit();
userComponent.loadUser();
expect(getDataSpy).toHaveBeenCalled();
})))
})
答案 1 :(得分:0)
只需将其添加到我的
ngOnInit(): void {
this.myForm.patchValue({
username: this.AUTH_USER.username
})
}
解决了问题:请记住,我已使用登录用户的初始值声明了 AUTH_USER。