Testing Button Click in React with Jest

When building React applications you will most likely find yourself using Jest as your testing framework.  Jest has some really, really cool features built in.  But when you use Enzyme you can take your testing to the nest level.

One really cool feature is the ability to test click events via Enzyme to ensure your code responds as expected.

Before we get started you are going to want to make sure you have Jest and Enzyme installed in your application.

Sample code under test

Screen Shot 2018-05-07 at 12.52.56 PM

What I would like to be able to do is pull the button out of my component and test the onClick event handler.

  
// Make sure you have your imports setup correctly
import React from 'react';
import { shallow } from 'enzyme';


it('When active link clicked, will push correct filter message', () => {
    let passedFilterType = '';
    const handleOnTotalsFilter = (filterType) => {
        passedFilterType = filterType;
    };
    const accounts = {};
    const wrapper = shallow(<MyComponent accounts={accounts} filterHeader="" onTotalsFilter={handleOnTotalsFilter} />);

    const button = wrapper.find('#archived-button');
    button.simulate('click');
    expect(passedFilterType).toBe(TotalsFilterType.archived);
});

Lets take a look at the test above

  1. First we are going to create a callback (click handler) to catch the bubbled up values.
  2. We use Enzyme to create our component MyComponent
  3. We use the .find() on our wrapped component to find our <Button /> by id
  4. After we get our button we can call .simulate(‘click’) which will act as a user clicking the button.
  5. We can assert that the expected value bubbles up.

As you can see, simulating a click event of a rendered component is very straight forward, yet very powerful.

Till next time,

One thought on “Testing Button Click in React with Jest

  1. Pingback: Weekly Links #112 – Useful Links For Developers

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s