angular - 在 Angular 单元测试中使用回车键提交表单

标签 angular unit-testing angular2-forms angular-components angular-test

我正在为作为登录表单的 Angular 4 组件编写测试。可以通过单击“提交”按钮或在任何输入字段中按回车键来提交表单。此行为由 Angular 表单指令决定。

我可以编写一个测试用例来验证单击按钮是否提交了表单,但我无法通过按键事件触发提交行为。

模板:

<form (ngSubmit)="onLoginSubmit()" #loginForm="ngForm">
<div class="form-group">
    <label for="userid">User ID</label>
    <input type="text" class="form-control" name="userid" id="userid" required
        [(ngModel)]="model.userId" #userid="ngModel">
    <div [hidden]="userid.valid || userid.untouched" class="alert alert-danger">
        User ID is required
    </div>
</div>
<div class="form-group">
    <label for="password">Password</label>
    <input type="password" class="form-control" name="password" id="password" required
        [(ngModel)]="model.password" #password="ngModel">
    <div [hidden]="password.valid || password.untouched" class="alert alert-danger">
        Password is required
    </div>
</div>
<button type="submit" class="btn btn-success" [disabled]="loginForm.form.invalid">Submit</button>    

规范:

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement, Component, ViewChild } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { Observable } from 'rxjs/Observable';

import { LoginFormComponent } from './login-form.component';
import { ILoginService } from '../../service/ILoginService';
import { IAuthService } from '../../service/IAuthService';


describe('Login Form', () => {
    let comp: LoginFormComponent;
    let fixture: ComponentFixture<LoginFormComponent>;
    let userIdElement: DebugElement;
    let passwordElement: DebugElement;
    let submitElement: DebugElement;

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [FormsModule, ReactiveFormsModule],
            declarations: [LoginFormComponent],
            providers: [
                { provide: 'IloginService', useClass: UserServiceMock },
                { provide: 'IAuthService', useClass: MockAuthService }]
        });
        fixture = TestBed.createComponent(LoginFormComponent);

        comp = fixture.componentInstance;

        userIdElement = fixture.debugElement.query(By.css('input[name=userid]'));
        passwordElement = fixture.debugElement.query(By.css('input[name=password]'));
        submitElement = fixture.debugElement.query(By.css('button'));
    });

    describe('Submit', () => {
        let authService: IAuthService;
        let authServiceSpy: jasmine.Spy;
        let loginService: ILoginService;
        let loginServiceSpy: jasmine.Spy;

        beforeEach(() => {
            comp.model.userId = 'mock user';
            comp.model.password = 'mock password';
            comp.loginUrl = 'mock url';

            authService = fixture.debugElement.injector.get('IAuthService');
            authServiceSpy = spyOn(authService, 'login').and.returnValue(null);

            loginService = fixture.debugElement.injector.get('IloginService');
            loginServiceSpy = spyOn(loginService, 'handleLoginResult');
        });

        it('should invoke the auth and login services when submit is clicked', () => {
            submitElement.nativeElement.click();
        });

        xit('should submit the form on enter key pressed in userId input', () => {
            userIdElement.nativeElement.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter' }))
        });

        xit('should submit the form on enter key pressed in password input', () => {
            passwordElement.nativeElement.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter' }))
        });

        afterEach(() => {
            fixture.detectChanges();
            fixture.whenStable().then(() => {
                expect(authService.login).toHaveBeenCalledWith('mock user', 'mock password', 'mock url');
                expect(loginService.handleLoginResult).toHaveBeenCalled();
            });
        });
    });
});

从按钮分派(dispatch)“点击”事件的测试通过,但从输入元素分派(dispatch) keydown 事件的测试(当前禁用)失败。

我可以分派(dispatch)其他事件来触发表单的 ngSubmit 处理程序吗?

最佳答案

尝试使用 keypress 而不是 'keydown`

new KeyboardEvent('keypress', { key: 'Enter' })

关于angular - 在 Angular 单元测试中使用回车键提交表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46289712/

相关文章:

angular - 如何将第三方 javascript 库与 ionic4 和电容器一起使用?

javascript - Angular 项目构建成功但出现这些错误

.net - 数据库单元测试。对于运行 CI、具有分支和重型数据库的企业解决方案,最好的数据库测试方法是什么?

java - 对于类型T的方法,它的 'inferred'类型应该是什么当它需要两个<? super T> 争论?

angular - 如何在 Angular 2 的 Material 选择框中显示 md 错误?

angular2-highcharts : update rendered chart data

json - 如何将 JSON 文件导入 TypeScript 文件?

ruby-on-rails - 如何显示在 Rails 单元测试中失败的验证?

angular - 悬停时如何在按钮顶部显示工具提示?

javascript - Angular 2,在表单中设置文本输入的值