Recently started unit testing in Angular with Jest and facing a challenge in testing whether the route is returning data or not. Is it possible to conduct unit testing to validate if data is being returned from the route in Angular? Any guidance would be greatly appreciated.
In my class component.ts
public data$: Observable<Data>;
public salariesPerHours: salariesPerHoursViewModel[];
private destroy$ = new Subject<boolean>();
constructor(private activatedRoute: ActivatedRoute) {}
public ngOnInit(): void {
this.data$ = this.activatedRoute.data;
this.data$?.pipe(takeUntil(this.destroy$)).subscribe((data: Data) => {
this.salariesPerHours= data?.Salary?.salaryPerHour;
});
}
In test class compontent
import { ActivatedRoute, Data } from '@angular/router';
import { salariesPerHoursViewModel, SalaryType } from 'lib/store/store.barrel';
import { Subject } from 'rxjs';
import { SalaryComponent } from './salary.component';
const dataMock: salariesPerHoursViewModel[] = [
{
year:2018,
salaryModifications:[
{
date:'2018-02-01T00:00:00',
type: 'Salary',
action:[
{
logical :'0212834',
label:''
}
]
},
]
}
]
describe('SalaryComponent', () => {
let component: SalaryComponent;
let activatedRoute: ActivatedRoute;
beforeEach(() => {
activatedRoute = new ActivatedRoute();
component = new SalaryComponent(activatedRoute);
});
describe('ngOnInit', () => {
beforeEach(() => {
jest.spyOn(component, 'ngOnInit');
});
//need help here on how to verify if data is returned
});
describe('ngOnDestroy', () => {
test('should complete the destroy observable', () => {
component['destroy$'].next = jest.fn();
component['destroy$'].complete = jest.fn();
component.ngOnDestroy();
expect(component['destroy$'].next).toHaveBeenCalledWith(true);
expect(component['destroy$'].complete).toHaveBeenCalled();
});
});
});