【问题标题】:How to mock third party modules with Jest如何使用 Jest 模拟第三方模块
【发布时间】:2018-02-19 20:58:41
【问题描述】:

我的测试目标中有当前导入:

import sharp from 'sharp'

并在我的同一个测试目标中使用它:

return sharp(local_read_file)
    .raw()
    .toBuffer()
    .then(outputBuffer => {

在我的测试中,我在下面模拟尖锐的功能:

jest.mock('sharp', () => {
  raw: jest.fn()
  toBuffer: jest.fn()
  then: jest.fn()
})

但我得到了:

  return (0, _sharp2.default)(local_read_file).
                             ^
TypeError: (0 , _sharp2.default) is not a function

有没有一种方法可以使用 Jest 模拟所有 Sharp 模块函数?

【问题讨论】:

    标签: javascript node.js jestjs


    【解决方案1】:

    你需要像这样模拟它:

    jest.mock('sharp', () => () => ({
            raw: () => ({
                toBuffer: () => ({...})
            })
        })
    

    首先你需要返回函数而不是对象,因为你调用了sharp(local_read_file)。此函数调用将返回一个带有键 raw 的对象,该对象包含另一个函数,依此类推。

    要对调用的每个函数进行测试,您需要为每个函数创建一个 spy。由于您在初始模拟调用中不能这样做,因此您可以先用间谍模拟它,然后再添加模拟:

    jest.mock('sharp', () => jest.fn())
    
    import sharp from 'sharp' //this will import the mock
    
    const then = jest.fn() //create mock `then` function
    const toBuffer = jest.fn({()=> ({then})) //create mock for `toBuffer` function that will return the `then` function
    const raw = jest.fn(()=> ({toBuffer}))//create mock for `raw` function that will return the `toBuffer` function
    sharp.mockImplementation(()=> ({raw})) make `sharp` to return the `raw` function
    

    【讨论】:

    • 我现在如何使用 spyon 来获取 callcount 和 args (尖锐)?我真的可以这样做吗? const sharpSpy = jest.spyOn("sharp", "raw") expect(sharpSpy).toBeCalled(); expect(sharpSpy.mock.calls.length).toEqual(1);这似乎在我的测试中失败了
    • 这需要更复杂的模拟方式。我会更新我的答案。
    • 稍后通过添加模拟来使用该方法时出现TypeError: (0 , _sharp2.default)(...).raw is not a function 错误。
    • Argh,你说得对,它必须返回一个对象而不仅仅是函数,更新了我的答案。
    • 啊,我只是忘记了{raw} 周围的() 和其他返回对象。更新了答案。
    猜你喜欢
    • 1970-01-01
    • 2018-11-17
    • 2019-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-31
    • 2020-10-07
    相关资源
    最近更新 更多