Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
834 views
in Technique[技术] by (71.8m points)

Angular unit testing for public void method which clears input filed on mat selectionChange

I am new to this job and programming and my task is to unit test and get 80 percent code coverage. I am not able to get code coverage for this method. It says statement not covered. What am I doing wrong?

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('');
question from:https://stackoverflow.com/questions/65896157/angular-unit-testing-for-public-void-method-which-clears-input-filed-on-mat-sele

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You don't need to spyOn the component method. External methods like service methods are spied on to avoid calling them when testing component's method.

So here you can directly call the method and test the conditions like below:

support.component.spec.ts

component.clearText();
expect(component.searchId).toEqual('');
expect(component.orechestion).toEqual('');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...