问题
I am making a simple application which has an input field and a button and on click of the button an api call was made and respective response is fetched.
Everything working fine with this.
Things done as of now: I am making a validation and display the error message via a function like,
hello.component.ts:
controlErrors(formControl: AbstractControl | FormControl): string {
if (
formControl &&
formControl.touched &&
formControl.invalid &&
formControl.errors
) {
return Object.keys(formControl.errors)[0];
} else {
return null;
}
}
And in HTML
template adding the validation message like,
hello.component.html:
<form [formGroup]="userForm" novalidate>
<input
class="email-input mat-body-1"
type="email"
formControlName="email"
/>
<button class="subscribe mat-body-2" [disabled]="userForm.invalid || submitted" (click)="subscribeEmail()">
Subscribe
</button>
<span *ngIf="controlErrors(userForm.get('email')); let error">{{
error
}}</span>
</form>
I have written test case to cover the control errors (as other test were already covered) like,
hello.component.spec.ts:
describe('controlErrors', () => {
it('should return null if !formControl', () => {
const result = component.controlErrors(null);
expect(result).toBeNull();
});
it('should return null if formControl is untouched', () => {
const formControl = new FormControl();
const result = component.controlErrors(formControl);
expect(result).toBeNull();
});
});
Issue: And the issue is while running the test coverage it is showing that the branch (yellow highlighted) and statement(red highlighted) not covered like,
Requirement: Kindly please help me to cover these tests of control errors completely so that this spec file will have 100% test coverage.
Working test case written stackblitz: https://stackblitz.com/edit/angular-testing-x5rx7s
As I am a beginner in angular unit testing please guide me with right solution.
Big thanks in advance.
Update:
Based on the comment by @Marc, I have tried like,
it('should return invalid formControl if touched with invalid email', () => {
const formControl = new FormControl('test');
formControl.touched;
fixture.detectChanges();
const result = component.controlErrors(formControl);
expect(result).toBeNull();
});
But it results in the same issue like the above screenshot.. Can anyone please help me how should I need to achieve the result of full test coverage?
来源:https://stackoverflow.com/questions/62153001/how-to-cover-the-test-for-form-control-in-angular-stackblitz-attached