useFilePicker icon indicating copy to clipboard operation
useFilePicker copied to clipboard

Unit test for FilePicker

Open ronald2x opened this issue 2 years ago • 2 comments

Hi, I'm learning React. I used useFilePicker in my learning react project. However still struggling how to do unit test for this component. Mock files always fails. Do you any example how to test components with useFilePicker ?

ronald2x avatar Jun 07 '22 06:06 ronald2x

@ronald2x Welcome to the React devs community 😉 What do You mean by "mock files always fails"? Can You provide us with some code snippets of tests and the component in which You're using useFilePicker?

MrKampla avatar Jun 14 '22 23:06 MrKampla

hello @ronald2x I just wrote a few tests and mocking in jest seems to behave as expected.

// test.ts
import { useFilePicker } from 'use-file-picker';

jest.mock('use-file-picker');

const mockUseFilePicker = useFilePicker as jest.MockedFunction<typeof useFilePicker>;

test('it should work', () => {
  mockUseFilePicker.mockReturnValue([
    jest.fn(),
    {
      filesContent: [],
      plainFiles: [],
      errors: [],
      loading: false,
      clear: jest.fn(),
    },
  ]);

  // render
})

if you need to mock selected files you can overwrite plainFiles with plainFiles: [new File([], 'image.jpg')],

krystofmatejka avatar Sep 05 '22 07:09 krystofmatejka

Hi @kxmatejka @ronald2x. I believe the testing should be done in a bit different way, you should aim to test what user see, not what the function/hook does. Here is a great article on that https://kentcdodds.com/blog/avoid-the-test-user

We recently got a pull request from @jakubczarnowski that follows the "correct" way. Tests

Jaaneek avatar Apr 06 '23 08:04 Jaaneek