Currently, I am working on creating unit test cases in Angular 7 for a Component that utilizes an asynchronous service.
This is the content of my component file:
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);
}
}
}
Here is the unit test case:
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('<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a8c0c9dbc6c9c6c1e8dec1dbc0c9c486cbc7c5">[email protected]</a>');
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']);
})
));
Upon running the test case, the value of the result is as shown in this https://i.sstatic.net/CMof6.png image link.
During testing, an issue was identified where the code did not proceed through the section "if (result['token'])". I'm looking for suggestions on how to access or send the body part of the HTTP response from the unit test case without impacting the component.