Skip to content

Instantly share code, notes, and snippets.

@sethkrasnianski
Last active February 15, 2019 18:12
Show Gist options
  • Save sethkrasnianski/cbda874327c911e148d7a7be5bb0fcb4 to your computer and use it in GitHub Desktop.
Save sethkrasnianski/cbda874327c911e148d7a7be5bb0fcb4 to your computer and use it in GitHub Desktop.
Better Component Testing

Better Component Testing

*In a Redux/React App

Things we know

  • Redux manages state
  • React manages presentation logic
  • Mixing the two together is not cool for testing
  • We can reduce cognitive overhead by decoupling redux logic and react components

What you know

import React from "react";
import TwitterFeed from "components/twitter-feed";
import Tweet from "components/tweet";

const TwitterFeed = ({ tweets, loadTweets}) => (
  <div>
    <button onClick={loadTweets}>Load Some Tweets</button>
    {tweets.length && tweets.map(t => <Tweet tweet={t} />)}
  </div>
);

const mapStateToProps = ({ tweets }) => ({ tweets });
const mapDispatchToProps = dispatch => 
  bindActionCreators({ loadTweets }, dispatch)

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(TwitterFeed);

Make life easier

Possible structure

/app
  /connected
    twitter-feed.js
  /components
    /twitter-feed/
      index.jsx
      index.test.jsx
      styles.css

connected/twitter-feed.jsx

import React from "react";
import TwitterFeed from "components/twitter-feed";

const mapStateToProps = ({ tweets }) => ({ tweets });
const mapDispatchToProps = dispatch => 
  bindActionCreators({ loadTweets }, dispatch)

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(TwitterFeed);

¿Why?

  • Better testing
  • Cleaner code

It is not necessary to test that our mapDispatchToProps is properly passing our login function to the connected component, because Redux is already responsible for this.

Integration and e2e tests solve this anyway (can ignore connected with coverage tool)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment