I am trying to write a unit test case for service inside Promise, I can able to execute promise call, but can't able to execute inside services, Also in code coverage report, it shows code is not covered for promise line. Please tell me where I am doing wrong.
The below file is our usercomponent.component.ts.
import {Component, OnInit} from '@angular/core';
import {UserService} from "../services/user.service";
@Component({
selector: 'user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
constructor(private userService: UserService) {}
getToken(){
return new Promise(function(resolve,reject){
if(this.token){
resolve(this.token);
}else{
this.userService.getToken().subscribe((data)=>{
resolve(data.token);
},
error: (error) => {
reject(error)
},
)
}
})
}
}
The below file is our user.component.spec.ts file
import {UserComponent} from './user.component';
import {async, ComponentFixture, fakeAsync, TestBed, tick} from '@angular/core/testing';
import {of} from 'rxjs';
import {UserService} from "../services/user.service";
class MockUserClass{
getToken(){ return new Observable()}
}
describe('UserComponent', () => {
const fixture;
const component;
beforeEach(
wairForAsync(()=>{
Test.Bed.configureTestingModule({
declarations: [UserComponent],
providers: [{{provide:UserService,useClass:MockUserClass}]
}).compileComponents();
});
)
beforeEach(()=>{
fixture = TestBed.createComponent(UserComponent);
component = fixture.componentInstance;
fixture.detectChanges();
})
it(`should call getToken method`,fakeAsync(()=>{
const spy = spyOn(component,'getToken').and.returnValue(Promise.resolve('token'));
const spyOnService = sppyOn(component.userService, 'getToken').and.returnValue(of(mockData))
component.getToken();
tick();
expect(spy ).toHaveBeenCalled();
expect(spyOnService).toHaveBeenCalled();
}));
});
you are making a spy:
const spy = spyOn(component,'getToken').and.returnValue(Promise.resolve('token'));.
Then, when you call this method, it will return your fake promise. So it won't call your service, it will only return your mocked promise. So this code does not make any sense:
component.getToken();
expect(spy).toHaveBeenCalled();
The expect() statement will always be true, since you call it manually. Try removing this spy first:
// const spy = spyOn(component,'getToken').and.returnValue(Promise.resolve('token'));
const spyOnService = spyOn(component.userService, 'getToken').and.returnValue(of(mockData))
component.getToken();
tick();
// expect(spy ).toHaveBeenCalled();
expect(spyOnService).toHaveBeenCalled();