简体   繁体   中英

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

How can I access the type variable inside validate function? The problem is code-covarage shows that type in if statement not covered and I dunno how can I cover that.

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 (!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. That will happen if you make sure that control variable have proper data in it and has data in control.value too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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