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

Angular unit test failing when using (submit)

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

我在规范中做错了什么?

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