繁体   English   中英

在Angular 6中测试登录组件

[英]Testing the Login component in Angular 6

我想使用Jasmine测试我的登录页面

步骤1:Sign-in.component(HTML组件)

<form [formGroup]="adminLogin" class="col s12 white" (ngSubmit)="OnSubmit()">
    <div class="row">
        <div class="input-field col s12">
          <i class="material-icons prefix">account_circle</i>
          <input type="text" name="UserName" formControlName="UserName" placeholder="Username" required>
        </div>
      </div>
      <div class="row">
         <div class="input-field col s12">
           <i class="material-icons prefix">vpn_key</i>
           <input type="password" name="Password" formControlName="Password" placeholder="Password" required>
         </div>
       </div>
       <div class="row">
           <div class="input-field col s12">
             <button class="btn-large btn-submit" type="submit">Login</button>
           </div>
         </div>
   </form>

步骤2:Sign-in.component(TSComponent)

import { Component, OnInit } from '@angular/core';
import { UserService } from 'src/app/shared/user.service';
import { Router } from '@angular/router';
import { HttpErrorResponse } from '@angular/common/http';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-sign-in',
  templateUrl: './sign-in.component.html',
  styleUrls: ['./sign-in.component.scss']
})
export class SignInComponent implements OnInit {
  isLoginError : boolean = false;
  constructor(private userService : UserService,private router : Router, private fb : FormBuilder) { }

  adminLogin : FormGroup;
  ngOnInit() {
    this.adminLogin =  this.fb.group({
      UserName: ['', Validators.nullValidator],
      Password: ['', Validators.nullValidator]
    })
  }


  OnSubmit(){
    console.log(this.adminLogin.value);
    const userName = this.adminLogin.value.UserName;
    const password = this.adminLogin.value.Password;
    this.userService.userAuthentication(userName,password).subscribe((data : any)=>{
      localStorage.setItem('userToken',data.access_token);
      this.router.navigate(['/home']);
    },
    (err : HttpErrorResponse)=>{
      this.isLoginError = true;
    });
  }

}

步骤3:服务组件

import { Injectable } from '@angular/core';
import { HttpClient, HttpResponse, HttpHeaders } from '@angular/common/http';
import { HttpClientModule } from '@angular/common/http';
import {Observable} from 'rxjs';
import { User } from './user.model';

@Injectable()
export class UserService {
  readonly rootUrl = 'http://localhost:54804';
  constructor(private http: HttpClient) { }


  userAuthentication(userName, password) {
    var data = "username=" + userName + "&password=" + password + "&grant_type=password";
    var reqHeader = new HttpHeaders({ 'Content-Type': 'application/x-www-urlencoded','No-Auth':'True' });
    return this.http.post(this.rootUrl + '/token', data, { headers: reqHeader });
  }

  getUserClaims(){
    return  this.http.get(this.rootUrl+'/api/GetUserClaims'
    ,{headers : new HttpHeaders({'Authorization' : 'Bearer '+localStorage.getItem('userToken')})}
    );
   }

}

代码效果很好

我已经尝试过下面的测试,但我也想测试两个方法,即userAuthentication(userName,password)getUserClaims()

谁能帮忙吗?

import { async, ComponentFixture, TestBed, fakeAsync } from '@angular/core/testing';
import{ BrowserModule, By}from '@angular/platform-browser'
import { SignInComponent } from './sign-in.component';
import { FormsModule } from '@angular/forms';
import { UserService } from 'src/app/shared/user.service';
import { HttpClientModule } from '@angular/common/http';
import { Router } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { by } from 'protractor';
import { ReactiveFormsModule } from '@angular/forms';



describe('SignInComponent', () => {
  let component: SignInComponent;
  let fixture: ComponentFixture<SignInComponent>;
  let el: HTMLElement;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ SignInComponent ],
      imports: [FormsModule, HttpClientModule, RouterTestingModule,ReactiveFormsModule],
      providers: [UserService]
    })
    .compileComponents();
  }));

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

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('Should set submitted to true', async(() => {
     component.OnSubmit();
     expect(component.OnSubmit).toBeTruthy();

  }));

  it('Should call the OnSubmit method', () =>{ fakeAsync(() =>{
    fixture.detectChanges();
    spyOn(component,'OnSubmit');
    el=fixture.debugElement.query(By.css('Login')).nativeElement;
    el.click();
    expect(component.OnSubmit).toHaveBeenCalledTimes(0);
  })

  });

  it('Form should be invalid', async(()=> {
    component.adminLogin.controls['UserName'].setValue('');
    component.adminLogin.controls['Password'].setValue('');
    expect(component.adminLogin.valid).toBeFalsy();
  }));

  it('Form should be valid', async(()=> {
    component.adminLogin.controls['UserName'].setValue('admin');
    component.adminLogin.controls['Password'].setValue('admin123');
    expect(component.adminLogin.valid).toBeTruthy();
  }));

});

看来您正在为SignInComponent( sign-in.component.spec.ts ?)编写测试。 检查AuthService中的功能是否正常工作不是测试的责任。

  • 测试组件时,您不应在sign-in.component.spec.ts提供真实的AuthService,而应提供一个模拟。 检查以下链接以了解执行此操作的不同方法: https : //angular.io/guide/testing#component-with-a-dependency 通过这种方式,您可以完全控制服务中的哪些功能返回,以测试组件在不同情况下的反应。

  • 您应该创建一个新文件user.service.spec.ts ,它将专门测试UserService中的两个功能。 Angular提供了HttpTestingModule来测试HTTP请求,您可以在这里查看它: https ://angular.io/guide/http#testing-http-requests。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM