【问题标题】:Angular unit test failing when using (submit)使用(提交)时角度单元测试失败
【发布时间】:2018-05-03 09:29:25
【问题描述】:

使用 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>

我在规范中做错了什么?

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 完美。谢谢。
    猜你喜欢
    • 2018-11-18
    • 1970-01-01
    • 1970-01-01
    • 2023-01-22
    • 2020-04-09
    • 2018-10-26
    • 2021-05-25
    • 2015-04-29
    • 2014-01-14
    相关资源
    最近更新 更多