首页 > 解决方案 > 使用fixture.detectChanges()时出错;在角度使用茉莉花

问题描述

我正在尝试使用 jasmine 检查是否触发了单击事件。使用点击事件调用的方法使用事件发射器。我已经尝试了以下代码,但是当我使用fixture.detectChanges()时,不知何故我收到错误“失败:未捕获(承诺):TypeError:无法读取未定义的属性'mobileNum'”;

it('trigget next button click', async(() => {

    const fixture = TestBed.createComponent(LoginForm1Component);
    const component = fixture.componentInstance;
    debugger;
    spyOn(component.validateLoginEvent, 'emit').and.callThrough();

    const nativeElement = fixture.nativeElement;
    const button = nativeElement.querySelector('#loginBtn');

    button.dispatchEvent(new Event('click'));
    expect(fixture.componentInstance.templateService.validFormFlag).toBe(false);
    component.validateUserRequest = {
        mobileNum: 'XXXXXXXX',

    };
    fixture.detectChanges();
    expect(component.validateLoginEvent.emit).toHaveBeenCalled();

}));

<form class="transfer-form marginTop120" id="loginForm" #declarativeForm="ngForm">
    <div class="form-group" id="email" class="email">
        <label for="mobileNumber" class="col-form-label col-form-label-lg" id="textformat">
            {{ 'LOGIN.ENTER_YOUR_MOBILE_NUMBER' | translate }}&nbsp;<span class="labelHint">q12333</span>
        </label>
        <input type="text" name="mobileNumber" placeholder="05XXXXXXXX" [(ngModel)]="validateUserRequest.mobileNum" only-number maxlength="10" />
    </div>  // getting error here
   <div style="transform:scale(0.7);transform-origin:0;">
    <re-captcha [(ngModel)]="declarativeFormCaptchaValue" name="captcha" (resolved)="resolved($event)" required></re-captcha>
</div>
    <div class="button-holder loginStep1">
       
        <a class="button btn-md btn-blue button-step-1 fa-pull-right new-button" id="loginBtn" href="javascript:void(0);" validateLoginDirective [ngClass]="{'disabled': !declarativeFormCaptchaValue && globalService.properties.CAPTCHA_ENABLE }" (click)="validate(this.templateService.validFormFlag)">
            {{ 'SHARED.NEXT' | translate }}
        </a>    // this is next click
    </div>
</form>


export class LoginForm1Component implements OnInit {
  @Input() validateUserRequest: ValidateUserRequest;
  @Output() validateLoginEvent = new EventEmitter();
  public declarativeFormCaptchaValue: any;

  constructor(
    public router: Router,
    public globalService: GlobalService,
    public templateService: TemplateService
  ) { }

  ngOnInit() { }

  validate(isValid: boolean) {
    if (isValid) {
      this.validateLoginEvent.emit();
    }
  }

  resolved(captchaResponse: string) {
    console.log(`Resolved captcha with response: ${captchaResponse}`);
  }
}

标签: angularjasmine

解决方案


在模板中,您正在使用 validateUserRequest

[(ngModel)]="validateUserRequest.mobileNum"

您是否在 ts 文件中初始化该 validateUserRequest ?

初始化 validateUserRequest 然后尝试:)


推荐阅读