您需要像这样模拟它:
jest.mock('sharp', () => () => ({
raw: () => ({
toBuffer: () => ({...})
})
})
首先,您需要返回function而不是对象,因为您需要调用sharp(local_read_file)
。该函数调用将返回带有键的对象,该键raw
包含另一个函数,依此类推。
要测试每个功能,您需要为每个功能创建一个间谍。由于您在最初的模拟调用中无法做到这一点,因此可以先使用间谍对其进行模拟,然后再添加模拟:
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