【问题标题】:Jest mocking - How do I mock this module..?开玩笑 - 我如何模拟这个模块..?
【发布时间】:2018-03-02 17:03:34
【问题描述】:

我正在尝试模拟 sharp,我有这个:

// /__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

当我 import sharp from 'sharp'console.log(sharp) 我得到:

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

看起来不错,它找到了我的模拟模块,而不是真正的模块。

你像这样使用sharp

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

但是,当我使用我的模拟模块从测试代码中调用 sharp() 时,它的值是 undefined,而不是 instanceof sharp

我尝试将const Sharp = jest.genMockFromModule('sharp') 替换为function Sharp (input, options) { return this },但这没有任何区别。

我做错了什么..?

【问题讨论】:

    标签: javascript unit-testing jestjs sharp


    【解决方案1】:

    sharp 构造函数中找到这个。

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

    所以我把const Sharp = jest.genMockFromModule('sharp')换成了:

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

    似乎有效...

    【讨论】:

      猜你喜欢
      • 2018-07-25
      • 2020-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多