[英]Access method's local variable in Angular unit test with Jasmine
如何訪問validate
函數中的type
變量? 問題是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(type)
,則意味着您的測試始終從以下位置返回:
if (!control || !control.parent) {
return;
}
在單元測試中,應以直到if (type)
語句為止的方式填充測試數據。 如果您確保control
變量中包含正確的數據,並且在control.value
也包含數據,則將發生這種情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.