作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在 Angular 7 中为 Component with async service 创建单元测试用例。
这是我的组件文件:
submitLoginForm() {
if (this.loginForm.valid) {
// send a http request to save this data
this.guestUserService.login(this.loginForm.value).subscribe(
result => {
// if (result) {
if (result['token']) { // The value of result is coming the complete HttpResponse.
localStorage.setItem('authToken', result['token']);
this.router.navigate(['/dashboard']);
}
},
error => {
console.log('error', error.message);
this.router.navigate(['/error']);
}
);
} else {
this.validateAllFields(this.loginForm);
}
}
}
单元测试用例:
fdescribe('LoginComponent', () => {
let component: LoginComponent;
let fixture: ComponentFixture<LoginComponent>;
let guestUserService: any;
let guestUserServiceSpy: any;
beforeEach(async(() => {
guestUserService = jasmine.createSpyObj('GuestUserService', ['login']);
TestBed.configureTestingModule({
declarations: [LoginComponent, ErrorComponent, RegistrationComponent],
imports: [
ReactiveFormsModule,
FormsModule,
RouterTestingModule,
HttpClientModule,
AppRoutingModule,
],
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true },
{ provide: APP_BASE_HREF, useValue: '/' },
{ provide: GuestUserService, useValue: guestUserService }]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(LoginComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should Successfully Submit Registration Form', async(inject([Router], (router) => {
guestUserServiceSpy = guestUserService.login.and.returnValue(of(new HttpResponse({ status: 200, body: { result: { token: 'DummyTokenIsSent' } } })));
spyOn(router, 'navigate');
spyOn(component, 'submitLoginForm').and.callThrough();
component.loginForm.controls['username'].setValue('hasnani@vishal.com');
component.loginForm.controls['password'].setValue('12345678');
component.submitLoginForm();
expect(component.submitLoginForm).toHaveBeenCalled();
expect(component.loginForm.invalid).toBe(false);
expect(guestUserService).toBeDefined();
expect(guestUserServiceSpy).toBeDefined();
expect(guestUserServiceSpy).toHaveBeenCalledTimes(1);
expect(router.navigate).toHaveBeenCalled();
expect(router.navigate).toHaveBeenCalledWith(['/dashboard']);
})
));
运行测试用例时的结果值:
我发现错误来了,因为代码没有经过这部分“如果(结果[' token '])”但是如何在不影响组件部分的情况下访问或发送 http 响应表单单元测试用例的正文部分。
最佳答案
使用 HttpClientTestingModule
作为导入并模拟您的 http 响应:
httpMock = injector.get(HttpTestingController);
const req = httpMock.expectOne(`path`);
expect(req.request.method).toBe("GET");
req.flush({fakeresponse:true);
关于javascript - Angular 7 : How to access/send only body part of HTTP Response from test case,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56750487/
我是一名优秀的程序员,十分优秀!