您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何用Jest模拟第三方模块

如何用Jest模拟第三方模块

您需要像这样模拟它:

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
其他 2022/1/1 18:20:25 有426人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶