如何使用 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 模块函数?
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屋!