How to properly mock library to be able to test the component with jest and react testing library

904 Views Asked by At

I'm tryng to test a component which uses react-dropzone library.

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

When I run the test I get:

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';

In setupTests.js I try to mock it as other libraries:

// 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()
}));

But I keep getting the same error.

Any idea?

1

There are 1 best solutions below

0
toncho.lozev On

More like:

import * as reactDropzone from 'react-dropzone';

const mockedUseDropzone = jest.fn();

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

or

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

Most of the times you will need "spyOn" in order to mock hooks from libraries Read more.