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
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
- First we are going to create a callback (click handler) to catch the bubbled up values.
- We use Enzyme to create our component
MyComponent
- We use the .find() on our wrapped component to find our <Button /> by id
- After we get our button we can call .simulate(‘click’) which will act as a user clicking the button.
- 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,
Pingback: Weekly Links #112 – Useful Links For Developers