您需要像这样模拟它:
jest.mock('sharp', () => () => ({ raw: () => ({ toBuffer: () => ({...}) }) })首先,您需要返回function而不是对象,因为您需要调用
sharp(local_read_file)。该函数调用将返回带有键的对象,该键
raw包含另一个函数,依此类推。
要测试每个功能,您需要为每个功能创建一个间谍。由于您在最初的模拟调用中无法做到这一点,因此可以先使用间谍对其进行模拟,然后再添加模拟:
jest.mock('sharp', () => jest.fn())import sharp from 'sharp' //this will import the mockconst then = jest.fn() //create mock `then` functionconst toBuffer = jest.fn({()=> ({then})) //create mock for `toBuffer` function that will return the `then` functionconst raw = jest.fn(()=> ({toBuffer}))//create mock for `raw` function that will return the `toBuffer` functionsharp.mockImplementation(()=> ({raw})) make `sharp` to return the `raw` function


