预期未定义是真实的-茉莉花/业力

时间:2018-08-09 04:20:43

标签: angular karma-jasmine

我已经用角度2开发了一个简单的反应形式,其中包括用户名,密码和登录按钮。这里的按钮默认禁用以获取电子邮件和密码值。在这里,我试图为按钮启用和禁用编写一个测试用例(如果我们将输入数据提供给两个字段,则按钮应启用,否则按钮将禁用)。 我已经编写了一个测试用例,例如“应禁用按钮”,期望它会通过,但是它失败,并显示错误“错误:期望未定义是真实的。”

这是我的反应形式:

<nb-card *ngIf="!loading" >
    <nb-card-header>
        <i class="fa fa-lock"></i>Sign In Form </nb-card-header>
    <nb-card-body>
        <form [formGroup]="authForm" (ngSubmit)="onLogin()" >
            <input id="userid" type="text" class="bx--text-input" placeholder="EOSE Userid" 
            formControlName="userid" [attr.data-invalid]="useridMessage ? '' : null"/> 

            <div class="bx--form-requirement" *ngIf="useridMessage">{{ useridMessage }} </div>  
              <br>
            <input id="password" type="password" class="bx--text-input" placeholder="EOSE Password" 
            formControlName="password" [attr.data-invalid]="passwordMessage ? '' : null"/> 
            <div class="bx--form-requirement" *ngIf="passwordMessage" >{{ passwordMessage }} </div>

           <br>
            <carbon-button type="primary" [disabled]="!authForm.valid">Sign In</carbon-button>  
        </form> 
    </nb-card-body>  
</nb-card>

这是我的.spec文件。

beforeEach(() => {
    fixture = TestBed.createComponent(LoginFormComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create the app', async(() => {
    const fixture = TestBed.createComponent(LoginFormComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  }));
  it('Button should be disable', async(() => {
    component.authForm.controls['userid'].setValue('');
    component.authForm.controls['password'].setValue('');
    fixture.detectChanges();
    let btn = fixture.debugElement.query(By.css('carbon-button'));  
    expect(btn.nativeElement.disabled).toBeTruthy(); 
  }));

这是.ts文件

import { Component, OnInit} from '@angular/core';
import { AbstractControl, FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';
import { ActionLoadModule } from '../../../@core/auth/auth.reducer';
import { Store } from '@ngrx/store';
import { AppState } from '../../../@models/app-state';
import { ActionSignIn, selectorLogin, ActionChangePassword } from '../../../@core/login/login.reducer';
import { LoginState } from '../../../@core/login/login.state';
import { BusyState } from '../../../@shared/busy-indicator/busy-state';

@Component({
  selector: 'eose-login-form',
  templateUrl: './login-form.component.html',
  styleUrls: ['./login-form.component.scss']
})
export class LoginFormComponent implements OnInit {

  dirty: true;
  // loading: BusyState;
  loading: boolean = false;
  loadingMsg: string = '';
  authForm: FormGroup;
  changeForm: FormGroup
  constructor(
    private store: Store<AppState>,
    private fb: FormBuilder
  ) {

  }

   userid = new FormControl('', [Validators.required, Validators.maxLength(8)]);
   password = new FormControl('', [Validators.required, Validators.maxLength(8)]);

  useridMessage: string;
  passwordMessage: string;


  handleLoadingChange(loadingState: BusyState) {
   // this.loading = loadingState;
  }
 private useridValidationMessage = {
        required: 'User id value is required.',
        maxlength: 'The maximum allowed length of user id is 8.'
 };
private passwordValidationMessages = {
    required: 'Password value is required.',
    maxlength: 'The maximum allowed length of password is 8.'
};

setMessage(c: AbstractControl): void {
    this.useridMessage = '';
    if ((c.dirty || c.touched) && c.errors) {
     this.useridMessage = Object.keys(c.errors).map(key =>
            this.useridValidationMessage[key]).join(' ');
    }
}
setpasswordMessage(c: AbstractControl): void {
    this.passwordMessage = '';
    if ((c.dirty || c.touched) && c.errors) {
        this.passwordMessage = Object.keys(c.errors).map(key =>
            this.passwordValidationMessages[key]).join(' ');
    }
}


ngOnInit() {

    this.authForm = this.fb.group({
      'env': new FormControl('cdtdevdir'),
      userid: this.userid,
      password: this.password
    });


  const useridControl = this.authForm.get('userid');
        useridControl.valueChanges.subscribe(value =>
            this.setMessage(useridControl));

    const passwordControl = this.authForm.get('password');
        passwordControl.valueChanges.subscribe(value =>
            this.setpasswordMessage(passwordControl));

  this.store.select(selectorLogin)
  .subscribe((loginState: LoginState) => {
    this.loading = loginState.loading;
    this.loadingMsg = loginState.loadingMsg;
  });

}


onLogin() {
   console.log('Login Payload', this.authForm.value);
   this.store.dispatch(new ActionSignIn(this.authForm.value));
   console.log('Where to save userid to get the Authstate')
   this.store.dispatch(new ActionLoadModule({userid: 'SOSMSV'}));
   this.onReset();
}


onReset() {
      console.log("Form Submitted!");
      this.authForm.get('password').setValue(null);
      this.changeForm.reset();
      this.authForm.removeControl('newpassword');
}

}

0 个答案:

没有答案