Option 1: Actively loading external resources in JSDOM
Initializing the JSDOM with resources: 'usable' should usually be sufficient using the latest API ( v10+ ):
const jsdom = new JSDOM('<!doctype html><html><body></body></html>',{ resources: 'usable' }); const { window } = jsdom;
This requires a canvas ( canvas or canvas-prebuilt ) as specified in the JSDOM doc .
Option 2: mock window.Image to gain control over it
Using the latest canvas module, you can mock window.Image to fire load events.
So, first create a layout for the window.Image class:
import CanvasImage from 'canvas/lib/image'; import fs from 'fs'; import path from 'path'; import { URL } from 'url'; import request from 'request'; // Where to fetch assets on the file system when path are provided. const ASSETS_DIRECTORY = path.join(__dirname,'.'); const WindowImage = function( // Reimplemented the following class: // https://github.com/tmpvar/jsdom/blob/master/lib/jsdom/living/nodes/HTMLImageElement-impl.js // https://github.com/Automattic/node-canvas
You can then mock window.Image in your tests by overriding the one used by JSDOM:
window.Image = WindowImage;
This is not very elegant, but it gives you the ability to control the loading of image data, since canvas.Image.src can usually accept any buffer.
source share