Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用Jest模拟第三方模块_Javascript_Node.js_Jestjs - Fatal编程技术网

Javascript 如何使用Jest模拟第三方模块

Javascript 如何使用Jest模拟第三方模块,javascript,node.js,jestjs,Javascript,Node.js,Jestjs,我的测试目标中有当前导入: import sharp from 'sharp' return sharp(local_read_file) .raw() .toBuffer() .then(outputBuffer => { 并在我的同一测试目标中使用它: import sharp from 'sharp' return sharp(local_read_file) .raw() .toBuffer() .then(outputBuff

我的测试目标中有当前导入:

import sharp from 'sharp'
return sharp(local_read_file)
    .raw()
    .toBuffer()
    .then(outputBuffer => {
并在我的同一测试目标中使用它:

import sharp from 'sharp'
return sharp(local_read_file)
    .raw()
    .toBuffer()
    .then(outputBuffer => {
在我的测试中,我将做以下操作来模拟sharp函数:

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模块函数?

您需要像这样模拟它:

jest.mock('sharp', () => () => ({
        raw: () => ({
            toBuffer: () => ({...})
        })
    })
首先,您需要返回函数而不是对象,因为您调用了
sharp(local\u read\u file)
。此函数调用将返回一个带有key
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

我现在如何使用spyon获取呼叫计数和args(夏普)?我真的可以这样做吗<代码>常量sharpSpy=jest.spyOn(“sharp”,“raw”)expect(sharpSpy).toBeCalled();expect(sharpSpy.mock.calls.length).toEqual(1)这在我的测试中似乎失败了这需要一种更复杂的模拟方式。我将更新我的答案。我得到
TypeError:(0,_sharp2.default)(…)。当我稍后通过添加mock来使用该方法时,raw不是一个函数
错误。啊,你是对的,它必须返回一个对象,而不仅仅是函数,更新了我的答案。啊,我只是忘记了
{raw}
周围的
和其他返回的对象。更新了答案。