角度测试以反应形式提交事件 [英] Angular testing submit event on reactive form

查看:65
本文介绍了角度测试以反应形式提交事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a component with a basic form (reactive form). I try to test the submit event on this form to see if it calls the necessary method properly.

我无法触发表单的Submit事件

I can't trigger the submit event of the form

<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:

I also tried that instead of calling submit on form:

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

然后如何触发表单提交事件?

推荐答案

第一个选择是直接调用ngSubmit:

First option is calling ngSubmit directly:

.triggerEventHandler('ngSubmit', null); 

第二个选项正在导入ReactiveFormsModule,它将在窗体上内部设置submit处理程序.因此您的触发方法应该可以工作:

Second option is importing ReactiveFormsModule that will internally set submit handler on form. So your trigger method should work:

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

这篇关于角度测试以反应形式提交事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆