简体   繁体   English

Angular 模板驱动表单中的 Karma-Jasmine 测试注册表

[英]Karma-Jasmine Testing register form in Angular template driven forms

I'm very new to Angular.我对 Angular 很陌生。 I'm trying to do Jasmine testing on template-driven forms but I got stuck.我正在尝试对模板驱动的表单进行 Jasmine 测试,但我被卡住了。

This is my .html file这是我的.html文件

<form name="Registerform" #Registerform="ngForm" (ngSubmit)="registerUser()" class="form">
            <div class="form-header">
                <h1 style="text-align: center;font-weight: bold; ">Register</h1>
            </div>
            <small class="text-danger">{{msg}}</small>
            <div class="row">
                <div class="form-group">
                    <label for="exampleInputEmail1">Email address</label>
                    <input type="email" class="form-control" placeholder="Enter email" name="email"
                        [(ngModel)]="user.emailId" required pattern="^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$" #email="ngModel"
                        [class.is-invalid]="email.invalid && email.touched">
                    <!--<small class="text-danger" [class.d-none]="email.valid || email.untouched">Email Id is required
                field</small>-->

                    <div *ngIf="email.errors && (email.invalid && email.touched)">
                        <small class="text-danger" *ngIf="email.errors.required">Email Id is required</small>
                        <small class="text-danger" *ngIf="email.errors.pattern">Enter the valid valid email id</small>
                    </div>
                </div>
            </div>
            <button [disabled]=" Registerform.form.invalid" type="submit" class="btn btn-primary">Register</button>
            <small class="float-right" [routerLink]="['/login']">Having an Account ? <a href="/login">Login</a>
                here</small>
        </form>

This is .ts file这是.ts文件

export class RegisterComponent implements OnInit {
user = new User();
  msg = "";
  roles: any = ['Admin', 'Employee'];
  constructor(private _service: RegistrationService, private _router: Router) { }

  ngOnInit(): void {
  }

  radioChangedHandler(event: any) {
    this.user.role = event.target.value;
  }

  registerUser() {

    this._service.registerUserFromRemote(this.user).subscribe(
      data => {
        console.log("response received");
        this.msg = "Registration Successful"
        this._router.navigate(['/login']);
      },
      error => {
        console.log("exception occured")
        // this.msg = error.error();
      }
    )

  }
}

This is User Class这是用户类

export class User {
    id: number | undefined;
    emailId: string | undefined;
    userName: string | undefined;
    password: string | undefined;
    cpassword: string | undefined;
    role: string | undefined;
    walletAmt: number | undefined;
    constructor() { }

}

I have tried to make an test case for component and email.But i'm getting "no expectation" error.我试图为组件和电子邮件制作一个测试用例。但是我收到了“没有期望”的错误。

This is my .spec file这是我的 .spec 文件

it('email should be correct', async () => {

        fixture.whenStable().then(() => {
            let email = component.user.emailId;
            email = "abc@gmail.com";
            expect(email).toBeTruthy();
            
            
        });

    })
    it('email should be false', async () => {
        fixture.whenStable().then(() => {
            let email = component.user.emailId;
            let val = component.registerUser()
            email = '';

            expect(email).toBeFalsy();
        });
    })

the expectations are inside unreachable code.期望在无法访问的代码中。 then callback with such approach would be executed after the test is finished. then在测试完成后执行这种方法的回调。 You can leverage very convenient await syntax to make it reachable.您可以利用非常方便的await语法使其可访问。

it('email should be correct', async () => {
   await fixture.whenStable();

   let email = component.user.emailId;
   expect(email).toBeTruthy();
})
    
it('email should be false', async () => {
   await fixture.whenStable();

   let val = component.registerUser()
   let email = component.user.emailId;
   expect(email).toBeFalsy();
})

While looking into the test code it is not that easy to grasp what is tested.在查看测试代码时,掌握所测试的内容并不容易。

PS: template-driven forms are not playing well with unit tests. PS:模板驱动的表单在单元测试中表现不佳。 And in general, this approach is less powerful than reactive forms.总的来说,这种方法不如反应式形式强大。 I would rather avoid attempts to cover those with tests and invest time in learning reactive forms.我宁愿避免尝试用测试来覆盖那些并花时间学习反应式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Karma-Jasmine for.sort() 中的单元测试故障排除 Angular 中的 function - Unit Testing Troubleshoot in Karma-Jasmine for .sort() function in Angular 测试角度模板驱动的表单 - testing angular template driven forms 管道 DatePipe 的 Angular karma-jasmine 失败 - Angular karma-jasmine failing for pipe DatePipe 使用 Karma-Jasmine 初始化 Angular 应用程序 - Angular app initialization with Karma-Jasmine 无法在angular 6项目中使用Karma-jasmine测试工具测试动态内容 - Unable to test the dynamic content using Karma-jasmine testing tool in angular 6 project Angular 单元测试:Karma-Jasmine:('onChange',(changeEvent:MatRadioChange):void 类型的参数不可分配给类型的参数 - Angular Unit Testing : Karma-Jasmine : ('onChange', (changeEvent: MatRadioChange) : Argument of type void is not assignable to parameter of type Angular Karma Jasmine 测试表单验证错误 - Angular Karma Jasmine Testing form validation error 如何修复 ChangeDetectorRef 没有提供程序! 在业力茉莉花测试 - How to fix No provider for ChangeDetectorRef! in Karma-Jasmine Testing Typeerror无法读取Karma-Jasmine测试中未定义的属性“ triggereventhandler” - Typeerror cannot read property 'triggereventhandler' of undefined in Karma-Jasmine testing Angular Karma-Jasmine无法读取未定义的属性“ get” - Angular Karma-Jasmine Cannot read property 'get' of undefined
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM