简体   繁体   English

使用Jasmine在Angular单元测试中访问方法的局部变量

[英]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显示该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;
        }
    }
}

upd: image 更新:图片 代码覆盖率的屏幕截图

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM