Angular 在响应式表单上测试提交事件

Angular testing submit event on reactive form

上下文

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

我的问题

无法触发表单的提交事件

文件

Component.html

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

Component.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);

如何触发表单提交事件?

第一个选项是直接调用 ngSubmit

.triggerEventHandler('ngSubmit', null); 

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

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