In my current project, I have a component that I am trying to write unit tests for. However, when I run the test, I noticed that the value of
console.log('**fav**' + favorite[`isFavorite`]);
shows up as undefined
. This indicates that the data I am trying to mock and return from the service is not being returned correctly. I believe that to properly test this, I need to mock the service and ensure that the data is returned so that handleData
is called and executed. Can you help me identify where I might be making a mistake?
ngOnInit(): void {
this.favoriteService.getData().subscribe(item => {
if (Object.keys(item).length) {
this.handleData(item);
}
});
}
handleData(favorite) {
console.log('**fav**' + favorite[`isFavorite`]);
if (favorite[`isFavorite`]) {
console.log('****1****');
// some logic
} else {
// some logic
}
}
Below is the content of my spec file:
describe('FavoritesComponent', () => {
let component: FavoritesComponent;
let fixture: ComponentFixture<FavoritesComponent>;
let stubFavoriteGatewaySpec: StubFavoriteGatewaySpec;
let spyFavoriteService: jasmine.SpyObj<FavoriteService>;
const favouriteData = [
{
tickerTypeName: 'Market Price',
type: 'MP',
headers: ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
data: [
[1, '1.020'],
[0, '-0.250'],
[-5, '-4.560'],
[-149, '-149.000'],
],
isFavorite: true,
}
];
beforeEach(async(() => {
stubFavoriteGatewaySpec = new StubFavoriteGatewaySpec();
spyFavoriteService = jasmine.createSpyObj('FavoriteService', [
'getData',
]);
spyFavoriteService.getData.and.returnValues(of(favouriteData));
TestBed.configureTestingModule({
imports: [MatExpansionModule],
declarations: [FavoritesComponent],
providers: [
{ provide: FavoritesGateway, useValue: stubFavoriteGatewaySpec },
{ provide: FavoriteService, useValue: spyFavoriteService },
],
})
.compileComponents()
.catch(console.log);
}));
beforeEach(async(() => {
fixture = TestBed.createComponent(FavoritesComponent);
component = fixture.componentInstance;
fixture.detectChanges();
}));
it('should create', () => {
expect(component).toBeTruthy();
});
});