I have a ImageLoader
class component that I am trying to test if the onload
function on a HTMLImageElement
is being called. It is important to note that ImageLoader
works as intended, I just can't get the tests to run. Here is the example of my class component:
export default class ImageLoader extends React.Component {
// Omitted for brevity
setSrc = () => {
const { src } = this.props;
if (src) {
this.tmpImg = new Image();
// this.tmpImg.onload is never called
this.tmpImg.onload = () => console.log('???');
this.tmpImg.src = src;
}
}
// Omitted for brevity
}
For my test I have left out what I am actually testing because I never actually get to the onload
event (it doesn't console.log
when the tests are running unless I manually call this.tmpImg.onload()
).
import { mount } from 'enzyme';
import ImageLoader from '../ImageLoader';
describe('ImageLoader', () => {
it('renders', () => {
const wrapper = mount(
<ImageLoader src="A_URL_STRING" />,
);
// Omitted for brevity
});
});
Now according to this is issue jsdom
has got rid of support for that, however towards the end a comment was left saying you can do it with the proper Jest setup.
I have added that to my setup but still can not get the onload
event to fire.
Here is that setup:
"jest": {
"testEnvironmentOptions": {
"resources": "usable"
}
},
Also in the jsdom
repository it talks about loading subresources here.
Update
What drives me even more mad is I can create the tests in Code Sandbox here and it passes all tests.
If I download it and run it locally I get a Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
One thing to note is I moved creating the image into a promise and then resolving that promise when onload
has been called.
Ok I figured it all out thanks to Andrew's comment above.
To make this work locally you have to have the canvas package installed with "testEnvironmentOptions": { "resources": "usable" },
setup in the Jest section of the package.json
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With