Jaaneek / useFilePicker

Simple react hook to open browser file selector.

Home Page:https://use-file-picker.vercel.app

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Unit test for FilePicker

ronald2x opened this issue · 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 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?

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')],

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