jest-image-snapshot icon indicating copy to clipboard operation
jest-image-snapshot copied to clipboard

Automatically detect Jest jsdom/canvas environment

Open mbullington opened this issue 2 years ago • 0 comments

Hello! Thanks for open sourcing jest-image-snapshot and working with the community on it!

I'm trying to use this for Image from jsdom, which you can automatically set up in Jest https://jestjs.io/docs/configuration#testenvironment-string and with the peerdep canvas. https://github.com/jsdom/jsdom#canvas-support

I wrote this little blurb to automatically detect a JSDOM Image in the toMatchImageSnapshot snapshot and think it would be useful if it was unstreamed. Here is my setupFilesAfterEnv file:

/**
 * Takes a JSDOM image and returns a Node.js buffer to use
 * with jest-image-snapshot.
 */
function imageToBuffer(image: HTMLImageElement): Buffer {
  const canvas = document.createElement('canvas');
  canvas.width = image.width;
  canvas.height = image.height;

  const ctx = canvas.getContext('2d');

  ctx.drawImage(image, 0, 0);

  const base64 = canvas.toDataURL().split(',')[1];
  return Buffer.from(base64, 'base64');
}

expect.extend({
  toMatchImageSnapshot: function (received, options) {
    // If these checks pass, assume we're in a JSDOM environment with the 'canvas' package.
    if (
      received &&
      received.constructor &&
      received.constructor.name === 'HTMLImageElement'
    ) {
      received = imageToBuffer(received);
    }

    return toMatchImageSnapshot.call(this, received, options);
  }
});

Best,

mbullington avatar Sep 07 '21 21:09 mbullington