JSFiddle - React, Tailwind, and code Playground

by Farzad YZ

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/0.0.1/prism.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/0.0.1/prism.min.css">
<div class="highlight">
  <p>Not all the components you write for your React application can be divided into Stateful and Stateless (dumb) categories. There is a 3rd advanced type of component in React called a higher-order component. A higher-order component is a function that
    takes a component as an argument and returns another component. Check out my other article to see how higher-order components are used in the real world.</p>
  <h2 id="creating-a-hoc-with-tests">Creating a HOC with Tests</h2>
  <p>We’ll be using Enzyme and Jest, but these concepts apply to any testing library.</p>
  <p>One of the common HOCs I write for every project of mine is called withConditional. Its purpose is to render a component if and only if the condition passes, otherwise just return null.</p>
  <pre><code class="language-jsx">import React from &quot;react&quot;;
const withConditional = Component =&gt;
  function withConditionalComponent({ condition, ...props }) {
    if (condition) {
      return &lt;Component {...props} /&gt;;
    }
    return null;
  };
export default withConditional;</code></pre>
  <p>As you can see, when the condition passed to the HOC evaluates to true, it returns the component, otherwise it returns null.</p>
  <p>So how can you unit test the HOC? There are surprisingly minimal articles talking about unit testing these components, and I had a hard time figuring out the proper way. Recently the solution clicked!</p>
  <h2 id="solution">Solution</h2>
  <p>To properly test these badass components, you just need to know that they are simple functions and that’s all!</p>
  <p><code>withConditional</code> is used in the following manner</p>
  <pre><code class="language-jsx">const ConditionalComponent = withConditional(MyComponent);
class HelloWorld extends React.Component {
 ...