如何使用Jest模拟第三方模块 [英] How to mock third party modules with Jest
问题描述
我目前已在我的测试目标中导入:
I've got current import in my test target:
import sharp from 'sharp'
并在我的同一测试目标中使用它:
and using it with in my same test target:
return sharp(local_read_file)
.raw()
.toBuffer()
.then(outputBuffer => {
在我的测试中,我正在做下面的模拟功能:
In my test, I'm doing below to mock sharp functions:
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模块函数? / p>
Is there a way we can mock all Sharp module functions using Jest with the function?
推荐答案
你需要像这样嘲笑:
jest.mock('sharp', () => () => ({
raw: () => ({
toBuffer: () => ({...})
})
})
首先你需要返回函数而不是一个对象,因为你调用 sharp(local_read_file)
。此函数调用将返回一个对象,其中包含键 raw
,该对象包含另一个函数,依此类推。
First you need to return function instead of an object, cause you call sharp(local_read_file)
. This function call will return an object with key raw
which holds another function and so on.
要测试您调用的每个函数都需要为每个函数创建一个间谍。由于你不能在最初的模拟调用中使用它,你可以先用间谍模拟它并稍后添加模拟:
To test on the every of your functions was called you need to create a spy for every of the function. As you can't to this in the initial mock call, you can mock it initially with a spy and add the mocks later on:
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
这篇关于如何使用Jest模拟第三方模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!