测试总是失败,因为login.subscribe错误没有error.status error.status - >'undefined'测试:
it('form submit fail', () => {
expect(element.querySelector('#login-email')).toBeDefined();
expect(element.querySelector('#login-password')).toBeDefined();
updateForm('[email protected]', '123456');
component.login(component.loginForm);
httpMock
.expectOne(`${environment.apiProtocol}://${environment.apiHost}/auth`)
.error( new ErrorEvent( 'SOME_ERROR', {error: 400}), {status: 400, statusText: ''});
httpMock.verify();
expect(component.hasError).toBeTruthy();
expect(component.error).toEqual('unregisteredPair');
});
component.login:
login(form: FormGroup): void {
if (this.lockForm) {
return;
}
if (!form.valid) {
Object.keys(form.controls).forEach(key => {
form.get(key).markAsTouched();
});
this.lockForm = false;
return;
}
this.lockForm = true;
this.hasError = false;
this.error = '';
this.loading = true;
this.service.login(form.value.email, form.value.password).subscribe(() => {
this.router.navigate([this.service.redirectUrl || '/dashboard']);
this.loading = false;
}, (error: any) => {
this.hasError = true;
this.lockForm = false;
this.error = error.status === 400 ? 'unregisteredPair' : error.error.localizationKey;
this.loading = false;
});
}
在这个测试结束时得到错误:
TypeError:无法读取未定义的属性“localizationKey”
这发生了然后状态!= 400
使用spyOn解决了这个问题
spyOn类似于httpMock(但是为了调用一些函数),这是一个例子:
it('form submit fail', () => {
email.value = '[email protected]';
email.dispatchEvent(new Event('input'));
password.value = '123456';
password.dispatchEvent(new Event('input'));
spyOn(service, 'login').and
.returnValue(
Observable.throw(
new HttpErrorResponse({
error: {
message: 'Here some message...',
localizedKey: 'someKey'
},
status: 500
})
)
);
button.click();
expect(component.hasError).toBeTruthy();
expect(component.lockForm).toBeFalsy();
expect(component.error).toEqual('someKey');
});
在此示例中,spyOn模拟来自AuthService.login()的响应(在调用时)并返回单元测试的预期响应
对于成功响应,使用Observable.of()和新的HttpResponse()
手动打电话给fixture.detectChanges()
it('form submit fail', () => {
fixture.detectChanges();
expect(element.querySelector('#login-email')).toBeDefined();
expect(element.querySelector('#login-password')).toBeDefined();
updateForm('[email protected]', '123456');
component.login(component.loginForm);
httpMock
.expectOne(`${environment.apiProtocol}://${environment.apiHost}/auth`)
.error( new ErrorEvent( 'SOME_ERROR', {error: 400}), {status: 400, statusText: ''});
httpMock.verify();
expect(component.hasError).toBeTruthy();
expect(component.error).toEqual('unregisteredPair');
});