Skip to content Skip to sidebar Skip to footer

How To Test Filereader Onload Using Simulate Change In Jest?

SimpleDialog.jsx const [imagePreview, setImagePreview] = React.useState(null); const handleChangeImage = event => { let reader = new FileReader(); let file = event.targ

Solution 1:

The cause of the error is that onload is defined as property descriptor and assigning it to FileReader.prototype which is done by spyOn isn't supported.

There's no reason to mock onload because it's assigned in tested code and needs to be tested.

The straightforward way is to not patch JSDOM FileReader implementation but stub it entirely:

jest.spyOn(global, 'FileReader').mockImplementation(function () {
    this.readAsDataURL = jest.fn();
});

wrapper.find('input[type="file"]').simulate('change', event);


let reader = FileReader.mock.instances[0];
expect(reader.readAsDataURL).toHaveBeenCalledWith(...);
expect(reader.onload).toBe(expect.any(Function));

expect(wrapper.find('#preview').prop('src')).toBeNull();

reader.onload({ target: { result: 'foo' } });

expect(wrapper.find('#preview').prop('src')).toBe('foo');

Solution 2:

Had the same issue with checking some side effect that should be invoked on FileReader.onload, so I just ended up setting a short pause after triggering the event (I'm using enzyme + jest). Setting the timeout is probably not the best solution here, but it was the only thing that worked.

constpauseFor = milliseconds => newPromise(resolve =>setTimeout(resolve, milliseconds));
...
wrapper.find('.upload-box').simulate('drop', someMockedDropEvent);
// set pause was the only way to make reader.onload to fireawaitpauseFor(100);
expect(something).toEqual(something)

Post a Comment for "How To Test Filereader Onload Using Simulate Change In Jest?"