简体   繁体   English

如何从茉莉花中的角度访问或添加模板引用变量

[英]How to access or add template reference variable from angular within jasmine

How do I access a template reference/variable within Jasmine?如何访问 Jasmine 中的模板引用/变量?

form.component.html表单.组件.html

<form #f="ngForm" class="form form-profession" novalidate>...

<div class="error-group" *ngIf="f.invalid">error</div>

form.component.ts form.component.ts

export class FormComponent implements OnInit {

  @ViewChild('f') f: NgForm;

  constructor(
    private router: Router
  ) { }

  ngOnInit() {
  }

  onSubmit(f) {
    if (f.valid) {
      // do stuff
    }
  }
}

form.component.spec.ts form.component.spec.ts

it('should display errors when form is invalid', () => {
  fixture.componentInstance.f.invalid = true;
  expect(fixture.nativeElement.querySelector('.error-group')).not.toBeNull();
});

I get this error "[ts] Cannot assign to 'valid' because it is a constant or a read-only property."我收到此错误“[ts] 无法分配给 'valid',因为它是一个常量或只读属性。”

Try doing this.尝试这样做。

 it('should show error message when form is invalid', () => {
    const form = fixture.componentInstance.f;  // get the form instance through the component.
    form.form.setErrors({required: true}); // making the form invalid

    fixture.detectChanges(); // trigger a change detection cycle for the component

    expect(fixture.nativeElement.querySelector('.error-group').textContent).toContain('sss');

    expect(form.valid).toBeFalsy();
  });

您可以使用它来访问组件fixture.debugElement.query(By.directive(ClassOfTheSearchedComponent))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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