【问题标题】:Angular 5 template driven form unit Test - Cannot read property 'form' of undefinedAngular 5模板驱动表单单元测试-无法读取未定义的属性“表单”
【发布时间】:2019-02-23 20:14:54
【问题描述】:

您好,我是测试新手。 我尝试了很多来测试一个函数,但即使在阅读了所有关于此的 Stackoverflow 主题之后也无法成功。 我希望你能找到一种方法来帮助我..

这是我的 html 的摘录:

<form #myForm="ngForm">

这是我的一张:

@ViewChild('myForm')myForm: NgForm;

我有一个验证功能:

public valider(): void {
    if (this.myForm.form.valid) {
        //doSomething
    } else {
        console.log('your form is not valid.');
    }
}

最后是我要运行的测试:

it('should send an error when the form is not valid', () => {
    fixture = TestBed.createComponent(myComponent);
    comp = fixture.componentInstance;
    fixture.detectChanges();
    fixture.whenStable().then(() => {
        fixture.detectChanges();
        expect(comp.myForm.form.invalid).toBeTruthy();
        comp.valider();
    });
});

我得到的错误是:

未处理的 Promise 拒绝:', 'Cannot read property 'form' of undefined'

非常感谢大家

【问题讨论】:

  • 您是否在TestBed 中导入了FormsModule
  • 是的,我会添加我的测试配置

标签: angular angular5 angular2-forms


【解决方案1】:

你应该在该行之后初始化你的表单

 fixture.detectChanges();

像这样:

   component.riskForm = new NgForm([],[]);

【讨论】:

    【解决方案2】:

    我已经稍微改变了你的组件。

    import {Component, ViewChild} from '@angular/core';
    import {NgForm} from '@angular/forms';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      @ViewChild('myForm') myForm: NgForm;
    
      valider = (): boolean => this.myForm.form.valid;
    }
    

    然后你的测试应该是这样的:

    import {TestBed, async, ComponentFixture} from '@angular/core/testing';
    import { AppComponent } from './app.component';
    import {FormsModule} from '@angular/forms';
    
    describe('AppComponent', () => {
    
      const initialFormValid = true;
      let fixture: ComponentFixture<AppComponent>;
      let component: AppComponent;
    
      beforeEach(async(() => {
        TestBed.configureTestingModule({
          imports: [
            FormsModule,
          ],
          declarations: [
            AppComponent
          ],
        }).compileComponents();
      }));
    
      beforeEach(() => {
        fixture = TestBed.createComponent(AppComponent);
        component = fixture.componentInstance;
      });
    
      it('should be defined', () => {
        expect(component).toBeDefined();
      });
    
      it('#valider should return forms valid state', () => {
        expect(component.valider()).toEqual(initialFormValid);
      });
    
    });
    

    【讨论】:

    • 非常感谢您的帮助,我会尽快尝试的 =)
    猜你喜欢
    • 2018-12-23
    • 1970-01-01
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    • 2021-01-22
    • 1970-01-01
    • 1970-01-01
    • 2017-06-28
    相关资源
    最近更新 更多