问题描述
我是这项工作和编程的新手,我的任务是进行单元测试并获得 80% 的代码覆盖率。我无法获得此方法的代码覆盖率。它说声明未涵盖。我做错了什么?
support.component.ts
searchId: string = '';
orchestration: string = '';
public clearText(){
this.searchId = '';
this.orchestration = '';
}
support.component.html
<mat-select id="searchselected" (selectionChange)="clearText()">
<input type="text" class="form-control" id="searchId" [(ngModel)]=""searchId size="40" placeholder="enter value">
<input type="text" class="form-control" id="orchestration" [(ngModel)]=""searchId size="40" placeholder="enter orchestration">
support.component.spec.ts
const spy = spy = spyon(component,'clearText').and.callThrough();
component.searchId;
component.orchestration;
component.clearText();
expect(spy).toHaveBeenCalled();
expect(component.searchId).toEqual('');
expect(component.orechestion).toEqual('');
解决方法
您不需要监视组件方法。服务方法等外部方法会被监视,以避免在测试组件的方法时调用它们。
所以在这里你可以直接调用该方法并测试如下条件:
support.component.spec.ts
component.clearText();
expect(component.searchId).toEqual('');
expect(component.orechestion).toEqual('');