While working on my project, I encountered a situation where I needed to define an inner function and assign it to a class variable for future use. The reason behind this decision was to have access to the parent function's arguments without granting access to that data to other methods within the class.
@Component({
selector: 'app-report-topup',
templateUrl: './report-topup.component.html',
styleUrls: ['./report-topup.component.scss'],
})
export class ReportTopupComponent implements OnInit {
loadReports: (pageNum, pageSize) => void;
reportDataSource: ReportDataSource;
currentPageDetails: { index: number; size: number } = { index: 0, size: 5 };
constructor(public topupHttpService: TopupHttpService){}
ngOnInit(): void {
this.reportDataSource = new ReportDataSource(this.topupHttpService);
}
onReportTopupSearchFormSubmit(formData: ReportTopupSearch) {
this.loadReports = (pageNum, pageSize) => {
this.reportDataSource.loadReports();
};
this.loadReports(0, this.currentPageDetails.size);
this.setCurrentPageDetails(0 , this.currentPageDetails.size);
}
Although the code seems to be working fine, I encountered some issues while testing it. Here's a snippet of my spec.ts function:
it('should call load Reports and setCurrentPageDetails on form submit', () => {
spyOn(component, 'setCurrentPageDetails');
const reportFormData: ReportTopupSearch = {
company: 'ABC',
dateFrom: '2021-01-01',
dateTo: '2021-01-02',
status: 'new',
};
component.onReportTopupSearchFormSubmit(reportFormData);
expect(component.loadReports).toBeDefined();
expect(component.loadReports).toHaveBeenCalled();
expect(component.setCurrentPageDetails).toHaveBeenCalled();
});
When attempting to use `spyOn` from jasmine, the test runner throws an error. Refer to this image for details: https://i.sstatic.net/5eD7q.png
If I switch to using `jasmine.createSpy` as shown below:
component.loadReports = jasmine.createSpy('load reports spy' , () => {});
I encounter the error "Expected spy but got a function". Refer to this image for more information: https://i.sstatic.net/ZyOj5.png
I'm currently stuck on how to resolve this issue and properly test whether `component.loadReports()` has been called. The spy for the `setCurrentPageDetails()` method seems to be working fine because it's a method of the class. Any assistance would be greatly appreciated.