如何正确地模拟库,以便能够测试组件与jest和React测试库

pcww981p  于 2023-06-27  发布在  Jest
关注(0)|答案(1)|浏览(129)

我正在测试一个使用react-dropzone库的组件。

import TextInput from './components/TextInput';
import Switch from 'react-switch';
import { useDropzone } from 'react-dropzone';
const MyComp = () => {
   return <div>CONTENT</div>
}

当我运行测试时,我得到:

TypeError: Invalid attempt to destructure non-iterable instance.
    In order to be iterable, non-array objects must have a [Symbol.iterator]() method.

  12 | import TextInput from './components/TextInput';
  13 | import Switch from 'react-switch';
> 14 | import { useDropzone } from 'react-dropzone';

setupTests.js中,我试图模仿其他库:

// Mock custom hook useDimensions
jest.mock('./hooks/useDimensions.js', () => ({
  useDimensions: jest.fn().mockReturnValue({
    ref: { current: null },
    dimensions: { width: 100, height: 100 },
    isFirstLoad: true
  })
}));

// Mock react-dnd
jest.mock('react-dnd', () => ({
  useDrop: jest.fn().mockReturnValue([{ handlerId: 'mockHandlerId', isOver: false }, jest.fn()]),
  useDrag: jest.fn().mockReturnValue([{ isDragging: false }, jest.fn()])
}));

// Mock react-dropzone
jest.mock('react-dropzone', () => ({
  ...jest.requireActual('react-dropzone'),
  useDropzone: jest.fn()
}));

但我一直得到同样的错误。
你知道吗?

hts6caw3

hts6caw31#

更像是:

import * as reactDropzone from 'react-dropzone';

const mockedUseDropzone = jest.fn();

jest.spyOn(reactDropzone, 'useDropzone').mockImplementation(() => mockedUseDropzone);

jest.spyOn(reactDropzone, 'useDropzone').mockImplementation(mockedUseDropzone);

大多数时候,你需要“spyOn”来模拟库中的钩子阅读更多。

相关问题