Aessandro
Aessandro

Reputation: 5771

React hook unit test

I have the following:

const Repairs: React.FC<RepairsProps> = ({repairs, repairsPropertyLoad}) => {
  const { t } = useTranslation()
  const [isARepair, setRepair] = useState(true)
  const handleOnClick = () => { 
    setRepair(false)
    repairsPropertyLoad('token')
  }

  return ( isARepair ? <p>on</p> : <p>off</p> )
  ...

since it's also a connected component I have added the following test:

describe('Repairs', () => {
  let store: any
  let component: any

  beforeEach(() => {
    store = mockStore({
      repairs: mockRepairs
    })

    store.dispatch = jest.fn()

    component = render(
      <Provider store={store}>
        <Repairs />
      </Provider>
    )

  })

  it('should render the Repairs component correctly', () => {
    expect(component).toMatchSnapshot()
  })

  it('should find the repair button in the document', () => {
    const { getByText } = component

    const repairsButton = getByText('Repair')
    expect(repairsButton).toBeInTheDocument()
  })
})

how can I test the isARepair flag scenarios (true and false) so that I can snapshot either off or on results?

Upvotes: 2

Views: 139

Answers (1)

Gasim
Gasim

Reputation: 7991

I would strongly suggest that you write test as if the end user is using your UI. For example, you are setting setIsRepair to false when user clicks the button. You can simulate the button click using fireEvent:

fireEvent.click(repairsButton);
expect(getByText('off')).not.toBeNull();
// this might not be the exact code but you get the gist

If you want to test your hooks, you should create a custom hook, render it into a dummy test component, and test the return values; or use React Hooks Testing Library. However, if your state logic is as simple as a single useState, I would suggest not testing it because you will essentially be testing React's useState instead of testing a your own state logic. My recommendation is to test state logic that consists of many parts (it is complex enough that it requires a test).

Upvotes: 3

Related Questions