DEV Community

Discussion on: How to test High Order Components in React

Collapse
 
squishybear profile image
Wai Chung Hon

Hi Jaime,

Great post! My team is trying to write tests for the componentDidUpdate() method in our HOC, but we're getting stuck. Do you have any recommendations?

Thanks,

Wai

Collapse
 
papaponmx profile image
Jaime Rios

Hi, Wai. I'm glad to help.

Regarding your question, here is how I would go about it:

When using componentDidUpdate, I imagine it might happen because of a browser event, like an user clicking a button or focusing on an input.

At a component level, this might look like a method being triggered after being rendered.

This is what the code looks like:

describe('Test click button simulation', () => {
  it('should update the count by 1 when invoked by default', () => {
    const wrapper = shallow(<Home />);
    expect(wrapper.state('counter')).toBe(0);
    wrapper.find('button').simulate('click');
    expect(wrapper.state('counter')).toBe(1);
  });

Note that I'm component's state for this example, but you might use props if required. Here is a link with more examples.

Cheers.