3

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?

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.