DEV Community

Glenn Stovall
Glenn Stovall

Posted on • Originally published at peanutbutterjavascript.com on

Test Clicks On Connected Components In Under 10 Lines of Code

Here’s a fairly benign component, that can give developers pause when its time to write unit tests for your components:

const ClickableButton = props => (
  <button onClick={props.doSomething}>Click Me!</button>
)
const mapDispatchToProps () => ({
  doSomething: dispatch(someFancyAction())
})
export default connect(
  null, 
  mapDispatchToProps,
)(ClickableButton)
Enter fullscreen mode Exit fullscreen mode

There is the only thing worth testing here: That when we click the button, the function we passed in as a prop gets called. That prop function could be a complex chain of actions & API calls. You don’t want to stress about that, at least not in these tests. But to do this, are we going to have to create a mock store and a provider component just because it’s connected? Ugh!

There has to be a better way.

You Can Remove The Redux Connection Entirely

While you want your component to be the default export, you can export the unconnected component, and just test that! Hat tip to Dave Ceddia for showing me a better way to export a connected component. All you have to do is change one line:

export const ClickableButton = props => (
Enter fullscreen mode Exit fullscreen mode

As an additional trick, if you have any helper functions not attached to the component, you can export those as well for easy testing.

With Jest and Enzyme, The Rest is Easy

Inside our test, import the unconnected component. Then, you can create a mock function using Jest, and simulate the click using Enzyme. Here’s what the test looks like all together:

describe('<ClickableButton />', () => {
  it('calls the doThing prop when the button is clicked', () => {
    const props = { doSomething: jest.fn() }
    const wrapper = shallow(<ClickableButton {...props} />)
    wrapper.find("button").first().simulate("click")
    expect(props.doSomething).toHaveBeenCalled()
  })
})
Enter fullscreen mode Exit fullscreen mode

The post Test Clicks On Connected Components In Under 10 Lines of Code appeared first on Glenn Stovall.

Top comments (0)