【问题标题】:Angular testing submit event on reactive form角度测试以反应形式提交事件
【发布时间】:2017-09-17 12:58:58
【问题描述】:

上下文

我有一个具有基本形式(反应形式)的组件。我尝试在这个表单上测试提交事件,看看它是否正确调用了必要的方法。

我的问题

我无法触发表单的提交事件

文件

组件.html

<form class="form-horizontal"
  id="staticForm"
  [formGroup]="mySimpleForm"
  (ngSubmit)="sendMethod();"
>
  <input type="text" formGroupName="email">
  <button type="submit">Send form</button>
</form>

组件.ts

  ngOnInit() {
    this.initSimpleForm();
  }

  private initSimpleForm() {
    let file = null;

    this.mySimpleForm = this.formBuilder.group({
      email: [
        '',
        [
          Validators.required
        ]
      ]
    });
  }

  sendMethod() {
    console.log('submitted');
  }

component.spec.ts

beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        MyComponent
      ],
      imports: [],
      providers: [
        FormBuilder
      ],
      schemas: [NO_ERRORS_SCHEMA]
    })
    .compileComponents();
}));

beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    comp = fixture.componentInstance;
});  

it(`should notify in console on form submit`, () => {
    spyOn(console, 'log');

    comp.mySimpleForm.controls['email'].setValue('test@test.com');
    fixture.debugElement.query(By.css('form')).triggerEventHandler('submit', null);     
    fixture.detectChanges();

    expect(console.log).toHaveBeenCalled(); // FAILS
});

// TO make sure my spy on console log works, I made this and it works

it(`will notify on direct sendMethod Call`, () => {
    spyOn(console, 'log');

    comp.sendMethod();      
    fixture.detectChanges();

    expect(console.log).toHaveBeenCalled(); // SUCCESS
});

我也尝试过,而不是在表单上调用submit

fixture.debugElement.query(By.css('button')).triggerEventHandler('click', null);

那么如何触发表单提交事件呢?

【问题讨论】:

    标签: angular typescript jasmine karma-runner karma-jasmine


    【解决方案1】:

    第一个选项是直接调用ngSubmit

    .triggerEventHandler('ngSubmit', null); 
    

    第二个选项是导入ReactiveFormsModule,它将在表单内部设置submit 处理程序。所以你的触发方法应该可以工作:

    TestBed.configureTestingModule({
          declarations: [
            MyComponent
          ],
          imports: [ReactiveFormsModule], // <== import it
          providers: []
    

    【讨论】:

    • 谢谢,它有效。我导入了 ReactiveFormsModule 和 FormsModule 以避免 no provider for ControlContainer 错误。
    • 知道为什么触发我的提交按钮没有开箱即用?
    • 它不起作用,因为没有提交事件的处理程序,因为没有指令可以处理它,因为您没有导入包含该指令的 ReactiveFormsModule
    • 谢谢,听起来合法。可能令人失望的是,角度并没有警告我们这一点......
    猜你喜欢
    • 2016-12-19
    • 2015-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-15
    • 1970-01-01
    • 1970-01-01
    • 2013-02-22
    相关资源
    最近更新 更多