Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular testing submit event on reactive form

Context

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.

My problem

I can't trigger the submit event of the form

Files

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('[email protected]');
    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
});

I also tried that instead of calling submit on form:

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

How then to trigger the form submit event?

like image 765
BlackHoleGalaxy Avatar asked Apr 20 '17 18:04

BlackHoleGalaxy


1 Answers

First option is calling ngSubmit directly:

.triggerEventHandler('ngSubmit', null); 

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: []
like image 184
yurzui Avatar answered Nov 11 '22 02:11

yurzui