2

使用 Angular v4.4.4,我正在使用元素(submit)上的事件保存表单。<form>在实时代码上,一切正常。但是,在单元测试中单击 a<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)按钮上的 a ,则单元测试确实有效。

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

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

但这成功了:

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

我在规范中做错了什么?

4

1 回答 1

6

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

于 2017-11-20T09:44:47.993 回答