Brian Emil Hartz

let me = enjoy ( pondering ( javascript ( reactjs ) ) )

Touch Event React Testing


React component testing has dramatically improved over the past year. A year ago I wrote a small post that used Enzyme which helped supply much needed tooling around react component testing and isolated component testing with shallow Rendering.

When I first wrote that post I looked into Jest but it seemed overly complicated and confusing at the time. Since then it has had a few major overhauls and has come out leading the pack for react testing especially with the addition of snapshot testing (sadly we wont get into snapshot testing here, but there are many great examples out there).

Jest leads the pack for react component testing

Testing

I've had an open issue on react-swipeable for over a year that has a task to create tests. I recently undertook this adventure and am going to share what I did by going through the creation of a simple touch event component and creating tests that utilize jest and enzyme.

Setup

First install all required dependencies by following the general setup on Jest's page and since we're doing "DOM testing" you want to install enzyme and react-addons-test-utils by following this example.

Component

Let's start with a simple component that keeps track of touch events along the x axis.

This component will keep track when a touch event has started, then tracks if the touch is "swiping" and finally when the touch finishes if the touch is considered a "swipe" - if distance touch travelled is > this.minDistance, which is 50px.

Test Utils

We will test our new touch event component using enzyme's mount component capabilities. Then we need to simulate touch events via simulate on a selected dom node.

With the addition of some helper functions to mock touch events we can more smoothly simulate what the component considers a touch "swipe". These are a few simple helpers to aid with this.

Tests

We now have our component created along with some general helper functions and can now setup our tests.

First we can just test that the component "renders". Then start to test some of the functionality:

  • state is updated - tested via checking text output
  • prop callback called appropriately - tested via jest.fn() spies

Full Example on Github

I setup this example component and tests in a small github repo that can be cloned and ran locally if desired.

https://github.com/hartzis/event-testing

Again this pull request is the original inspiration for this small post.

Let me know if you have questions, cheers!