I'm trying to write the unit testing for the file upload method (not integrated with API yet) in angular. Can someone help me on adding mock files and to get the full code coverage without errors pls?
onFileUpload(event) {
this.successMsg = '';
this.errorMsg = '';
this.sheetJsExcelName = event.target.files.item(0).name;
const target : DataTransfer = <DataTransfer>(event.target);
const reader : FileReader = new FileReader();
reader.onload = (e : any) => {
const bstr : string = e.target.result;
const wb: XLSX.WorkBook = XLSX.read(bstr, { type: 'binary'});
const wsname: string = wb.SheetNames[1];
const ws: XLSX.WorkSheet = wb.Sheets[wsname];
this.data = (XLSX.utils.sheet_to_json(ws, { header: 1 }));
if(this.data.length > 20) {
this.errorMsg = "Record limit is exceeding";
} else {
setTimeout(() => {
this.successMsg = this.sheetJsExcelName + " is uploaded succesfully";
}, 5000);
}
}
reader.readAsBinaryString(target.files[0]);
}
// in spec file
it('should detect file input change', () => {
component.onFileUpload('Upload.xlsx');
fixture.detectChanges();
expect(data.length).toBeLessThanOrEqual(20);
expect(component.sheetJsExcelName).toBeTruthy()
expect(component.sheetJsExcelName).toBe('Upload.xlsx')
})
<input type="file" (change)="onFileUpload($event)" accept=".xlsx" multiple="false" style="display: none;">Bulk Upload