对于下面的EditFlag组件,我编写了角度测试用例。在执行规范文件中提到的以下测试用例时,我看到此错误 TypeError:无法读取未定义的属性“ client” 。
此外,我想将用于切换用例的测试用例包括到我的测试用例中。 有人可以帮我这个测试用例吗?
editflag.component.ts
constructor(private flagService: FlagService,
private editFlagDialog: MatDialogRef<EditFlagComponent>),
@Inject(MAT_DIALOG_DATA) public data: any,
private dialog: MatDialog){}
ngOnInit: void {
switch(this.data.action) {
case 'create':
this.flagClone = this.initializeFlagClone();
break;
case 'edit':
this.flagEdit();
break;
default:
console.log('No action');
}
}
public flagEdit(){
const res = {...this.data};
this.flagVar = { ...res.flag};
if(this.data.flag.client == null ) {
this.isSearch = false;
this.initializeClient();
}
}
editflag.spec.ts
const testData = {
"flag":{
id: null, //string
description: null, //string
url: null, //string
client: null
},
"action": "edit"
};
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule
],
declarations: [
EditFlagComponent
],
providers: [
HttpClient,
HttpHandler,
{provide: MatDialog, useValue: {} },
{provide: MatDialogRef, useValue: {} },
{provide: MAT_DIALOG_DATA, useValue: {testData} },
]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(EditFlagComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should call flagEdit',() => {
component.flag.client = testData.flag.client;
component.flagEdit();
fixture.detectChanges();
expect(component.isSearch).tobeFalsy();
});
此外,希望将以下内容纳入报道摘要:
switch(this.data.action) {
case 'create':
this.flagClone = this.initializeFlagClone();
break;
case 'edit':
this.flagEdit();
break;
default:
console.log('No action');
}
答案 0 :(得分:0)
我认为您做错了useValue
。
更改此行:
{provide: MAT_DIALOG_DATA, useValue: {testData} },
对此:
{provide: MAT_DIALOG_DATA, useValue: testData },
删除行
component.flag.client = testData.flag.client;
在单元测试中。
答案 1 :(得分:0)
错误提示 TypeError:无法读取未定义的属性“ client”。该错误在行this.data.flag.client == null
中引发
您定义了@Inject(MAT_DIALOG_DATA) public data: any,
,在测试中您拥有{provide: MAT_DIALOG_DATA, useValue: {testData} },
就像拥有{provide:MAT_DIALOG_DATA,useValue:{testData:testData}}一样,即
this.data = { testData: {
"flag":{
id: null, //string
description: null, //string
url: null, //string
client: null
},
"action": "edit"
}}
现在有问题,您尚未设置this.data.flag
的值
要解决此问题,只需将{provide: MAT_DIALOG_DATA, useValue: {testData} },
设置为{provide: MAT_DIALOG_DATA, useValue: testData },
,现在您将正确提供该值