2017-11-27 15 views
0

login.component.ts :각도-CLI 재스민 단위 테스트 방법을 감시하는 방법

@Component({ 
    selector: 'app-login', 
    templateUrl: './login.component.html', 
    styleUrls: ['./login.component.css'] 
}) 
export class LoginComponent implements OnInit { 

    loginForm: FormGroup; 
    email: AbstractControl; 
    password: AbstractControl; 
    isError: boolean; 
    errorMessage: string; 
    constructor(public loginService: LoginService, fb: FormBuilder, public router: Router, public helperService: HelperService) { 
    this.loginForm = fb.group({ 
     'email': ['', Validators.compose([Validators.required, Validators.email, Validators.minLength(4), Validators.maxLength(50)]) 
     ], 
     'password': ['', Validators.compose([Validators.required, AppValidator.digitsOnly, Validators.minLength(4), Validators.maxLength(50)]) 
     ] 
    }); 
    } 
    this.email = this.loginForm.controls['email']; 
this.password = this.loginForm.controls['password']; 
    ngOnInit() { } 

    onLogin(loginForm: LoginForm): void { 
    this.isError = false; 
    if (this.loginForm.valid) { 
     // if email='[email protected]'& password='123456', login will success else it will fail. 
     this.loginService.fakeLogin(loginForm) 
     .subscribe((res: LoginResponse) => { 
      const url = '/dashboard'; 
      this.router.navigate([url]); 
     }, 
     (err: ErrorResponse) => { 
      this.errorMessage = err.message; 
      this.isError = true; 
     }); 
    } 
    } 
} 

login.component.html :

<div class="login"> 
    <h1>Login</h1> 
    <p *ngIf="isError"> 
     <ngb-alert [type]="'danger'" [dismissible]="true" (close)="closeAlert()">{{ errorMessage }}</ngb-alert> 
    </p> 
    <form method="post" [formGroup]="loginForm" (ngSubmit)="onLogin(loginForm.value)"> 
     <div class="form-group row" [ngClass]="helperService.getInputValidationClass(loginForm,'email')"> 
      <div class="col-sm-12"> 
       <input [formControl]="email" type="text" class="form-control" id="email" placeholder="Email"> 
       <span *ngIf="helperService.showCtrlValidationMsg(loginForm,'email')" class="help-block sub-little-text text-danger">{{helperService.getCtrlValidationMsg(loginForm,'email')}}</span> 
      </div> 
     </div> 
     <div class="form-group row" [ngClass]="helperService.getInputValidationClass(form,'password')"> 
      <div class="col-sm-12"> 
       <input [formControl]="password" type="password" class="form-control" id="password" placeholder="Password"> 
       <span *ngIf="helperService.showCtrlValidationMsg(loginForm,'password')" class="help-block sub-little-text text-danger">{{helperService.getCtrlValidationMsg(loginForm,'password')}}</span> 
      </div> 
     </div> 
     <button type="submit" [disabled]="helperService.isFormSubmitDisabled(loginForm,helperService.isProcessing)" class="btn btn-primary btn-block btn-large login-submit"> 
      <span >Sign in</span><span *ngIf="helperService.isProcessing">Processing...<i class="fa fa-spinner fa-spin fa-fw" aria-hidden="true"></i></span> 
     </button> 
    </form> 
</div> 

login.component.spec .ts :

import { By } from '@angular/platform-browser'; 
import { LoginService } from './login.service'; 
import { async, ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing'; 
import { FormsModule, ReactiveFormsModule } from '@angular/forms'; 
import { SlimLoadingBarModule } from 'ng2-slim-loading-bar'; 
import { SlimLoadingBarService } from 'ng2-slim-loading-bar'; 
import { RouterTestingModule } from '@angular/router/testing'; 

import { LoginComponent } from './login.component'; 
import { HelperService } from '../shared/helper.service'; 
import { NgbAlertModule } from '@ng-bootstrap/ng-bootstrap/alert/alert.module'; 
import { NgbAlertConfig } from '@ng-bootstrap/ng-bootstrap/alert/alert-config'; 

describe('LoginComponent',() => { 
    let component: LoginComponent; 
    let fixture: ComponentFixture<LoginComponent>; 

    beforeEach(async(() => { 
    TestBed.configureTestingModule({ 
     imports: [FormsModule, ReactiveFormsModule, RouterTestingModule, NgbAlertModule,], 
     declarations: [LoginComponent], 
     providers: [LoginService, HelperService, NgbAlertConfig,], 
    }).compileComponents(); 
    })); 

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

    function updateForm(loginFormValue) { 
    component.loginForm.controls['email'].setValue(loginFormValue.email); 
    component.loginForm.controls['password'].setValue(loginFormValue.password); 
    }  

    it('isError should be true when password is wrong', fakeAsync(() => { 
    const loginFormValue = { 
     email: '[email protected]', 
     password: '123', // give wrong password 
    }; 
    updateForm(loginFormValue); 
    fixture.debugElement.query(By.css('.login-submit')).triggerEventHandler('ngSubmit', null); 
    tick(); // wait for async operations 
    expect(component.isError).toBeTruthy(); 
    })); 

    it('onLogin should be called', fakeAsync(() => { 
    spyOn(component, 'onLogin'); 
    const loginFormValue = { 
     email: '[email protected]', 
     password: '123456', 
    }; 
    updateForm(loginFormValue); 
    fixture.debugElement.query(By.css('.login-submit')).triggerEventHandler('ngSubmit', null); 
    expect(component.onLogin).toHaveBeenCalledWith(loginFormValue); 
    })); 
}); 
내 테스트 케이스

모두 실패 :

  1. 는 (암호가 잘못된 경우 LoginComponent ISERROR 사실이해야하는) : truthy로 정의되지 않은 예상.
  2. (LoginComponent onLogin를 호출한다) : 예상 스파이 onLogin가 호출 된 것으로 [객체 ({이메일 : '[email protected]', 비밀번호 : '12345'})]하지만이 호출되지 않았다. 내가 잘못 여기

를하고있는 중이 야 정확히 무엇?

답변

0

두 결과 모두에서 onLogin이 호출되지 않음을 보여줍니다.

fixture.debugElement.query(By.css('.login-submit')).triggerEventHandler('ngSubmit', null); 

내가 사용합니다 :

fixture.debugElement.query(By.css('.login-submit')).click(); 

아마 다른 방법을 ngSubmit 이벤트를 트리거하는 것입니다 :

fixture.debugElement.query(By.css('.login-submit')).dispatchEvent(new Event('ngSubmit')); 

비록 내가 천국 내 의심이 라인이 작동하지 않는 것입니다 ngSubmit 이벤트로 시도했지만 다른 이벤트에서도 작동합니다.