0

I'm trying to mock sharp and I have this:

// /__mocks__/sharp.js

const Sharp = jest.genMockFromModule('sharp')

Sharp.prototype.jpeg = function (options) { return this }
Sharp.prototype.trim = function (options) { return this }
Sharp.prototype.normalise = function (bln) { return this }
Sharp.prototype.background = function (colour) { return this }
Sharp.prototype.embed = function () { return this }
Sharp.prototype.clone = function () { return this }
Sharp.prototype.resize = function (width, height) { return this }

Sharp.prototype.toBuffer = function () {
  return Buffer.from('')
}

export default Sharp

When I import sharp from 'sharp' and console.log(sharp) I get:

function Sharp() {return mockConstructor.apply(this,arguments);}

Seems right, it's found my mock module, not the real module.

You use sharp like this:

const sharpImage = sharp(input, options).jpeg(options).trim()
const myImageBuff = await sharpImage.toBuffer()

However, when I call sharp() from test code, using my mocked module, it's value is undefined, rather than an instanceof sharp.

I've tried replacing const Sharp = jest.genMockFromModule('sharp') with function Sharp (input, options) { return this } but that makes no difference.

What am I doing wrong..?

Stephen Last
  • 5,491
  • 9
  • 44
  • 85

1 Answers1

1

Found this in the sharp constructor function.

https://github.com/lovell/sharp/blob/35117239144dcd085ecf653697df725b2f2e8fbb/lib/constructor.js#L97

So I switched out const Sharp = jest.genMockFromModule('sharp') for:

function Sharp (input, options) {
  if (!(this instanceof Sharp)) {
    return new Sharp(input, options)
  }
  return this
}

Seems to work...

Stephen Last
  • 5,491
  • 9
  • 44
  • 85