繁体   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