<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ben Rozenberg on Medium]]></title>
        <description><![CDATA[Stories by Ben Rozenberg on Medium]]></description>
        <link>https://medium.com/@benrozenberg?source=rss-5939aa5979e8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*6xsl--xKklfyLTrj.</url>
            <title>Stories by Ben Rozenberg on Medium</title>
            <link>https://medium.com/@benrozenberg?source=rss-5939aa5979e8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 06:34:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@benrozenberg/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Improve your code with Hooks, Context API and React-Apollo]]></title>
            <link>https://medium.com/@benrozenberg/improve-your-code-with-hooks-context-api-and-react-apollo-70d2609856b9?source=rss-5939aa5979e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/70d2609856b9</guid>
            <category><![CDATA[apollo-client]]></category>
            <category><![CDATA[context-api]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Ben Rozenberg]]></dc:creator>
            <pubDate>Sun, 11 Aug 2019 11:11:40 GMT</pubDate>
            <atom:updated>2019-08-11T11:18:49.108Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iDDey32uUop8S9YetBNu0w.jpeg" /></figure><p>Recently <a href="https://www.apollographql.com/docs/react/">Apollo Client</a> has upgraded its library to work with hooks.<br>This was the trigger for us to make some changes in our codebase and also for me to publish this post.</p><p>The purpose of this post is to present how we used React Hooks, Context API, and React-Apollo features to improve our codebase.</p><p>This Post should still be relevant even if you are not using Apollo but do want to learn how to leverage Context API and Hooks. Which you want!<br>We will go over briefly on Hooks and Context API and then we will look at an example.</p><h3>Hooks:</h3><p>React is a UI, component-based library, it provides us two methods for creating components: A class component and a functional component.<br>You can find many articles which explain the differences between them but let’s just say that most of the times functional components are faster and are the recommended way by the React team to write components. <br>On the other hand, functional components lack some key features which class components have, such as State and life cycle methods. <br>Hooks give us access to those missing features in functional components, basically giving us the ability to write functional components and to enjoy the benefits of class components. AWESOME!</p><p>** The main idea behind React Hooks was to find a better, simpler way to reuse code logic. You can read more about it <a href="https://medium.com/@dan_abramov/making-sense-of-react-hooks-fdbde8803889">here</a>.</p><h3>Context API:</h3><p>context gives us a way to pass props down the component tree without having to pass it through each node in the tree. With this, we have an improved way to share state among components, which was not an easy task in React a few years ago.</p><h3>Let’s Mix:</h3><p>By now, hopefully, you at least understand the ideas behind Context API and React Hooks. So let’s go through a common scenario which should explain things further. <br>Your app should have a user object, keeping details of the logged-in user and passing it down to be consumed by many components to check user permissions and more.</p><p>Harnessing the power of all the new cool features we received, we now can make a query to the server, asking for the user details, via Apollo <a href="https://apollographql.com/docs/react/essentials/queries/">useQuery</a> awesome hook and pass the result down to every component in need via the Context API. Wait, there is more fun coming, we also now would be able to consume the user object via React <a href="https://reactjs.org/docs/hooks-reference.html#usecontext">useContext</a> hook.<br>You gotta love that!</p><p>Ok, I hear you, let’s see it:</p><pre>...<br>import { UserProvider } from &#39;./userContext&#39;;</pre><pre>&lt;UserProvider&gt;   <br> &lt;Main&gt;          // main component or any component up in the tree<br>&lt;/UserProvider&gt;</pre><p>First, we render UserProvider which is our component that is responsible for getting the user info. By rendering UserProvider somewhere high in the tree we are enabling each node under it to have access to the user object.</p><p>Now let’s take a look in our userContext.js file. This file was created for isolating the Context API logic so later we could just import the Context component we need and use it very cleanly as you see above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a57ed0edabc24fac320d0886d8ba3af8/href">https://medium.com/media/a57ed0edabc24fac320d0886d8ba3af8/href</a></iframe><p>At line 6 we create the context with a default value of an empty object.<br>Later we create UserProvider functional component. Inside it, you can see the use of Apollo useQuery. The useQuery hook runs as soon as the component renders and is fetching the user data. It gives back an object with loading and data for us to use.<br>And finally, the component returns the UserContext.Provider which is what actually <strong>provides</strong> the value prop (user in our case) down to all of the components. <br>At line 15 we just create UserConsumer so later in other components we could use it and not UserContext.Consumer (just looks better)</p><p>That’s great. So far we have used Apollo hook to query the needed data and rendered the data via Context API so it is ready to be consumed by other components.</p><h4>Consuming Context data:</h4><p>There are a few ways to consume Context data. <br>The first one would be to get the data inside the return function using context.Consumer:</p><pre>//random component<br>...<br>import { UserConsumer } from &#39;../userContext&#39;;</pre><pre>return (<br>&lt;UserConsumer&gt;   // just a nicer way to write UserContext.Consumer <br>{user =&gt; /* do somehting with user */}<br>&lt;/UserConsumer&gt;<br>);</pre><p>We import UserConsumer which subscribes to UserContext and in return receives the context data.</p><p>But what if we need/prefer to consume the data outside of the return method you ask?</p><p>Well, it depends on the component type:</p><p><strong>class component:</strong></p><pre>import React, { Component } from &#39;react&#39;;<br>import UserContext from &#39;./UserContext&#39;;</pre><pre>class YourClassName extends Component {<br> ...<br> static contextType = UserContext</pre><pre>soneFunction = () =&gt; {<br>  const user = this.context;<br> }</pre><pre>}</pre><p>We are using static contextType which is a property belongs to the class.<br>Pay attention that later we access the context via <strong>this.context</strong> and not this.contextType.</p><p><strong>Functional component:</strong></p><pre>import React, { useContext } from &#39;react&#39;;<br>import UserContext from &#39;./UserContext&#39;;</pre><pre>function YourCompName() {  <br> const user = useContext(UserContext)    <br> ....<br>}</pre><p>WOW! React useContext hook allows us to consume the context easily in a functional component.</p><p><strong>In conclusion:<br>What I hopefully showed here is how hooks and context API can replace render props / HOC patterns, giving us more features while writing less code.</strong></p><p>Pay Attention:<br># Make sure you have the minimum version to use hooks, both in React (<strong>all React packages need to be 16.8.0</strong>) and also in React Apollo (3.0) if you use it <br># Remember you can not use Hooks in a class component<br># A component calling useContext Hook will always re-render when the context value changes. If re-rendering the component is expensive, you can <a href="https://github.com/facebook/react/issues/15156#issuecomment-474590693">optimize it by using memoization</a>.</p><p>I really hope this post could help some of you.<br>Get familiar with React hooks, Context API, and upgrade your React Apollo library (if you are using it) so you could enjoy the latest features. <br>It will help you write cleaner, better code.</p><p>Be good!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70d2609856b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding JavaScript Objects]]></title>
            <link>https://medium.com/halolabs/understanding-javascript-objects-d31cd24ca60f?source=rss-5939aa5979e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/d31cd24ca60f</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[objects]]></category>
            <dc:creator><![CDATA[Ben Rozenberg]]></dc:creator>
            <pubDate>Thu, 26 Jul 2018 13:20:48 GMT</pubDate>
            <atom:updated>2018-07-29T13:26:51.710Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*nthoso33zFMHBRbWP9BQcA.jpeg" /></figure><p>Objects are a core concept in JavaScript. When I started learning about Objects it seemed to me pretty straightforward, just pairs of keys and values they said.</p><p>It took me some time to realize that this topic is much more complicated than I had in mind. I then started learning from different sources, some were good, but I could never get “the big picture”.</p><p>In this post I have tried to create a comprehensive overview of objects in JS, not going too deep into any subject, but just deep enough to help you understand and feel comfortable to go and read further.</p><p>So, let’s start from the beginning.</p><h3>Object</h3><p><strong>A JavaScript object is just a collection of properties, each property is a pair of a key and a value.</strong> <br>You can access keys using dot notation( obj.a ) or brackets notation ( obj[&#39;a&#39;]). Remember that you should use the brackets notation if your key is one of the following:<br>1. Not a valid JavaScript identifier (has space, dash, starts with a number...) <br>2. Is a variable</p><p>Objects in JS are created with a property called Prototype which is a very important subject to master.</p><h3><strong>prototype:</strong></h3><p>Every object in JavaScript has an internal property called Prototype, in most browsers you can access it as __proto__. Prototype is Javascript’s solution for inheritance, which allows sharing functionality without duplicating the code in memory. It does so by linking one object to another. <br>Simply put, Prototype creates a reference from one object to another.</p><p><strong>Prototype chain</strong> — Every time you look for a property in an object, JS will try to find it on the object, if it can’t, it will look inside the Prototype object. If the property is still missing, JS will go on looking in the Prototype of the linked object. This will continue until JS finds the relevant property or until the end of the prototype chain.</p><p>Let’s take an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/903e9af089622d1d3f22c0f0c2c2c433/href">https://medium.com/media/903e9af089622d1d3f22c0f0c2c2c433/href</a></iframe><p>cons is a constructor (just a function that can use the new operator). At line 5 we create new object, a new instance of cons. when created, obj also gets a prototype property.<br>Now we add properties (&#39;b&#39;, &#39;c&#39;) to the prototype object of cons and let’s take a look at obj :</p><p><strong>obj.a // 1</strong> — nothing new here, obj.a is still 1.<br><strong>obj.c</strong> — there is no c property on obj! but just as we said earlier, JS will now look in obj Prototype and will come back with a 4.<br> <br>Now ask yourself what is the value of obj.b and what would be the value after we delete obj.b ?</p><p>obj.b is 2 . We did set a b property but on cons Prototype so when we check for obj.b we still get 2. However, after we delete obj.b, JS can’t find b on obj anymore so it goes to its prototype and come back with a 3.</p><p>I want to briefly show the different ways to create an object and talk some more about prototype.</p><h3>creating an object</h3><p><strong>Object literal: </strong><strong>let obj = {a: 1};</strong> we have created an object with the following ptototype chain:<strong> </strong>obj ---&gt; Object.prototype ---&gt; null <br>As you can guess object.prototype is the prototype of object and it is also the end of the prototype chain.</p><p><strong>Object.create(): </strong><strong>var newObj = Object.create(obj);</strong> newObj will have this ptototype chain:<strong> </strong>newObj ---&gt; obj ---&gt; Object.prototype ---&gt; null</p><p><strong>Constructor: </strong>As the example above, a constructor is just a JS function that allows us to use new operator to create instances of it.</p><p><strong>ES6 Classes:</strong></p><pre>class rectangle {<br>  constructor(height, width) {<br>    this.height = height;<br>    this.width = width;<br>  } </pre><pre>  getArea() {<br>    return this.height * this.width;<br>  }<br>}<br>let square = new rectangle(2, 2);</pre><p>Square is an instance of rectangle constructor, so we can call square.getArea() //4, square.width and also all the functions it inherited from object.prototype.</p><p>Which way should you choose? If you plan to create several instances you better use ES6 / constructor method but if you plan to create a one time object you might want to choose object literal because it is probably the easiest.</p><p>Now that we know about prototype and are familiar with all the ways to create new objects we can move forward talking about one of the most confusing parts in objects:</p><h3>Comparing &amp; changing Objects</h3><p><strong>In JavaScript objects are a reference type.</strong> <br>When we create an object let obj = {a: 1};<strong> </strong>the variable obj receives the location in memory of the object and not the value! This is extremely important to understand because it can cause a variety of errors. When we create another object let newObj = obj , we have actually created a <strong>pointer </strong>to the location in memory of the obj and not a totally new object. <br>This means that when we do newObj.a = 2 we actually change obj so obj.a is now 2 ! <br>This is so bug prone that many companies are working with immutable objects, meaning you can not change the object you have created. Instead you have to create a new object (a copy of the original one) and change it. This is the way important libraries like Redux are working and it is one of the most important concepts in functional programming. You can read more about it <a href="https://facebook.github.io/immutable-js/">here</a>.</p><p><strong>Equality:</strong> This also means that two objects are never equal, even if they have the exact same properties. This is because JS actually compares the location in memory of the objects and two objects can never be in the same memory cell.</p><pre>// Two distinct objects with the same properties are not equal<br>var fruit = {name: &#39;apple&#39;};<br>var fruitbear = {name: &#39;apple&#39;};<br>fruit === fruitbear; // return false</pre><pre>// here fruit and fruitbear are pointing to same object<br>var fruit = {name: &#39;apple&#39;};<br>var fruitbear = fruit;  <br>fruit === fruitbear; // return true<br></pre><p>So by now you might be thinking how can I compare objects or how should I manipulate objects immutably?</p><p>Let’s go over some possibilities:</p><p><strong>Object changing:</strong></p><p>We understand we better not mutate our objects, so we would like to create a copy of the relevant object and change its properties. <br><strong>Object.assign()</strong> to the rescue.</p><pre>var obj = { a : 1, b : 2};<br>var newObj = Object.assign({}, obj,{a:2}) // {a : 2, b : 2 }</pre><p>If we want to change a property value of obj we can use object.assign to create a copy of obj and change it.<br>You can see how we first create an empty object, then copy the values of obj and later add our changes so eventually we get a new updated object to use.</p><p>Please pay attention that this will not work for a deep copy . A deep copy is when we want to copy an object which has one object property or more:</p><pre>const obj = {a : 1, b : { a : 1 } };  // b property is an object</pre><p>Object.assign()copies property values, so when the property value is a reference to an object, it only copies that reference.</p><p>For deep copy we have to copy recursively. We could create a function or simply use <a href="https://lodash.com/docs/4.17.10#cloneDeep">_.cloneDeep</a> of <a href="https://lodash.com/">Lodash</a>.</p><p><strong>Object comparing :</strong></p><p>One cool trick for working with objects is to stringify them. <br>What we do here is to stringify both objects, and then compare the resulted <strong>strings</strong> :</p><pre>JSON.stringify(<strong>obj1</strong>) === JSON.stringify(<strong>obj2</strong>) </pre><p>This works because we now compare strings which is a reference done by value data type. The bad news is that it is not always going to work, mainly because object properties order is not guaranteed.</p><p>Another good solution is to use <a href="https://lodash.com/">Lodash</a>’s _.isEqual which is making a deep object comparison.</p><p>Before we finish, lets go over some object’s interview questions which will help us dive in some more and to practice what we have learned.<br> <br>Try to think about a solution before going on reading the answer.</p><h4>How to find out the length of an object?</h4><p>To find the answer we would need to iterate over the object properties one by one and to count them. There are number of ways to iterate over an object:</p><ul><li><strong>for in: </strong>This method traverses all enumerable properties of an object and its prototype chain. Now that we (hopefully) know prototype we can easily realize that if we want to get only the object properties it might not be right to use for in.</li><li><strong>Object.keys: </strong>This method returns an array with all the <strong>own</strong> (only on object) <strong>enumerable </strong>properties keys of an object. This is better because we are only working on the object properties without its prototype properties. Rarely you will set property’s enumerable attribute to false, causing object.keys to skip them and you might not get the result you were wishing for. This is where getOwnPropertyNames can be handy.</li><li><strong>getOwnPropertyNames </strong>returns an array containing all object <strong>own</strong> keys (enumerable or not).</li></ul><p>Also worth mentioning:</p><ul><li><strong>Object.values</strong> iterate over own and enumerable properties and returns an array with the relevant <strong>values</strong>.</li><li><strong>Object.entries </strong>iterate over own and enumerable properties and returns an array with pairs of <strong>keys and values</strong></li></ul><p>As you can see, most of the above methods return an array, so you can leverage all of the methods available to JavaScript arrays.<br>One of this methods is array.length so we can simply write:</p><pre>let objLength = Object.getOwnPropertyNames(obj).length;</pre><h4>How to check if an object is empty ?</h4><ol><li>JSON.stringify(myObj) === “{}” — we are using the stringify tool again, which allows us to easily check if the object is empty (comparing strings not objects)</li><li>!Object.keys(myobj).length // true — As we said before, converting object’s keys to array can benefit us. Here we are taking advantage of the length property inherited from Array.prototype to check for the length of the keys array. In JS 0 is converted to false so when we add not ! we turn it to true while all other number will result in false.</li></ol><h3>In Conclusion</h3><p>We have been through a lot. I hope you now feel somewhat more comfortable creating and dealing with objects.</p><ul><li>Remember that objects are a reference type, which means you are advised to work immutably.</li><li>Make friends with the prototype property and the prototype chain.</li><li>Get familiar with the different tools that help us work with objects. Remember that you can stringify it, create an array of its keys, or just traverse through its properties with one of the various methods we have learned.</li></ul><p>I wish you great luck exploring JavaScript objects. Have fun with it!</p><p><em>Feel free to connect with us: </em><a href="https://www.halolabs.io/?utm_source=Medium&amp;utm_medium=Medium&amp;utm_campaign=Are%20you%20an%20XR%20product%20designer%3F%20Thinking%20of%20entering%20the%20immersive%20space%3F%20This%20is%20for%C2%A0you."><em>Halolabs.io</em></a><em> | </em><a href="https://twitter.com/HaloLabsTeam"><em>Twitter</em></a><em> | </em><a href="https://www.linkedin.com/company/18005717"><em>LinkedIn</em></a></p><h4>Liked what you read? Hold down the 👏 to say “thanks!” and help others find this article.</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fb8b184%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fb8b184%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/20733fbbb15f628904d407715afad40a/href">https://medium.com/media/20733fbbb15f628904d407715afad40a/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d31cd24ca60f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/halolabs/understanding-javascript-objects-d31cd24ca60f">Understanding JavaScript Objects</a> was originally published in <a href="https://medium.com/halolabs">Halo Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing React Components with Jest & Enzyme]]></title>
            <link>https://medium.com/halolabs/testing-react-components-with-jest-enzyme-5d1dd4ddccc4?source=rss-5939aa5979e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d1dd4ddccc4</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[enzyme]]></category>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ben Rozenberg]]></dc:creator>
            <pubDate>Wed, 30 May 2018 09:25:35 GMT</pubDate>
            <atom:updated>2018-05-30T09:25:35.231Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*xZURv-fdC3H8Lv7p6vd1Qw.jpeg" /></figure><p>At <a href="https://www.halolabs.io/">Halo Labs</a>, we are developing a design, prototyping and collaboration platform for VR and AR. For those of you who haven’t read our <a href="https://blog.halolabs.io/our-journey-from-a-vr-to-an-xr-editor-ada40305fa9">previous post</a><a href="https://blog.halolabs.io/our-journey-from-a-vr-to-an-xr-editor-ada40305fa9">s</a>, in this series we share our insights from the development process.</p><p>Recently I finished writing tests for our component library. It was my first time creating tests and using Jest and Enzyme. This post is about sharing some of my conclusions from the process, hopefully saving you some time and effort.</p><p><strong>Why testing?</strong></p><p>You might be asking yourself, ‘Why should I spend time and effort creating tests?’. It’s a fair question. The short answer is that tests should save you more time in the future than you initially invested creating them. It’s never nice to deploy new code, only to later discover you have a bug in production. Ideally, tests should help decrease these occurrences by resolving those bugs before they hit production.</p><p>More important, it will allow you to change / refactor your code without being afraid of breaking some code which you are not aware of.</p><p>How do you know if you should write tests for your components? Ask yourself if tests will be worth your time and if so to what extent do you want your tests to cover possible bugs. <br>My advice is to at least do snapshot testing (we will get to it later), which will provide wide coverage in minimum time.<br>It is important to note that there are a variety of testing methods; in this post I will be focusing on Component Level Testing.</p><p><strong>What is Jest?</strong></p><p><a href="https://facebook.github.io/jest/">Jest</a> is a testing framework created by Facebook. It has gained popularity in the React community because of its robust set of features. From my experience it is simple to use and has solid documentation.</p><p><strong>What is Enzyme?</strong></p><p><a href="http://airbnb.io/enzyme/docs/api/">Enzyme</a> is a JavaScript Testing utility for React created by AirBnB. It works great with Jest and no special setup is needed. Enzyme is useful to assert, manipulate, and traverse React Components’ output.</p><p><strong>Getting Started</strong></p><p>Setting up should be pretty straight-forward, once you follow these instructions: <a href="https://facebook.github.io/jest/docs/en/getting-started.html">Jest</a> and then <a href="http://airbnb.io/enzyme/">Enzyme</a>.</p><p>The best advice I could give you is to think about testing when you’re writing your components. Thinking about the need to test your component will make you create a better, more isolated component, which is also the “React way” to write code.</p><p><strong>Let’s test</strong></p><p>When I need to test a component I try to understand what it supposed to do and to create specific tests to check that it does so. If you only intend to write small amounts of tests try to find the weak points, think what could go wrong and test those occurrences. <br>The test should have a relevant name and should check for one scenario only. Remember that we are testing only a specific component so you would like to mock functions, actions and props coming from outside and focus only on internal behavior.</p><p>Lets take a basic example to emphasize what we talked about:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/387cdd2a017bdd2dcb2c98105770f57b/href">https://medium.com/media/387cdd2a017bdd2dcb2c98105770f57b/href</a></iframe><p>Looking at this Greet component I can see a few things we would like to test:<br>1. checking greetText function gets called<br>2. checking greetText returns the right text<br>3. checking Greet renders &lt;GreetWrapper&gt;, &lt;span&gt; and some text.<br>Notice that I don’t test GreetWrapper, ideally it should have its own testing file.</p><p>Before we can show an example we need to talk about one more thing:</p><p><strong>Shallow vs Mount</strong>: Enzyme offers two basic functions for component mounting, shallow and mount. The shallow function loads only the root component in memory, whereas mount loads the full DOM tree. This actually means that a bug, introduced to a child component, won’t break your component’s test. For this reason I would suggest using shallow rendering and not mount. The idea is to <strong>isolate </strong>the component so if the test fails we will know the cause.</p><p>Now look at this test:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32a08fcde04c66fe3b1ba708f472efe1/href">https://medium.com/media/32a08fcde04c66fe3b1ba708f472efe1/href</a></iframe><p>Here we want to test that Greet renders as should. First, we define the props we want to render Greet with. Next we use the shallow function to create a greet wrapper.<br>The last stage is to understand what is the outcome we expect to find and to make sure it is the case. If everything works as planned, the wrapper we created should render GreetWrapper component, and a &lt;span&gt; with the text “welcome John Doe” and our test will pass. If anything goes wrong one of our assumptions will fail the test and we will know which one.</p><p><strong>Testing connected components</strong>: You may see the above example and think that sometimes components are much more complex so it is not possible to test them in isolation. This is not the case. Even components connected to <a href="https://redux.js.org/">Redux</a> can and should be tested. The best way to handle those components is to export them twice as follows:</p><pre><strong>export</strong> class compName extends component {<br>//code here//<br>}<br>export default connect(mapStateToProps, mapDispatchToProps)(compName);</pre><p>Now we only need to import the component as { compName } in the test file.<br>If action functions are used, you will want to mock them. Look at the following code:</p><pre>const wrapper = shallow(&lt; mycomp addModal={jest.fn()} clearAll={jest.fn()} {…props} /&gt;);</pre><p>In the above example we created a wrapper of mycomp (shallow rendered) while passing to it addModal and clearAll as actions and some props. We are using jest.fn function to mock our functions.</p><p>Mock function capture the calls (and parameters) to our function, so later we can inspect the mock’s state to check if our function was invoked as expected.</p><p>We are now ready for a more advanced example. Look at this method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b727ccd91ae75c96b85f638ebe0efc82/href">https://medium.com/media/b727ccd91ae75c96b85f638ebe0efc82/href</a></iframe><p>One of the things I would like to test here is that the method invokes _renderToastrForPostion the right amount of times.</p><p>Here is the test:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30699ea2d19a07188b81ba22c7f8d017/href">https://medium.com/media/30699ea2d19a07188b81ba22c7f8d017/href</a></iframe><p>Take a deep breath and let’s go over it slowly.<br>First, I declare the props I want to pass in. Then I create the wrapper of ReduxToastr while passing in props and mock functions.<br>Nothing new so far.</p><p>At line 14 we create an instance of the wrapper function. This instance will allow us to play with the component methods, as we do in the next line.<br>We are now able to mock _renderToastrForPosition so that later we can check the number of times it has been invoked.<br>At line 16 we update our wrapper to match the changes we have made. <br>We are finally ready to invoke _renderToastrs and to check if the number of times renderToastrForPosition have been called is the same as toastrPosition length. It should be the case because the map function calls renderToastrForPosition once for every index of toastrPosition.</p><p><strong>Snapshot Test</strong>: As its name suggests this test takes a snapshot of your component rendered result, so if anything changes it will fail the test. It is more of a macro test, which has a very wide coverage. It’s an extremely popular type of test and you could easily find blog post specifically about it, like <a href="https://blog.kentcdodds.com/effective-snapshot-testing-e0d1a2c28eca">this</a> or <a href="https://hackernoon.com/snapshot-testing-react-components-with-jest-744a1e980366">that</a>. I would recommend you to use it, but always remember that a wide coverage has its downsides. Usually it will make it much more difficult to determine what was broken and why.<br>If you are using <a href="https://www.styled-components.com/">styled- component</a> for your CSS you might want to use Mount when snapshot testing because this way you can cover also unwanted CSS changes (mount render also children).</p><h4><strong>Some general tips:</strong></h4><ul><li><strong>Debugging:</strong> Most of the times logging to console should do the trick. After you have created a wrapper just use console.log(wrapper.debug()); for more extreme cases you would have to learn how to add break points and go deeper. To do this you will have to add some code. The setup depends on your editor of choice. <a href="https://github.com/Microsoft/vscode-recipes/tree/master/debugging-jest-test">Here</a> is a great guide how to do it in VScode.</li><li><strong>Binding: </strong>There is a difference between binding a function in render, and binding it in the constructor function. Binding in render will create a new function with every render<em>,</em> which is a bad idea for performance and could potentially cause problems for testing. <br>Pay attention that if you do decide to bind in render and you are using arrow function you will not be able to spy on this method under prototype. One way around it is to create a wrapper instance and to spy on this method under instance.</li><li><strong>Running a specific test:</strong> For running a specific test use:<br> yarn test -t name-of-spec</li><li><strong>Console warning: </strong>Running your tests might result in unwanted console warning. While there are number of ways to ignore it, the easiest one is to run your test with the silent flag as follow:<strong><br></strong> yarn test -t name-of-spec — silent</li><li><a href="https://devhints.io/enzyme"><strong>Enzyme cheatsheet</strong></a></li></ul><p>Thank you for reading! I wish you good luck in your testing journey.</p><p><em>Feel free to connect with us: </em><a href="https://www.halolabs.io/?utm_source=Medium&amp;utm_medium=Medium&amp;utm_campaign=Are%20you%20an%20XR%20product%20designer%3F%20Thinking%20of%20entering%20the%20immersive%20space%3F%20This%20is%20for%C2%A0you."><em>Halolabs.io</em></a><em> | </em><a href="https://twitter.com/HaloLabsTeam"><em>Twitter</em></a><em> | </em><a href="https://www.linkedin.com/company/18005717"><em>LinkedIn</em></a></p><h4>Liked what you read? Hold down the 👏 to say “thanks!” and help others find this article.</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fb8b184%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fb8b184%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/20733fbbb15f628904d407715afad40a/href">https://medium.com/media/20733fbbb15f628904d407715afad40a/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d1dd4ddccc4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/halolabs/testing-react-components-with-jest-enzyme-5d1dd4ddccc4">Testing React Components with Jest &amp; Enzyme</a> was originally published in <a href="https://medium.com/halolabs">Halo Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>