Ad
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.target.files[0];
reader.onload = event => {
console.log(event);
setImagePreview(event.target.result);
};
reader.readAsDataURL(file);
};
return (
<div>
<input
accept="image/*"
id="contained-button-file"
multiple
type="file"
style={{ display: 'none' }}
onChange={handleChangeImage}
/>
<img id="preview" src={imagePreview} />
</div>
);
SimpleDialog.test.js
it('should change image src', () => {
const event = {
target: {
files: [
{
name: 'image.png',
size: 50000,
type: 'image/png'
}
]
}
};
let spy = jest
.spyOn(FileReader.prototype, 'onload')
.mockImplementation(() => null);
wrapper.find('input[type="file"]').simulate('change', event);
expect(spy).toHaveBeenCalled();
expect(wrapper.find('#preview').prop('src')).not.toBeNull();
});
When running the test it gives me the error TypeError: Illegal invocation.
Anyone who can help me with this unit test? I Just want to simulate on change if the src of an image has value or not.
Ad
Answer
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');
Ad
source: stackoverflow.com
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad