簡體   English   中英

使用Jasmine在Angular單元測試中訪問方法的局部變量

[英]Access method's local variable in Angular unit test with Jasmine

如何訪問validate函數中的type變量? 問題是code-covarage顯示該typeif語句未涵蓋,我不知道該如何涵蓋。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM