javascript - 测试 Angular 6 中的登录组件

标签 javascript html angular angular6 karma-jasmine

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

第1步:登录.组件(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步:登录.组件(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')})}
    );
   }

}

代码运行良好

我已经尝试过以下测试,但我还想测试两种方法,即 用户身份验证(用户名,密码) 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 。通过这种方式,您可以完全控制服务中的函数返回的内容,以测试组件对不同情况的 react 。

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

关于javascript - 测试 Angular 6 中的登录组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54646267/

相关文章:

javascript - 如何在 Meteor 中创建自定义登录字段?

html - 图片库代码问题

javascript - Angular2 - 在用户更改后重置选择的值

ios - mac 终端上的 cordova 权限被拒绝

javascript - HTML base href 和 A​​ngular APP_BASE_HREF 有什么区别?

Javascript:使用addEventListener时如何在函数中放置参数?

javascript - Jquery ID申请

javascript - 如何正确使用Vue插件? <插件名称> 未定义

javascript - Scriptaculous 排序和句柄的问题(元素排序不正确)

PHP重复输出