代码之家  ›  专栏  ›  技术社区  ›  Raymond the Developer

如何从jasmine的角度访问或添加模板引用变量

  •  0
  • Raymond the Developer  · 技术社区  · 6 年前

    如何在jasmine中访问模板引用/变量?

    表单.component.html

    <form #f="ngForm" class="form form-profession" novalidate>...
    
    <div class="error-group" *ngIf="f.invalid">error</div>
    

    表单.component.ts

    export class FormComponent implements OnInit {
    
      @ViewChild('f') f: NgForm;
    
      constructor(
        private router: Router
      ) { }
    
      ngOnInit() {
      }
    
    onSubmit(f) {
        if (f.valid) {
          // do stuff
        }
      }
    

    表.component.spec.ts

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

    我知道这个错误 “[ts]不能赋给'valid',因为它是常量或只读属性。”

    1 回复  |  直到 6 年前
        1
  •  1
  •   Anuradha Gunasekara    6 年前

    试试这个。

     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();
      });
    
        2
  •  0
  •   mr__brainwash    5 年前

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