In the ngOnInit
of my component I am defining the Filereader.onload
callback function. I found several solutions that say to mock the filereader and the onload but I think this defeats my purpose to test if the callback is correctly executed when onload is being called. So I tried to mock the onload Event and then test if the functions inside the callback get called.
it("should import data on filereader onload event", () => {
const fileReader = new FileReader();
let loadEvent: ProgressEvent<FileReader>;
spyOn(fileReader, "onload").and.callThrough();
spyOn(mockServiceOne, "convertData").and.returnValue(
mockData
);
spyOn(mockServiceTwo, "importData").and.callThrough();
fileReader.onload(loadEvent);
fixture.detectChanges();
expect(fileReader.result).toBeDefined();
expect(mockServiceOne.convertData).toHaveBeenCalled();
expect(mockServiceTwo.importData).toHaveBeenCalledTimes(1);
});
});
The function I am trying to test is this:
this.fileReader.onload = (event) => {
const jsonData = JSON.parse(event.target.result.toString());
const data = this.serviceOne.convertData(
jsonData
);
this.serviceTwo.importData(data);
};
I mocked the two services and methods inside them. But in the test spec they never get called. However the first assertion that the result of the onload event (event.target.result
) needs to be defined seems to check true.
Maybe there is a problem with the first line in the function that converts the data to json, since I am not actually giving the function a real file. However when I try to give anything other than the mocked ProgressEvent
it gives an error.
Please help me with testing the onload callback. Is it correct that I can't mock the filereader onload for this?
Aucun commentaire:
Enregistrer un commentaire