我想用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')})}
);
}
}
代码工作精细
我尝试过以下测试,但我也想测试两种方法,即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。