加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

在Angular单元测试中使用enter键提交表单

发布时间:2020-12-17 18:10:45 所属栏目:安全 来源:网络整理
导读:我正在编写一个Angular 4组件的测试,它是一个登录表单.可以通过单击“提交”按钮或在任何输入字段中输入来提交表单.此行为由Angular表单指令决定. 我可以编写一个测试用例来验证按钮单击提交表单,但是我无法通过按键事件触发提交行为. 模板: form (ngSubmit
我正在编写一个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();
            });
        });
    });
});

从按钮调度“click”事件的测试通过,但从输入元素调度keydown事件的测试(当前禁用)失败.

我可以发送一个不同的事件来触发表单的ngSubmit处理程序来触发吗?

解决方法

尝试使用keypress而不是’keydown`

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读