user4351649
user4351649

Reputation:

How to test a React Component with a Custom Hook

Given a simple custom hook (which I know how to test):

const useCounter = () => {
  const [value, setValue] = useState(0)

  const increase = () => {
    setValue(value + 1)
  }

  return {
    value, 
    increase
  }
}

And a component that use it:

const App = (props) => {
  const { value, increase } = useCounter()

  return (
    <div>
      <div>{value}</div>
      <button onClick={increase}>
        plus
      </button>
    </div>
  )
}

How do I test the component? What is the "right way" of doing it? Do I have to mock the custom hook? How?

Upvotes: 2

Views: 1619

Answers (2)

wentjun
wentjun

Reputation: 42526

Assuming you are working with Jest and Enzyme for unit testing, I would wrap the App component into a shallow wrapper using Enzyme's shallow rendering API.

Then, I will use .find() to find the button element, and use .simulate('click') on the element, to simulate an onClick event on the button, such that the increase method will be called.

After which, I will carry on to check with the expected result and behaviour.

Here is a brief on how it can be done:

import { shallow } from 'enzyme';
import * as React from 'react';

describe('<App />', () => {

  it('test for onClick', () => {
    const wrapper = shallow(<App />);
    wrapper.find('button').simulate('click');

    // do the rest here
    // expect().....
  });

})

Upvotes: 1

T. Short
T. Short

Reputation: 3614

You should not need to mock it. When you run App in a test it will just use your custom hook.

If you want to modify it's behaviour somehow specifically for the test, then you would have to mock it.

Upvotes: 1

Related Questions