使用 Karma 进行角度单元测试,测试分支或服务间谍错误 ()



我目前正在 Angular 7 中测试一个 angular 应用程序,但我无法弄清楚如何测试提交函数的这个分支,我在这个组件中大约有 20 多个测试,其中一些甚至使用与不起作用的测试相同的服务间谍:

分行:

submit(): void {
if (this.systemTable) {
// this.formArray = this.formBuilder.array([]);
while (this.formArray.length) {
this.formArray.removeAt(0);
console.log('dfdfdf');
} //this.formArray.removeAt(0);

} //...

我的测试:

it('submit() should remove when systemTable is true', () => {
app.ngOnInit();
app.systemTable = true; //Entering the branch i wan't to test
const f = app.formArray; 
app.addRow(); //This function adds a row into the app.formRow, I checked it's values with a debugger and it's working
const userServiceSpy = spyOn(app.formArray, 'removeAt');
app.submit();
expect(userServiceSpy).toHaveBeenCalledTimes(1);
});

将循环从 while 更改为 for,在角度 8 中将不再需要此循环。

最新更新