角单元测试异步管道不会触发

时间:2019-07-17 10:00:17

标签: angular unit-testing asynchronous

我有这个组件来吸引用户并显示有关该用户的信息。在HTML中,我有一个异步管道,该管道仅在调用完成后显示div。

export class PersonalComponent implements OnInit, OnDestroy {
  errorGettingUser = false;
  roles = USER_ROLE;
  personalInformationForm: FormGroup = this.fb.group({
    firstName: ['', [Validators.required]],
    lastName: ['', [Validators.required]],
    role: ['', [Validators.required]],
    email: ['', [Validators.required, Validators.pattern(EMAIL_REGEX)]],
    phone: ['', [Validators.required, Validators.minLength(9)]]
  });
  user$: Observable<Account>;
  userEdited$ = new Subject<User>();


  private userId = '1231124125';
  private inView = true;

  constructor(private fb: FormBuilder, private userService: UserService) {}

  ngOnInit() {
    this.user$ = this.getUser();
    this.onEditUser();`
  }

  ngOnDestroy() {
    this.inView = false;
  }

  getUser() {
    console.log('getUser')
    return this.userService.getUser(this.userId).pipe(
      takeWhile(() => this.inView),
      tap(user => {
        this.fillForm(user);
      }),
      catchError(error => {
        this.errorGettingUser = true;
        return of(error);
      })
    );
  }
<div *ngIf="user$ | async as user"> ...FORM... </div>

我已经测试了fakeasync,async和done()。在div内部,我有一个显示用户的表单。我要测试的是表单是否正确实现,以及表单是否有效,如果表单的按钮已启用。

例如,在这种情况下,表单应该无效。但是当我尝试获取按钮时,它给了我空值,因为div不在HTML上呈现。

it('personalInformationForm should be invalid', async() => {
fixture.detectChanges();
updateForm('', '', '', '', '');
fixture.detectChanges();
fixture.whenStable().then(() => {
  expect(component.personalInformationForm.valid).toBeFalsy();
  fixture.detectChanges();
  let els: HTMLElement[];
  els = fixture.debugElement.nativeElement.querySelectorAll('app-button');
  expect(els[0].querySelector('button').disabled).toBeTruthy(); // check if it is disabled
})

});

用异步管道实施测试的最佳方法是什么?

0 个答案:

没有答案