Search code examples
angularunit-testingkarma-jasmineangular-unit-test

Angular unit test failing when using (submit)


Using Angular v4.4.4, I am saving a form using the (submit) event on the <form> element. On the live code everything works correctly. However, in the unit test clicking on a <button> does not trigger (submit) and the test fails. For example,

Component (pseudo-code):

@Component({
    template: `
        <form [formGroup]="formGroup" (submit)="onSave()">
            Your name: <input type="text" formControlName="name">
            <button id="saveButton">Save</button>
        </form>
    `
})
export class FooComponent {
    public formGroup: FormGroup;

    public onSave(): void {
        // save and route somewhere
    }
}

Unit test (pseudo-code):

describe('FooComponent', () => {
    let fixture, component, _router, routerSpy;

    beforeAll(done => (async() => {
        TestBed.configureTestingModule({
            imports: [
                RouterTestingModule.withRoutes([]),
                FormsModule,
                ReactiveFormsModule
            ]
        });

        fixture = TestBed.createComponent(FooComponent);
        component = fixture.componentInstance;
        _router = fixture.debugElement.injector.get(Router);
        routerSpy = spyOn(_router, 'navigate');
        fixture.detectChanges();
    })().then(done).catch(done.fail));

    it('should save the form', () => {
        const saveButton = fixture.debugElement.query(By.css('#saveButton'));
        saveButton.triggerEventHandler('click', null);
        expect(routerSpy).toHaveBeenCalled();

        // the test fails because the form is not actually submitted
    });
});

I am certain the problem is with the (submit) event because if I remove it and move the onSave() call to a (click) on the button the unit test does work.

So this fails in a unit test:

<form [formGroup]="formGroup" (submit)="onSave()">

But this succeeds:

<button id="saveButton" (click)="onSave()">Save</button>

What am I doing wrong in the spec?


Solution

  • Because you have no event handler on the button. That's why triggerEventHandler can't trigger any handler on the button. In your case you have to use saveButton.nativeElement.click() because now click event will be bubbled and submit event will be fired