使用(提交)时角度单元测试失败

时间:2017-11-20 07:54:27

标签: angular unit-testing karma-jasmine angular-unit-test

使用Angular v4.4.4,我使用(submit)元素上的<form>事件保存表单。在实时代码上一切正常。但是,在单元测试中,单击<button>不会触发(submit)并且测试失败。例如,

组件(伪代码):

@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
    }
}

单元测试(伪代码):

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
    });
});

我确定问题出在(submit)事件上,因为如果我删除它并将onSave()调用移动到按钮上的(click),则单元测试会起作用。

所以这在单元测试中失败了:

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

但这成功了:

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

我在规范中做错了什么?

1 个答案:

答案 0 :(得分:2)

因为按钮上没有事件处理程序。这就是为什么triggerEventHandler无法触发按钮上的任何处理程序的原因。在您的情况下,您必须使用saveButton.nativeElement.click(),因为现在点击事件将被冒泡并且submit事件将被触发