<?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 Tyrone Tudehope on Medium]]></title>
        <description><![CDATA[Stories by Tyrone Tudehope on Medium]]></description>
        <link>https://medium.com/@tyronetudehope?source=rss-7f56b557bed3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*huwRrYPg1Oq3C-og.</url>
            <title>Stories by Tyrone Tudehope on Medium</title>
            <link>https://medium.com/@tyronetudehope?source=rss-7f56b557bed3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 06:41:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tyronetudehope/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[Generating Vue.JS Components]]></title>
            <link>https://medium.com/tyrone-tudehope/generating-vue-js-components-675b7a4ee98c?source=rss-7f56b557bed3------2</link>
            <guid isPermaLink="false">https://medium.com/p/675b7a4ee98c</guid>
            <category><![CDATA[babel]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[babel-macros]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[Tyrone Tudehope]]></dc:creator>
            <pubDate>Tue, 14 Nov 2017 22:11:28 GMT</pubDate>
            <atom:updated>2017-11-14T22:11:28.775Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yaYuqOEmc_lzhGm_iPk2Fg.jpeg" /></figure><h4>Use babel-macros and the codegen macro to generate SSR compatible components</h4><p><strong>Recently</strong> I built a button component which needed to have an icon on either the left or right of the text. The API is something like this:</p><pre>&lt;icon-button right-glyph=&quot;lock&quot;&gt;Sign In&lt;/icon-button</pre><p>The prop right-glyph accepts a string which corresponds to some SVG. The problem I was faced with was that I’d have to import all the SVGs into an object and map the glyph props to the object keys.</p><pre>const svgs = {<br>  lock: () =&gt; import(&#39;src/assets/svg/lock.svg&#39;),<br>  eye: () =&gt; import(&#39;src/assets/svg/eye.svg&#39;),<br>  ...<br>}</pre><p>This would be tedious to maintain; each SVG in assets/svg would need to have a corresponding key in the svgs object.</p><p>A nice solution to this problem is to generate the the svgs object from SVGs that exist in the folder at <em>compile time. </em>In this way, our object is always synchronised and we can use the SVG folder as reference when passing props to our component.</p><p>To implement this solution we can use <a href="https://github.com/kentcdodds/babel-macros">babel-macros</a>. babel-macros allows you to run code transformations in the form of user-defined macros. The macro we’re using is <a href="https://github.com/kentcdodds/babel-plugin-codegen">codegen</a>. The codegen macro requires the code you want to be executed at <em>runtime</em> be resolved to a string at <em>compile time</em>.</p><p>I’ve created a function which finds all files in my SVG folder, and maps their filenames to a string representation of an object. This object would look like this:</p><pre>{ <br>  name: &#39;lock&#39;, <br>  component: () =&gt; require.ensure(<br>      [], <br>      (require) =&gt; require(&#39;../../assets/svgs/lock.svg&#39;<br>    )<br>}</pre><p>The function returns a string which, when converted to code, will reduce the mapped objects into a single object for us to use.</p><p><em>Note: I’m using Webpack to enable </em><a href="https://webpack.js.org/guides/code-splitting/#dynamic-imports"><em>code splitting</em></a><em>, hence </em><em>require.ensure.</em></p><p><em>Note 2: </em><a href="https://github.com/visualfanatic/vue-svg-loader"><em>vue-svg-loader</em></a><em> loads svgs as Vue.js components.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e90d5a4274a9c996bec28c13f8187e40/href">https://medium.com/media/e90d5a4274a9c996bec28c13f8187e40/href</a></iframe><p>Using the generateSvgComponents function is easy now. We just need to tell codegen to export the result of the function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9a095a66832924b502105d869ff87fd/href">https://medium.com/media/f9a095a66832924b502105d869ff87fd/href</a></iframe><p>Now, when we run our dev environment, or build the application, codegen will generate the code necessary to set the svgs variable, making it possible for us to use it somewhere else:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f46416983c8c7372fb1e0a65679d9492/href">https://medium.com/media/f46416983c8c7372fb1e0a65679d9492/href</a></iframe><pre>&lt;svg-loader :name=&quot;selectedSvg&quot; /&gt;</pre><h3>Setup</h3><h4>Add babel-macros and configure babel</h4><pre>$ yarn add --dev babel-macros</pre><p>In your .babelrc file, add &quot;babel-macros&quot; to plugins:</p><pre>{<br>  &quot;presets&quot;: [...],<br>  &quot;plugins&quot;: [<br>    &quot;babel-macros&quot;,<br>    ...<br>  ]<br>}</pre><h4>Add your macros</h4><pre>$ yarn add --dev babel-plugin-codegen</pre><p>See <a href="https://github.com/kentcdodds/babel-plugin-codegen">this post</a> for more information babel-macros and available macros.</p><h3>Notes</h3><p>If you’re going to use vue-svg-loader or the like, a <em>much </em>simpler method would be to just import the SVG as a code split point:</p><pre>{<br>  template: `&lt;div&gt;&lt;lock-icon /&gt;&lt;/div&gt;`,<br>  components: {<br>    LockIcon: () =&gt; import(&#39;./lock.svg&#39;)<br>  }<br>}</pre><p>This is much more explicit. The approach I’ve outlined is really only useful in some specific cases, for example, the IconButton component.</p><h3><strong>The Code</strong></h3><p><strong>Source:</strong> <a href="https://github.com/johnnynotsolucky/samples/tree/master/generated-svgs">https://github.com/johnnynotsolucky/samples/tree/master/generated-svgs</a></p><p><strong>Demo:</strong> <a href="https://johnnynotsolucky.github.io/samples/generated-svgs/">https://johnnynotsolucky.github.io/samples/generated-svgs/</a></p><p><strong>P.S.</strong> Something I didn’t get a chance to figure out was to use () =&gt; import(&#39;...&#39;) instead of () =&gt; require.ensure(...). import is the preferred way for dynamic code splitting, but it generates a syntax error when run inside a macro. If anybody has a solution, that would be great!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=675b7a4ee98c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tyrone-tudehope/generating-vue-js-components-675b7a4ee98c">Generating Vue.JS Components</a> was originally published in <a href="https://medium.com/tyrone-tudehope">Tyrone Tudehope: Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bound Transitions in Vue.js]]></title>
            <link>https://medium.com/tyrone-tudehope/bound-transitions-in-vue-js-1ad9521f63c2?source=rss-7f56b557bed3------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ad9521f63c2</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Tyrone Tudehope]]></dc:creator>
            <pubDate>Fri, 24 Feb 2017 10:26:39 GMT</pubDate>
            <atom:updated>2017-02-24T10:26:39.219Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o3EXCHG5oNGxKIeeoItstA.jpeg" /></figure><h4>Dynamically set transition effects</h4><p><strong>Sometimes</strong> we need use different transitions on the same element. For example, you might have a calendar component and you want to transition month changes from left to right and from right to left depending on user interaction. You might also want to use transitions based on the state of an object, for example a transition for an empty array and another for a non-empty array.</p><p>With Vue.js we can use the v-bind directive which can be applied to any attribute of an element or component. We can use this with the transition components name attribute:</p><pre>&lt;transition v-bind:name=&quot;transitionName&quot;&gt;<br>  &lt;div v-if=&quot;someCondition&quot;&gt;<br>    {{text}}<br>  &lt;/div&gt;<br>&lt;/transition&gt;</pre><p>transitionName can be a prop, computed, a method, etc. As long as it returns a string which matches a transition defined in your css, it’ll work.</p><p>Here’s an example where an element either slides in from left to right, right to left or fades in/out depending on the state of some arbitrary array, or which button the user clicks to navigate the (also arbitrary) view.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fjsfiddle.net%2F7y4vemqc%2F&amp;src=https%3A%2F%2Fjsfiddle.net%2F7y4vemqc%2Fembedded%2F&amp;type=text%2Fhtml&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/7759450cb3f0a87e7d9ff79f3418b05f/href">https://medium.com/media/7759450cb3f0a87e7d9ff79f3418b05f/href</a></iframe><p>We’ve defined a computed property, transition, which determines which of the three transitions to use and spits out either fade, out-left or out-right. These transition names match styles defined in our css:</p><pre>.out-left-enter-active, .out-left-leave-active,<br>.out-right-enter-active, .out-right-leave-active,<br>.fade-enter-active, .fade-leave-active {<br>  transition: all .3s ease;<br>}</pre><pre>.out-left-enter, .out-left-leave-to,<br>.out-right-enter, .out-right-leave-to, <br>.fade-enter, .fade-leave-to {<br>  opacity: 0;<br>  position: absolute;<br>}</pre><pre>.out-left-leave-to, .out-right-enter {<br>  transform: translateX(-2.5em);<br>}</pre><pre>.out-left-enter, .out-right-leave-to {<br>  transform: translateX(2.5em);<br>}</pre><p><em>These transition effects are the same ones used in the </em><a href="https://vuejs.org/v2/guide/transitions.html"><em>Vue.js documentation</em></a><em>.</em></p><p>As the user navigates the view, a new array is computed based on which direction the user is navigating. When the last element of the array is removed, the item should fade out. If there are no elements and a new one is added, it should fade in.</p><p>The example might be overly complex for what it actually achieves; I wanted to illustrate the idea with more than two transitions.</p><p><em>If you’re interested in how the code works, read on!</em></p><h3>The Code</h3><p>We’ve defined a few properties:</p><ul><li>items — the arbitrary array of data which we’d like to render in our component.</li><li>prevLength — an integer which stores the previous length of the items array.</li><li>startIndex — a point in the items array which we’d like to render first.</li><li>direction — an integer which can be positive or negative. Could be substituted for a boolean, e.g. isRight: false.</li></ul><p>Our template doesn’t care about any of these properties. We have defined some useful computed properties which form the bulk of the logic we need to render the correct item:</p><ul><li>shouldFade — our requires that the last item fades out when removed, or fades in when the array is empty and a new item is added. This is where prevLength comes in.</li><li>transition — determines which of the three transition effects to apply based on shouldFade and direction.</li><li>adjustedIndex — we’ll see in a moment that startIndex can be mutated and that there is no limit on how much the value can change. This computed property adjusts that index to fall within the items array bounds relative to startIndex.</li><li>shifted — rearrange the items array using the adjustedIndex. We just chop of the first subset, and push it to the end of the array. <em>Note, we’re using non-destructive array operators.</em></li><li>firstItem — a convenience property to keep our template neat. Returns first item from our arbitrary set of data.</li></ul><p>The prevLength property needs to be updated somehow. We could update it from methods which change the items array. But that would mean we need to mutate this property everywhere the array is changed.</p><p>Vue.js exposes a watch API. Properties defined here correlate to properties defined in your data object or computed properties. Or anything that is reactive! Example: &#39;$route&#39;() { /* */ }</p><p>We’ll listen to changes to the length of our arrays length, and use the old value as our previous length. We don’t have to worry about that when we add logic to mutate the items array.</p><p>Our methods do some simple data manipulation:</p><ul><li>slide(direction) — sets the direction property and adds direction onto startIndex.</li><li>prev and next — helper methods which call slide with hard-coded values.</li><li>add and remove — non-destructive push and pop.</li><li>limit — constrains x withy. e.g. limit(9, 6) === 3</li></ul><p>The template defines a few buttons and registers click listeners which execute the prev, next, add and remove methods. We also render whatever is returned by the firstItem computed property, if anything is returned (it could be undefined if the array is empty).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ad9521f63c2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tyrone-tudehope/bound-transitions-in-vue-js-1ad9521f63c2">Bound Transitions in Vue.js</a> was originally published in <a href="https://medium.com/tyrone-tudehope">Tyrone Tudehope: Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Plugin for Vue.js]]></title>
            <link>https://medium.com/tyrone-tudehope/creating-a-plugin-to-vue-js-d9041501e3e7?source=rss-7f56b557bed3------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9041501e3e7</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Tyrone Tudehope]]></dc:creator>
            <pubDate>Sat, 18 Feb 2017 20:33:32 GMT</pubDate>
            <atom:updated>2017-11-07T11:34:11.895Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yujXsgqSGhlBw0YlkaENvQ.jpeg" /></figure><h4>Create a plugin which augments the Storage API with Vue.js to manage state</h4><p><a href="https://vuejs.org/v2/guide/plugins.html">Plugins</a> in Vue.js are very useful; they allow you inject global methods, instance methods, add directives and create mixins. For this example, we’ll be creating a basic state management plugin which stores and fetches data from the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Storage">Storage API</a>.</p><p>The idea is that when the app loads, we load a set of default data into localStorage (or sessionStorage), if the data already exists, the plugin will update itself with that data.</p><p>For example, if we had the following default data:</p><pre>{<br>  name: &#39;Default&#39;,<br>  count: 10<br>}</pre><p>and localStorage had just the name key stored with a value of Foobar, the plugin should update itself so that the actual data it contains is</p><pre>{ <br>  name: &#39;Foobar&#39;,<br>  count: 10<br>}</pre><p>and LocalStorage should be updated to have a key of count with the value 10.</p><p>Changes to the data stored by the plugin should update localStorage.</p><p>Before we dive in, have a look at the finished plugin and its usage. Run the Fiddle, and add a few names to the list. When you rerun it, the data you captured should still be there. The same applies when names are removed.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fjsfiddle.net%2Fbdpgpr4x%2F&amp;src=https%3A%2F%2Fjsfiddle.net%2Fbdpgpr4x%2Fembedded%2F&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/87e082cbb030c412dff7137631c1b663/href">https://medium.com/media/87e082cbb030c412dff7137631c1b663/href</a></iframe><p>Vue.use() requires that an install method is exposed. This method accepts the Vue object and anoptions object. The install method is where we can add any mixins, directives, etc. In our case, we need a mixin and an instance property:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/970b93c4fb145147173ed62434ff70b2/href">https://medium.com/media/970b93c4fb145147173ed62434ff70b2/href</a></iframe><p>We want to tell Vue that we would like to use this plugin, but we don’t want to configure it immediately. Therefore, we need to override the beforeCreate lifecycle hook to check if we’ve passed an instance of the plugin through to Vue when it was instantiated, like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90dd1caf090cd15233645cb36f121253/href">https://medium.com/media/90dd1caf090cd15233645cb36f121253/href</a></iframe><p>In beforeCreate we define an instance property $storage which returns the plugin instance passed to Vue. All child components will also receive this property from their parent.</p><p>createStorage() is where we pass through an implementation of Storage, our desired initial state, and an optional flag to reset the state. It creates a new Vue instance with a data object created from the initial state passed to it, and watcher functions for each of the data props which update Storage for us. It also updates the data object with any data previously stored in the storage instance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2d19463ce4b8e433dc39e663f1d02d7/href">https://medium.com/media/b2d19463ce4b8e433dc39e663f1d02d7/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5095b1b4d858d2c27cccd1fef56cff74/href">https://medium.com/media/5095b1b4d858d2c27cccd1fef56cff74/href</a></iframe><p>Because we’ve created an instance of Vue, all our data is already reactive. So we can make use of all the cool things Vue gives us, such as watchers, computed functions and reactive templates.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c39e1fd6eb82ab4d713656798a312610/href">https://medium.com/media/c39e1fd6eb82ab4d713656798a312610/href</a></iframe><p>Plugins let you add global functionality to your Vue application. With this plugin we have wrapped the Storage API and provided access to it without the need to reference localStorage.</p><p>I recommend checking out the <a href="https://github.com/vuejs/vuex">vuex</a> and <a href="https://github.com/vuejs/vue-router">vue-router</a> repositories for examples of much more complex plugins.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9041501e3e7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tyrone-tudehope/creating-a-plugin-to-vue-js-d9041501e3e7">Creating a Plugin for Vue.js</a> was originally published in <a href="https://medium.com/tyrone-tudehope">Tyrone Tudehope: Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Plex Server Up and Running with Docker]]></title>
            <link>https://medium.com/tyrone-tudehope/plex-server-up-and-running-with-docker-d21b2c0a3dd1?source=rss-7f56b557bed3------2</link>
            <guid isPermaLink="false">https://medium.com/p/d21b2c0a3dd1</guid>
            <category><![CDATA[plex]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Tyrone Tudehope]]></dc:creator>
            <pubDate>Fri, 17 Feb 2017 14:11:44 GMT</pubDate>
            <atom:updated>2017-02-27T20:22:11.090Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZvZaPjkCpmKiizM1nCGhKw.jpeg" /></figure><h4>Install a Plex Media Server in three steps</h4><p><a href="https://plex.tv/">Plex</a> is a media server which aggregates your media and allows you to access it on your home network. Installing the server is relatively simple… Installing it with Docker is even simpler. Docker also makes it easy to define a single configuration which is reusable across environments.</p><p>I’m working off a Lubuntu installation, since that is where I’m setting up my home media centre, but once docker is installed, getting Plex going should be nearly identical in any OS.</p><p>The only requirement is that Docker is installed on your machine/vm:</p><pre>$ sudo apt-get install docker.io<br>$ docker --version<br>Docker version 1.12.3, build 6b644ec</pre><p>Next we pull the latest Plex Docker image:</p><pre>$ sudo docker pull plexinc/pms-docker<br>Using default tag: latest<br>latest: Pulling from plexinc/pms-docker<br><br>8aec416115fd: Downloading 22.87 MB/50.31 MB<br>695f074e24e3: Download complete <br>946d6c48c2a7: Download complete <br>bc7277e579f0: Download complete <br>2508cbcde94b: Download complete <br>8c4564719b44: Download complete <br>58f7154b2281: Download complete <br>8ceeaf7f0f36: Downloading 36.76 MB/101.7 MB<br>Digest: sha256:a31aada7c1ed938772c3742569edd47078ae53563b9d2c53f...<br>Status: Downloaded newer image for plexinc/pms-docker:latest</pre><p>We also should create somewhere for Plex to store config and transcoded data (this is optional).</p><pre>$ mkdir ~/.plex<br>$ mkdir ~/.plex/config<br>$ mkdir ~/.plex/transcode</pre><p>And finally, we run a new container with mapped host ports to ports required by Plex within the container:</p><pre>$ sudo docker run \<br>-d \<br>--name plex \<br>-p 32400:32400/tcp \<br>-p 3005:3005/tcp \<br>-p 8324:8324/tcp \<br>-p 32469:32469/tcp \<br>-p 1900:1900/udp \<br>-p 32410:32410/udp \<br>-p 32412:32412/udp \<br>-p 32413:32413/udp \<br>-p 32414:32414/udp \<br>-e TZ=&quot;YOUR-TIME-ZONE&quot; \<br>-e PLEX_CLAIM=&quot;YOUR-CLAIM&quot; \<br>-e ADVERTISE_IP=&quot;http://192.168.1.10:32400/&quot; \<br>-h 192.168.1.10 \<br>-v ~/.plex/config:/config \<br>-v ~/.plex/transcode:/transcode \<br>-v ~/media:/data \<br>plexinc/pms-docker</pre><p>The first two -v flags are only necessary if you created the config and transcode directories.</p><p>The port mappings (-p 32400:32400/tcp) map a port from the host (left), to the container (right).</p><p>Simply replace the timezone with your timezone, and get a <a href="https://plex.tv/claim">Plex Claim</a>. The IP addresses must be the IP address of the <em>host </em>machine, not the IP allocated to container itself.</p><pre>$ sudo docker ps<br>CONTAINER ID        IMAGE                COMMAND             CREATED             STATUS                    PORTS                                                                                                                                                                                        NAMES<br>86fba9199b7e        plexinc/pms-docker   &quot;/init&quot;             11 minutes ago      Up 2 minutes (healthy)    0.0.0.0:3005-&gt;3005/tcp, 0.0.0.0:8324-&gt;8324/tcp, 0.0.0.0:1900-&gt;1900/udp, 0.0.0.0:32410-&gt;32410/udp, 0.0.0.0:32400-&gt;32400/tcp, 0.0.0.0:32412-32414-&gt;32412-32414/udp, 0.0.0.0:32469-&gt;32469/tcp   plex</pre><p>It takes a few minutes for Plex server to boot up. Once up, you should be able to browse to http://&lt;your-ip&gt;:32400. The app is available at http://&lt;your-ip&gt;:32400/web. Also, the server is now discoverable; if you have the Plex app installed on your iPhone/iPad, you should be able to see the server in the app.</p><p>Have fun!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d21b2c0a3dd1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tyrone-tudehope/plex-server-up-and-running-with-docker-d21b2c0a3dd1">Plex Server Up and Running with Docker</a> was originally published in <a href="https://medium.com/tyrone-tudehope">Tyrone Tudehope: Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Download Files With Ajax]]></title>
            <link>https://medium.com/tyrone-tudehope/download-files-with-ajax-74d371f548f3?source=rss-7f56b557bed3------2</link>
            <guid isPermaLink="false">https://medium.com/p/74d371f548f3</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[ajax]]></category>
            <dc:creator><![CDATA[Tyrone Tudehope]]></dc:creator>
            <pubDate>Fri, 17 Feb 2017 14:11:18 GMT</pubDate>
            <atom:updated>2017-02-17T14:11:18.820Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1cS8C4NurW_AYrXIkm00Fw.jpeg" /></figure><h4>Quick and simple method for downloading files using XMLHttpRequest</h4><p><em>Originally appeared on </em><a href="https://tyronetudehope.com/"><em>https://tyronetudehope.com</em></a><em>.</em></p><p>Traditionally, clients would rely on the browser to handle downloading files from a server. However this method requires opening a new browser window, iframes, or any other sort of unfriendly and hacky behaviour. It is also difficult to add extra header information to requests for downloads. A better solution would be to make use of the HTML5 File API along with XMLHttpRequest or a <a href="https://github.com/request/request">request</a> library.</p><p>The File API allows you to create, load and manipulate files in your browser. We can use a Blob to create an in-memory file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/293454d634b26d680fbe3c979516b7b0/href">https://medium.com/media/293454d634b26d680fbe3c979516b7b0/href</a></iframe><p>With a bit of extra work, we can download this file to our file system:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fjsfiddle.net%2Fpnevzccu%2F&amp;src=https%3A%2F%2Fjsfiddle.net%2Fpnevzccu%2Fembedded%2F&amp;type=text%2Fhtml&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/73cf6e3c4cd3a1df8e440a02369afd40/href">https://medium.com/media/73cf6e3c4cd3a1df8e440a02369afd40/href</a></iframe><p>When you click the trigger anchor, we create a throw-away anchor element which receives a download attribute with the filename we want to save it as and a URL generated by readAsDataURL() which essentially represents our data as a base64 encoded string. We then simulate a click event on the new anchor element to trigger a download.</p><p>Now lets get an image of a coyote from <a href="https://httpbin.org/">httpbin</a>:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fjsfiddle.net%2Fhs7dmkxm%2F&amp;src=https%3A%2F%2Fjsfiddle.net%2Fhs7dmkxm%2Fembedded%2F&amp;type=text%2Fhtml&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f7fa43978b229a5adf455a1c442d4a5/href">https://medium.com/media/1f7fa43978b229a5adf455a1c442d4a5/href</a></iframe><p>We’re creating an request to httpbin.org for a JPEG image, and using the same logic as before, we load the images data into a blob and download it to the users filesystem.</p><p>With this technique, we can elegantly add all the extra properties we need to the ajax request. You could even wrap it in a nice Vue or React component.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74d371f548f3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tyrone-tudehope/download-files-with-ajax-74d371f548f3">Download Files With Ajax</a> was originally published in <a href="https://medium.com/tyrone-tudehope">Tyrone Tudehope: Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Composing D3 Visualizations With Vue.js]]></title>
            <link>https://medium.com/tyrone-tudehope/composing-d3-visualizations-with-vue-js-c65084ccb686?source=rss-7f56b557bed3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c65084ccb686</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[3d]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[Tyrone Tudehope]]></dc:creator>
            <pubDate>Fri, 17 Feb 2017 14:10:58 GMT</pubDate>
            <atom:updated>2017-02-24T07:20:09.967Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nadJdKmKK8-60bhV7QmD2w.jpeg" /></figure><h4>Vue.js makes composing visualizations with D3 simple, elegant and fun</h4><p><em>Originally appeared on </em><a href="https://tyronetudehope.com/"><em>https://tyronetudehope.com</em></a><em>.</em></p><p><a href="https://d3js.org/"><em>D3</em></a><em> is a powerful data visualization library combining visualization components and DOM manipulation. On the other hand, </em><a href="https://vuejs.org/"><em>Vue.js</em></a><em> is a reactive front-end framework which allows you to declaritvely render data to the DOM and abstract out complex logic. Both frameworks try to do similar things, however, when combined it can become difficult to keep logic consistent. This post will attempt to address this conflict by demonstrating how we can use Vue to manipulate the DOM while embracing reactivity to update D3 components.</em></p><p>A demo can be found <a href="https://johnnynotsolucky.github.io/samples/vuejs-d3/">here</a>, and the sample code <a href="https://github.com/johnnynotsolucky/samples/tree/master/vuejs-d3">here</a>.</p><p>Before we begin, lets create a Vue component which renders a simple line chart using regular D3 DOM manipulation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d606f3b2c98b34ea4826e78fb152f5f2/href">https://medium.com/media/d606f3b2c98b34ea4826e78fb152f5f2/href</a></iframe><p>This will render the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/0*aLgsp9-9zJ7OXXSG.png" /></figure><p>The code is simple and easy to understand, but this is just a basic example. Because we aren’t making use of a template, more complex visualizations which would require a lot more manipulation and calculations, would obscure design and logic of a component. Another caveat of the above approach is that we cannot make use of the scoped property for our CSS since D3 is dynamically adding elements to the DOM.</p><p>We can recreate this example in a more <em>vuu-esque</em> fashion:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d84fa12b3ed5349a8deb95d3b7470f32/href">https://medium.com/media/d84fa12b3ed5349a8deb95d3b7470f32/href</a></iframe><p>Quite cool, even though it doesn’t expose any properties and the data is hard-coded, it nicely separates the view from the logic and makes use of Vue hooks, methods and the data object.</p><p>We are making use of D3s components to generate the data we require to populate the document with, but we’re using Vue to manage the DOM and the state of the component.</p><p>Here is component which generates a stacked area chart, adds user interaction, responds to resize events on its parent container and reacts to changes to its dataset by animating the chart to its new state:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7347db5345b3897ce3f3f9cb821640fe/href">https://medium.com/media/7347db5345b3897ce3f3f9cb821640fe/href</a></iframe><p>We have now built a reusable component which requires only an array of arbitrary numbers to be passed down to it.</p><p>This component registers a listener on the resize event which calculates the container dimensions; Updates are triggered by changes to width and data; And, a mouseover handler snaps the data “selector” to a value in the chart and emits an event back to the parent component.</p><p>An example rendering of pseudo-random numbers within a range defined by the user:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E7XVq4QR3Gf90xGu.png" /></figure><p><a href="https://johnnynotsolucky.github.io/samples/vuejs-d3/">Live example</a></p><p>There are plenty of responsive HTML charting libraries available, and most of them can be quite easily wrapped inside Vue components. However, the extensibility of D3 and the amount of features it offers makes it a good fit for anybody wanting advanced data visualisation. Coupled with Vue.js, creating D3 components is not only easy, but also quite fun!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c65084ccb686" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tyrone-tudehope/composing-d3-visualizations-with-vue-js-c65084ccb686">Composing D3 Visualizations With Vue.js</a> was originally published in <a href="https://medium.com/tyrone-tudehope">Tyrone Tudehope: Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Asserting REST API Workflows]]></title>
            <link>https://medium.com/tyrone-tudehope/asserting-rest-api-workflows-866cd7bb2837?source=rss-7f56b557bed3------2</link>
            <guid isPermaLink="false">https://medium.com/p/866cd7bb2837</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[rest]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[upssert]]></category>
            <dc:creator><![CDATA[Tyrone Tudehope]]></dc:creator>
            <pubDate>Fri, 17 Feb 2017 14:10:17 GMT</pubDate>
            <atom:updated>2017-02-17T14:10:17.105Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T_e4DYRcxsOyw95UmgWamA.jpeg" /></figure><h4>Tutorial on testing REST API endpoints with dependencies on other endpoints with Upssert</h4><p><em>Originally appeared on </em><a href="https://tyronetudehope.com/"><em>https://tyronetudehope.com</em></a><em>.</em></p><p><em>In a </em><a href="https://tyronetudehope.com/2016/11/21/testing-rest-apis-with-upssert/"><em>previous post</em></a><em> I introduced Upssert and talked about how it can be quickly configured to run tests against a REST API. In this post, I’ll demonstrate how we can easily configure test cases with dependencies to previous tests in a suite.</em></p><p>Imagine you have an endpoint which accepts a username and password and returns and authentication token. Then, by using that token you can create and fetch resources. To start, let’s create a very simple server app which stores items in an in-memory datastore. The authentication does nothing other than compare user input against some hard coded values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f0be7baf49505d79f48f070fa85d310/href">https://medium.com/media/6f0be7baf49505d79f48f070fa85d310/href</a></iframe><p>Start the server, then in another terminal, test whether you can make requests to it:</p><pre>$ node index<br>$ curl -X POST http://localhost:8080/auth-token \<br>    -d username=user \<br>    -d password=passwd<br>{&quot;auth-token&quot;:&quot;secret&quot;}<br>$ curl -X POST http://localhost:8080/items \<br>    -d name=&quot;Hello World&quot; \<br>    -H &quot;Authorization: Token secret&quot;<br>{&quot;id&quot;:&quot;/items/1&quot;}</pre><p>Kill your server, and start it again so that we have a clean datastore. Because we know exactly what data is required, and what the authorization token should be, we can test the POST /items endpoint by creating test cases with static data. If you haven’t already, install Upssert:</p><pre>$ npm install -g upssert</pre><p>We’ll create a simple test case to test creating a new item:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ba9a7940bd78e7ac8cead5c93a95701/href">https://medium.com/media/7ba9a7940bd78e7ac8cead5c93a95701/href</a></iframe><p>Running the test suite should result in a pass:</p><pre>$ upssert static-test.json<br>Executing 1 test suites (1 assertions)…</pre><pre>Create new item<br>  ✓ POST /items</pre><pre>1 passing (81ms)</pre><p>Testing REST APIs with static data is fine in development, but what happens if this server was running in an environment where you have no control over the data you’re testing against? We would have no control over authentication; we would also not be able to test the GET /items/:id endpoint because we would not be certain about the ID returned by the server. Running the previous command again would result in the test failing:</p><pre>$ upssert static-test.json<br>Executing 1 test suites (1 assertions)…</pre><pre>Create new item<br>  ✖ POST /items</pre><pre>1) POST /items<br>Error: expected &#39;/items/2&#39; to match /^\/items\/1$/ (body.id)</pre><pre>0 passing (38ms)<br>1 failing</pre><p>Since we never reset the datastore, and we’re asserting that the ID returned should be /items/1, all future tests will fail.</p><p>To mitigate these issues, Upssert passes response bodies from previous test cases through to any test case which requires them using the requires: [...] property. Therefore, we can create a test suite which authenticates a user, passes the token received from the server to the next test to create an item and tests that the GET /items/:id endpoint returns the correct data:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7858b8ce62019d92715b3fe2bf3ee330/href">https://medium.com/media/7858b8ce62019d92715b3fe2bf3ee330/href</a></iframe><p>Upssert supports <a href="https://mustache.github.io/">Mustache</a> templates, and properties are compiled against an object containing environment variables and previous test response bodies. In this case:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6be5bfde55df6665524d939e2906eff1/href">https://medium.com/media/6be5bfde55df6665524d939e2906eff1/href</a></iframe><p>Test cases with dependencies have to require the data through the requires property. This enables Upssert to fail tests automatically if one or more of their dependencies have failed. If a test case id is not specified, it will be generated; ids generated as testN where N is the 1-based position of the test in the suite.</p><p>In the test suite above, we are not explicitly defining assertions; we’re passing string values directly to properties. Upssert converts these properties to a match assertion, and the value becomes a regular expression. For example, &quot;body.name&quot;: &quot;foobar&quot; becomes</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f3871108f925ee1c405765d942000d5/href">https://medium.com/media/5f3871108f925ee1c405765d942000d5/href</a></iframe><p>If you start or end the value with ^ or $ respectively, Upssert will not add any additional characters, it will use the expression as is. match assertions are not modified and are passed through as a regular expression.</p><p>We can run our test suite:</p><pre>$ upssert dynamic-test.json<br>Executing 1 test suites (4 assertions)…</pre><pre>Get an item<br>  ✓ Authenticate<br>  ✓ Create<br>  ✓ Retrieve</pre><pre>3 passing (47ms)</pre><p>We have successfully authenticated that our API is operational using test case dependencies and variables.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=866cd7bb2837" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tyrone-tudehope/asserting-rest-api-workflows-866cd7bb2837">Asserting REST API Workflows</a> was originally published in <a href="https://medium.com/tyrone-tudehope">Tyrone Tudehope: Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vue.js, Vuex, and Testing; an Introduction]]></title>
            <link>https://medium.com/tyrone-tudehope/vue-js-vuex-and-testing-an-introduction-7a9df587d6ed?source=rss-7f56b557bed3------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a9df587d6ed</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[Tyrone Tudehope]]></dc:creator>
            <pubDate>Fri, 17 Feb 2017 14:09:57 GMT</pubDate>
            <atom:updated>2017-02-23T05:52:03.105Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bhEvGUrH2NKgHr0fPBzr-A.jpeg" /></figure><h4>An introduction to building and testing a Vue.js app with Vuex state management</h4><p><em>Originally appeared on </em><a href="https://tyronetudehope.com/"><em>https://tyronetudehope.com</em></a><em>.</em></p><p><em>In this post we create a </em><a href="https://vuejs.org/"><em>Vue.js</em></a><em> app which uses </em><a href="https://vuex.vuejs.org/"><em>Vuex</em></a><em> for state management. The app simply renders two components; one is a link which when clicked, reverses the string it displays; the other, a list of items which we emit from a faux-eventsource. We also explore a method for mocking out parts of the store for better isolation when testing individual components. You can view the live demo </em><a href="https://johnnynotsolucky.github.io/samples/vuejs-sample-1/"><em>here</em></a><em>, or alternatively, check out the </em><a href="https://github.com/johnnynotsolucky/samples/tree/master/vuejs-sample-1"><em>repository</em></a><em>.</em></p><p>Vue.js is a brilliant front-end framework and has a very active and vibrant community supporting it. It also encapsulates the <a href="http://react-etc.net/entry/comparison-js-angular-react-vue">best of angular and react</a>. The Vue.js documentation is up-to-date, extremely beneficial and with the help of one of the CLI templates, it is easy to get an app up and running within a few minutes.</p><h3>Setting Up</h3><p>The Vue.js docs are more than sufficient to get started, so we’ll just quickly run through the relevant commands to set up your project. We’ll make use of the <a href="https://github.com/vuejs-templates/webpack">webpack</a> template which bootstraps your app with all the necessary configuration and unit and integration tests.</p><pre>$ npm install -g vue-cli<br>$ vue init webpack my-project<br>$ cd my-project<br>$ npm install<br>$ npm install vuex --save</pre><p>When prompted with Setup unit tests with Karma + Mocha?, choose Y. We’ll be writing some tests later.</p><p>Before we run the app or any tests, there are a few more steps we need to do; Vuex uses Promises, so we can install babel-polyfill to ensure a consistent ES6 environment.</p><pre>$ npm install babel-polyfill --save-dev</pre><p><em>22/02/2017: Thank you </em><a href="https://medium.com/u/107ccde222ea"><em>Stefano Nepa</em></a><em> for pointing out that </em><em>babel-polyfill should be included in the webpack config as well as the karma config so that we can establish an ES6-like environment across browsers and not just the browser(s) we’re using to run our tests in. Therefore, because we’re building an app and we’re not too concerned about polluting the global scope, we can remove the </em><em>babel-runtime and rely on babel-polyfill. Also, the babel-runtime dependency was originall installed because it was required by babel-loader. However, this is not an app dependency and can safely be removed (reinstall babel-loader if you get an error such as </em><em>Cannot find module &#39;babel-runtime/helpers/typeof).</em></p><p>Webpack needs to include babel-polyfill in its output bundle for our app entrypoint:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48a3293f5b4d32bd36d33dfb43ce1079/href">https://medium.com/media/48a3293f5b4d32bd36d33dfb43ce1079/href</a></iframe><p>Andkarma.conf.js needs to be told to include the polyfill:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0677689eec723be486667942bf17dfd6/href">https://medium.com/media/0677689eec723be486667942bf17dfd6/href</a></iframe><p>Our project is now configured for ES6 and Vuex, so we can run the tests and the app.</p><pre>$ npm run unit<br>$ npm run dev</pre><h3>Creating a Store and a Fake SSE</h3><p>As with the Vue.js docs, the <a href="https://vuex.vuejs.org/en/getting-started.html">Vuex docs</a> are perfect to get you started. We’ll just add the relevant code.</p><p>In the src directory of your project, create a new dir called store, create an index.js file and an api.js file. The index.js is the store itself, whilst the api.js is our event emitter that emits random strings generated with node’s crypto module. It is designed to simulate real server side events.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f921269c24a95a9e29fa32f6172d4f3f/href">https://medium.com/media/f921269c24a95a9e29fa32f6172d4f3f/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41c2639d372912b179a5aa6841480961/href">https://medium.com/media/41c2639d372912b179a5aa6841480961/href</a></iframe><p>In order for the components we’ll create to access the store, we need to add it to our component definitions. The webpack template creates an entrypoint atsrc/main.js which defines the primary Vue component under which all our components will fall.</p><p>We could add the store to each component we create as needed, however, for brevity, we’ll add it once to our primary component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7225f3ee07a18e49ccebcb03521eacbc/href">https://medium.com/media/7225f3ee07a18e49ccebcb03521eacbc/href</a></iframe><p>We now have a store which defines an action to reverse a value and call an arbitrary API, and an action which connects to an event source and listens for updates.</p><p>Next, we’ll create a couple of components to consume the methods we’ve created.</p><h3>Using the Store</h3><p>In the src/components folder, delete the Hello.vue component and createReverse.vue and List.vue.</p><p>The Reverse component renders an anchor which, when clicked, should dispatch a call to the store we created previously and render the new value once the stores state has updated.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/665aa258bf1e2acb5aa08697bc323f4a/href">https://medium.com/media/665aa258bf1e2acb5aa08697bc323f4a/href</a></iframe><p>The List component simply renders a list of items from our store. As the store receives updates from the event source, the List component should render the new items.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/684d1fe156658533113e8d635593bd13/href">https://medium.com/media/684d1fe156658533113e8d635593bd13/href</a></iframe><p>We need to tell our App component to render the two new components, and also that the Hello component no longer exists.</p><p>In src/App.vue, replace &lt;hello /&gt; with &lt;reverse /&gt; and &lt;list /&gt;. And, in the component list, remove Hello and add Reverse and List.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e804465f5d64b58b3d3bf6430e60f633/href">https://medium.com/media/e804465f5d64b58b3d3bf6430e60f633/href</a></iframe><p>When we run our app, we should be greeted with a link which says “foobar”, and a list of random strings which is updated every few seconds. Click the link and watch the the text reverse itself!</p><pre>$ npm run dev</pre><pre>&gt; vuejs-sample-1@1.0.0 dev /home/samples/vuejs-sample-1<br>&gt; node build/dev-server.js</pre><pre>Listening at <a href="http://localhost:8080/">http://localhost:8080</a></pre><h3>Testing Our Application</h3><p>Lets quickly create our two files where we’ll be defining our test cases. In thetests/unit directory, create Reverse.spec.js and List.spec.js with mocha describe hooks. If you’re unfamiliar with testing with Mocha and the hooks it exposes for you to use, have a quick look through their <a href="https://mochajs.org/">documentation</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e46a99b22bc52c9d56480a6660416e09/href">https://medium.com/media/e46a99b22bc52c9d56480a6660416e09/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e563bda5ca703002ea90e5bffbd4fe3e/href">https://medium.com/media/e563bda5ca703002ea90e5bffbd4fe3e/href</a></iframe><p>For the purposes of this post, we’ll be testing that updates to the stores state reflect correctly in our components. It is important to understand the relationship between the components and the store, and how this affects our test cases we’ll be writing.</p><p>Both components depend on a store for managing their state, and in turn, the stores actions depend on either an API request or an eventsource. Both of these dependencies are intractable. They are out of our control and we cannot know with an absolute certainty what the data the store receives will be.</p><p>Problems when attempting to test components with these types of dependencies can include the test runner timing out, and undesirable data returned or emitted.</p><p>To demonstrate this, we can write a test case which waits for data to be emitted before we run any assertions. Add the following test case to List.spec.js:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cac6e034d1979c270a77a7301a70fef3/href">https://medium.com/media/cac6e034d1979c270a77a7301a70fef3/href</a></iframe><p>With this case, we want to wait for the event source to emit a string, at which point we’ll test that the computed function items returns the correct amount and that the generated html is correct.</p><p>There are two immediately obvious pitfalls to this approach; We’re relying directly on the event source for updates to the state, and we have no way of knowing what the emitted string will be. For the latter, we cannot reasonably test that we’re rendering the string correctly. If we execute npm run unit a few times, there is a strong chance that the tests will fail. This is due to our event emitter being designed to emit an event at random intervals between 1 and 5 seconds - Mochas default timeout is 2 seconds.</p><p>Now that we’ve seen how fickle our tests can be, lets have a look at how we can mitigate these problems. We’ll start with the Reverse component.</p><h3>Mocking the Store</h3><p>We know that the Reverse components initial state does not depend on any changes to the stores state. This makes it deceptively easy to test initially. We can add the following test case to Reverse.spec.js and run our tests. Everything should pass and Mocha should be happy.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6f47f8c889128df23d26f2b02d41986/href">https://medium.com/media/c6f47f8c889128df23d26f2b02d41986/href</a></iframe><p><em>Note, because we’re testing an individual component in isolation, the store is not injected into that component via our global App component. Luckily, we don’t need the global component, we can just inject it directly.</em></p><p>If we want to test updates to the DOM and component state after the user clicks “foobar”, we might find ourselves writing some sort of loop-timeout combination which essentially creates a race condition that waits for a server response. This might work, but we’ll never be sure that it will <em>always</em> pass.</p><p><a href="https://tyronetudehope.com/2016/11/24/vue-js-vuex-testing-an-introduction/sinonjs.org">Sinon</a> provides some relief, and thankfully, the webpack template we used included sinon and karma-sinon-chai which exposes chaiassertions and sinon spies and stubs.</p><p>To resolve the issue of asserting DOM and state changes after some asynchronous update, we can mock out the portions of the Vuex store that we rely on. In this case, we rely on the REVERSE action which executes an http request. We can mock this action to update the stores state after some duration:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a758faccabadee0c7a0b83a68caf907/href">https://medium.com/media/1a758faccabadee0c7a0b83a68caf907/href</a></iframe><p>Sinon replaces the original REVERSE action with the function we just defined. This is useful because we can now control and guarantee the data we’re using to update our state with. We can now mount the component, call the method which triggers the stores REVERSE action, and run our assertions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/300dd5afefd8fbc529f7fa2e58dd77b2/href">https://medium.com/media/300dd5afefd8fbc529f7fa2e58dd77b2/href</a></iframe><p>Because we control the data flowing back into the store, we can assert with confidence the actual value of the data. The tests should run and return no errors now.</p><p>We can use the same pattern to control the flow of data for the component which relies on an eventsource. Remove the test case we added to List.spec.js earlier, and replace it with the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b74f456f3a6a7a21d3b179e0ab604afa/href">https://medium.com/media/b74f456f3a6a7a21d3b179e0ab604afa/href</a></iframe><p>Again, we mock out the CONNECT action to execute some logic which is completely in our control allowing us to assert against both state updates and DOM updates by waiting on Vue.nextTick().</p><h3>Conclusion</h3><p>We have seen that building an app, albeit very simple, can be quick and fun. Most importantly, with minimal effort, we can write effective and trustworthy tests for the components we build.</p><p>I hope that this post has given you a foundation to building apps with Vue.js and Vuex, or any other state management framework.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a9df587d6ed" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tyrone-tudehope/vue-js-vuex-and-testing-an-introduction-7a9df587d6ed">Vue.js, Vuex, and Testing; an Introduction</a> was originally published in <a href="https://medium.com/tyrone-tudehope">Tyrone Tudehope: Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing REST APIs With Upssert]]></title>
            <link>https://medium.com/tyrone-tudehope/testing-rest-apis-with-upssert-4aa057420301?source=rss-7f56b557bed3------2</link>
            <guid isPermaLink="false">https://medium.com/p/4aa057420301</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[upssert]]></category>
            <category><![CDATA[rest]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Tyrone Tudehope]]></dc:creator>
            <pubDate>Fri, 17 Feb 2017 14:09:36 GMT</pubDate>
            <atom:updated>2017-02-17T14:09:36.684Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C5M_j1Yxyx27oxLdOzgRtw.jpeg" /></figure><h4>An introduction to the opensource Upssert API assertion framework</h4><p><em>Originally appeared on </em><a href="https://tyronetudehope.com/"><em>https://tyronetudehope.com</em></a><em>.</em></p><p><a href="https://github.com/upssert/upssert">Upssert</a> is the result of the <em>need</em> for API uptime monitoring and the <em>want</em> for test case simplicity. It was inspired by the extreme ease of use and simplicity of tools such as <a href="https://ansible.com/">Ansible</a> and <a href="https://terraform.io/">Terraform</a>.</p><p>In this post, we will have a look at some basic assertions to add an extra layer of confidence on your API.</p><p>First, we need to install Upssert:</p><pre>$ npm install upssert</pre><p>Upssert is a javascript utility, but since test suite definitions are defined as JSON, it can be used to its full capacity without writing any code.</p><p>The simplest assertion is a ping. We can run a ping assertion against the /get httpbin endpoint:</p><pre>$ upssert --url https://httpbin.org/get<br>Executing 1 test suites (2 assertions)…</pre><pre>Ping<br>  ✓ https://httpbin.org/get</pre><pre>1 passing (405.000ms)</pre><p>We’re now pretty confident that httpbin is online! The --url flag simply generates a default test suite for you:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ad0329df4d474d655c15a525a1e2be5/href">https://medium.com/media/2ad0329df4d474d655c15a525a1e2be5/href</a></iframe><p>This asserts that the servers response code is either in the succes range or the redirection range.</p><p>But we don’t always want to just know that the status code is OK. As an example, we might need to check that a URL which returns a 302 status code is actually returning the correct Location header:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6fe7b88adf975f401aaac3ca08b8729/href">https://medium.com/media/f6fe7b88adf975f401aaac3ca08b8729/href</a></iframe><pre>$ upssert redirect.json<br>Executing 1 test suites (3 assertions)…</pre><pre>Httpbin.org<br>  ✓ /redirect</pre><pre>1 passing (411.000ms)</pre><p>Here, we’ve asserted that the status code is 302, the Content-Type header is HTML, and that there exists a Location header with the value of /get.</p><p>An interesting feature: if the content type is application/json, Upssert will parse the body (thank you JSON.parse!), and allow assertions against the resulting object:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c130acfe61425c89783ae760447791b/href">https://medium.com/media/9c130acfe61425c89783ae760447791b/href</a></iframe><p>For this test case, we could use the TAP reporter:</p><pre>$ upssert foobar.json --reporter tap<br>1..1<br>ok 1 /foobar<br># tests 1<br># pass 1<br># fail 0<br># assertions 2</pre><p>Hopefully I have succeeded in illustrating the ease at which you can create and run test cases against an API.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4aa057420301" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tyrone-tudehope/testing-rest-apis-with-upssert-4aa057420301">Testing REST APIs With Upssert</a> was originally published in <a href="https://medium.com/tyrone-tudehope">Tyrone Tudehope: Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>