测试登录组件 [英] Testing Login Component
本文介绍了测试登录组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要你支持我的问题。我想测试我的登录应用。
I need your support for my question please. I want to test my Login app.
- 我的项目是Angular 5,Jasmine2.6.4
- 登录系统我请遵循以下代码:
Step1。 Html组件
Step1. Html Component
<div id="container">
<div id="login_card_container">
<div id="login_card" class="card col s12">
<form [formGroup]="loginForm" (ngSubmit)="onLogin()" class="col s12">
<h1 id="form_title">Login</h1>
<div class="row">
<div class="input-field col s12">
<input formControlName="username" id="username" type="text" class="validate" [ngClass]="{invalid: invalidCredentials}">
<label for="username">Username</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input formControlName="password" id="password" type="password" class="validate" [ngClass]="{invalid: invalidCredentials}">
<label for="password" data-error="Your username/password combination is invalid">Password</label>
</div>
</div>
<div id="login_button_container" class="row">
<button id="login_button" type="submit" class="btn waves-effect waves-light" [disabled]="!loginForm.valid">
<i class="fa fa-sign-in left"></i>
Login
</button>
</div>
</form>
</div>
</div>
</div>
第2步:TS组件
onLogin() {
this.loading = true;
this.auth.loginByUsernameAndPassword(
this.loginForm.controls['username'].value,
this.loginForm.controls['password'].value)
.subscribe(
result => {
if (result === true) {
this.router.navigate(['/']);
} else {
this.loading = false;
this.invalidCredentials = true;
}
},
error => {
this.loading = false;
this.invalidCredentials = true;
}
);
}
步骤3.服务
export class AuthService {
private static readonly CURRENT_USER = 'currentUser';
constructor(private http: Http, private router: Router) {
this.currentUser = this.loadCurrentUser();
}
public loginByUsernameAndPassword(username: string, password: string): Observable<boolean> {
let urlSearchParams = new URLSearchParams();
urlSearchParams.append('username', username);
urlSearchParams.append('password', password);
urlSearchParams.append('user_uniqueIdid', '0');
urlSearchParams.append('session_id', '0');
let body = urlSearchParams.toString();
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
return this.http.post(Api.getUrl(Api.URLS.Login), body, {
headers: headers
})
.map((response: Response) => {
let res = response.json();
if (res.StatusCode === 0 && res.Token) {
this.currentUser = {
username: username,
token: res.Token,
role: res.StatusDescription.Role
}
localStorage.setItem(AuthService.CURRENT_USER, JSON.stringify(this.currentUser));
return true;
}else {
return false;
}
});
}
public isAuthenticated(): boolean {
let currentUser: any = localStorage.getItem(AuthService.CURRENT_USER);
if (currentUser !== null) {
try {
currentUser = JSON.parse(currentUser);
if (!currentUser.username !== undefined &&
!currentUser.token !== undefined &&
!currentUser.permission !== undefined) {
return true;
}
} catch (ex) {
}
}
return false;
}
public getCurrentUser(): any {
return this.currentUser;
}
private loadCurrentUser(): any {
let currentUser: any = localStorage.getItem(AuthService.CURRENT_USER);
if (currentUser !== null) {
try {
currentUser = JSON.parse(currentUser);
if (!currentUser.username !== undefined &&
!currentUser.token !== undefined &&
!currentUser.permission !== undefined) {
return currentUser;
}
} catch (ex) {
}
}
return null;
}
}
此代码工作完美,如何测试这个?
This code work perfect, how to testing this?
这是我的第一次尝试,但非常差。
This is my first attempt, but is very poor.
仅显示:执行0 0错误(0.04秒/ 0秒)
Only show: Executed 0 of 0 ERROR (0.04 secs / 0 secs)
describe('Component: Login', () => {
let comp: LoginComponent
let fixture: ComponentFixture<LoginComponent>;
let de: DebugElement;
let el: HTMLElement;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [LoginComponent],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
RouterTestingModule
]
}).compileComponents().then(() => {
fixture = TestBed.createComponent(LoginComponent);
comp = fixture.componentInstance;
de = fixture.debugElement.query(By.css('form'));
el = de.nativeElement;
});
}));
});
更新:
此代码成功,但我无法发布用户名和密码。如何发布和用户名:'用户'密码:'123'?
This code is successful, but I can't post username and password. How to post and username: 'user' password:'123' ?
describe('Component: Login', () => {
let component: LoginComponent;
let fixture: ComponentFixture<LoginComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ReactiveFormsModule, FormsModule, HttpModule, RouterTestingModule],
declarations: [LoginComponent],
providers: [AuthService],
});
fixture = TestBed.createComponent(LoginComponent);
component = fixture.componentInstance;
component.ngOnInit();
});
it('should call auth login method', async(() => {
let loginElement: DebugElement;
let debugElement = fixture.debugElement;
let authService = debugElement.injector.get(AuthService);
let loginSpy = spyOn(authService, 'loginByUsernameAndPassword').and.callThrough();
loginElement = fixture.debugElement.query(By.css('form'));
loginElement.triggerEventHandler('ngSubmit', null);
expect(loginSpy).toHaveBeenCalledTimes(1);
}));
});
推荐答案
你可以测试你的服务方法是这样调用的:
you can test that your service method is called like this :
it('should call auth login method', async(() => {
let loginElement: DebugElement;
const debugElement = fixture.debugElement;
authService = debugElement.injector.get(AuthService);
loginSpy = spyOn(authService , 'loginByUsernameAndPassword').and.callThrough();
loginElement = fixture.debugElement.query(By.css('form'));
// to set values
component.loginForm.controls['username'].setValue('user');
component.loginForm.controls['password'].setValue('123');
loginElement.triggerEventHandler('ngSubmit', null);
expect(loginSpy).toHaveBeenCalledTimes(1); // check that service is called once
}));
这篇关于测试登录组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文