[英]Access method's local variable in Angular unit test with Jasmine
How can I access the type
variable inside validate
function? 如何访问
validate
函数中的type
变量? The problem is code-covarage
shows that type
in if
statement not covered and I dunno how can I cover that. 问题是
code-covarage
显示该type
的if
语句未涵盖,我不知道该如何涵盖。
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(type)
,则意味着您的测试始终从以下位置返回:
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. 在单元测试中,应以直到
if (type)
语句为止的方式填充测试数据。 That will happen if you make sure that control
variable have proper data in it and has data in control.value
too. 如果您确保
control
变量中包含正确的数据,并且在control.value
也包含数据,则将发生这种情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.