I am having real issue with my tests for FileReader. i mock the FileReader and trying To test if It has been called when onChange event is triggered. I have tried to write tests for method that call on OnLoad event of File Reader.
.ts File
reader = new FileReader();
readFileOnChange(files: any) {
if (files && files.length > 0) {
const file: File = files.item(0);
if (file.type == "text/csv") {
this.reader.readAsText(file, "UTF-8");
this.reader.onload = (e) => { this.parse()}
}
}
}
Spec.ts
describe('AppComponent', () => {
let mockFile = new File(['testData'], 'filename.csv', { type: 'text/csv' });
let mockEvt = { target: { files: [mockFile] } };
let mockReader: FileReader = jasmine.createSpyObj('FileReader', ['readAsText',
'onload']);
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [ AppComponent ],
providers: [],
imports: [HttpClientTestingModule, BrowserDynamicTestingModule],
}).compileComponents();
component = fixture.componentInstance;
fixture.detectChanges();
spyOn(component, 'readFileOnChange').and.callThrough();
}));
it('should call parse on onLoad of FileReader', () => {
spyOn(window, 'FileReader').and.returnValue(mockReader);
component.readFileOnChange(mockEvt as any);
expect(window.FileReader).toHaveBeenCalled();
expect(component.parse).toHaveBeenCalled();
});
})
gives Error:
Expected spy FileReader to have been called.
Please help Thank you