How can I access the type
variable inside validate
function? The problem is code-covarage
shows that type
in if
statement not covered and I dunno how can I cover that.
interface NotUnique {
notUnique: boolean;
}
@Injectable()
export class CheckExists implements AsyncValidator {
constructor(
private http: HttpClient
) {}
async validate(control: FormControl): Promise<NotUnique> {
try {
if (!control || !control.parent) {
return;
}
const value: string = control.value;
const type = value.includes('@') ? 'email' : 'username';
if (type) {
const res = await this.http.post('/users/exists', {field: type, value: value}).toPromise();
if (!(res as ExistsResponse).exists) {
return null;
}
return { notUnique: true };
}
} catch (err) {
return null;
}
}
}
If code-coverage is not covering if(type)
that means your test is always returning from:
if (!control || !control.parent) {
return;
}
In your unit test, you should fill the test data in such a way that it reaches till if (type)
statement. That will happen if you make sure that control
variable have proper data in it and has data in control.value
too.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.