Unit testing React components with Jest

Jest is a unit test framework for testing React apps. The Getting Started guide is pretty much all you need to get started. If you’ve created your project using create-react-app then you’re already setup, just run ‘npm test’ and a runner will test up that repeatedly runs your tests as you make code or test changes.

create-react-app also creates a sample test for the sample App.js component. This is a good starting point to follow for other tests:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

it('renders without crashing', () => {
  const div = document.createElement('div');
  ReactDOM.render(<App/>, div);
});

To test the results of rendering a component, the enzyme library allows you to easily capture the output from a render, and then query the results. For example:

import React from 'react';
import ReactDOM from 'react-dom';
import {shallow, mount} from 'enzyme';
import Calculator from '../Components/CalculatorComponent';
it('renders with result 3', () => {
    const result = mount(<Calculator value1="1" value2="2" />);
    result.find('button').simulate('click');
    const buttonResult = result.find("#result").first();
    expect(buttonResult.text()).toEqual("3");
});

The CalculatorComponent I’m testing here is the one from my previous React post.

Remember the Motorola Atrix in 2011 with its Webtop mode?

One of the rumors about Samsung’s upcoming S8 is that they are going to introduce a desktop mode supporting an external monitor and keyboard/mouse.

Not so long ago Microsoft were trying to convince us about Continuum and how we’d all be plugging our phones into desktop monitors and keyboards.

Let’s not forget that Microsoft was not the first to try this – several years before Continuum, Motorola tried out something similar on their Atrix phone back in 2011 (and a number of Motorola phones that followed?) where it supported a dual boot mode that could be booted into a Ubuntu Linux based desktop mode when connected to a monitor, keyboard and mouse.

Motorola apparently discontinued the feature because base features in Android starting supporting HDMI and attaching USB devices such as USB external drives, keyboards, mice etc to your phone via a USB OTG connector. Not many people are aware that your Android phone may already support connecting to a monitor, keyboard and mouse, if you so want to. Take a look on the box or in your manual for the ‘USB on-the-go’ logo and you might have these features already.

Packet Radio: Checking in to the Central California Sunday Packet Net using Linpac and Direwolf

I didn’t think it was year ago that I last checked to the Central California Packet Sunday night net, but looking for notes on how to send packet unproto frames from Linpac, this post was today exactly last year. Apparently January 15th is my favorite day for doing some packet radio.

This is using ax25, Direwolf and Linpac setup on Debian that I posted about a few days back. I did a screen recording of the net checkins so you can see what a packet net looks like. It’s not exactly fast paced, and in the middle there’s some WinLink email inbox checking going on, but you can see Ben KG6BNL running Net Control, and then check-ins that follow.

In the screencapture I’m ssh’d from my Mac into my desktop upstairs which has a Rigblaster Plug n Play connected to my Icom 880h. The top session is Direwolf, so you can see it’s decoding all the packets it hears. The bottom session is Linpac, where I’m using :unproto to send my check-in.

Are foldable/flexible phones coming in 2017?

Apple has been criticized in the press from several points of view (for example) that their recent product releases have not been innovative enough, and they’re no longer pushing the boundaries of what’s currently possible. I came across a comment somewhere (I forgot to bookmark it), that the mobile phone industry in general has reached it’s peak of what’s possible, and to continue growth there needs to be a new revolution to innovate beyond the current form factor of the smartphone as we know it today.

I’ve said many times before that each device form factor has unique benefits and limitations according to its size and user interface. For example, a phone that fits in your pocket it a poor replacement for a desktop computer with a large LCD monitor, full size keyboard and mouse, and the reverse holds true too, a desktop computer is hardly a portable computing device.

The recent rumors and articles (in 2015, in 2016 and Lenovo’s concept phone here and here, and more recently: here, here, and here) about new phones from Samsung and LG possibly coming with folding screens starts to blur what’s possible. What if you have a phone that’s small enough and portable to be a phone (as we know it in the current form factor), but it has a screen that unfolds into something larger, say with a 7″ or larger screen that can be used in place of a tablet? That would certainly shake things up, allowing you to carry a device with a large enough screen to sit down and use it at a desk, but still carry it around in your pocket. I’m really curious and hope these come to market soon.

 

Comparing React with ES5 versus React with ES6

Learning React in 2016 seemed like it was stuck halfway transitioning from examples and tutorials using ES5 JavaScript, to the similar but different ES6 JavaScript syntax. If you haven’t done any JavaScript for a while (or at all), it was easy to get confused between the different styles. Even worse, you could easily spend some time reading an article before realizing that it was using ES5 or ES6 syntax and recognizing the differences (or not). As I was learning React, I’m sure I wasn’t the first to paste some ES5 style React syntax into a app using ES6 and get into a complete mess. Once you’ve got to the point of recognizing the differences then it becomes more obvious which is which, and becomes easier to spot an older (and possibly out of date) article with a newer, up to date article.

I like to build example apps to help me understand what’s going on with any new tech or framework, so thought it would be useful to build the same app twice, once using React with ES5 and then rebuild it with React and ES6 as a comparison.

Here’s a rundown of the differences and similarities (I’m sure there’s others too, but these are the ones I’m familiar with).

First up, the entry index.html for each app is mostly the same. The only difference with the ES5 version on the left is that I manually included the webpacked bundle.js, whereas this was done for me from the create-react-app scripts:

Next up, the first index.js to set up the root container component is almost identical. The only difference the JavaScript ES5 using the RequireJS module syntax, versus the ES6 style imports:

Now looking at the AppContainer component. React with ES5 on the left, and ES6 on the right:

Using React with ES5:

  • uses the React.createClass() api
  • defines component state using getInitialState()
  • exports the component as a module using ‘module.exports’

React with ES6:

  • uses the ES6 class
  • defines component state using this.state in the constructor()
  • exports the component as a module using ‘export default’

The render() function is similar in both.

CalculatorComponent – here you’ll notice some more significant differences:

React with ES5:

  • props are implicit
  • implicit binding of ‘this’ to functions

React with ES6:

  • props are passed into the component via the constructor()
  • explicit binding of ‘this’ to functions in the constructor, using this.functionname.bind(this)

And that’s it! Hope this is a useful reference if you’re looking for a side by side comparison. You can clone my example apps from github here: https://github.com/kevinhooke/ReactJavaScriptComparisons

As I’m still learning as I go, if I’ve misunderstood anything or got anything wrong, please leave a comment and let me know!

React: _registerComponent(…): Target container is not a DOM element

Using Webpack with React, it’s critical you import your bundle.js after any DOM elements in your page that you intend to reference. See this issue discussed in this SO question here.

For example:

<body>
<h2>React with ES5</h2>
 <script src="dist/bundle.js"></script>
 <div id="app"></div>
</body>

Importing bundle.js before a DIV element that you reference in your app will result in this error:

Uncaught Error: _registerComponent(...): Target container is not a DOM element.
    at invariant (bundle.js:839)
    at Object._renderNewRootComponent (bundle.js:20668)
    at Object._renderSubtreeIntoContainer (bundle.js:20758)
    at Object.render (bundle.js:20779)

Instead, you need to ensure bundle.js is loaded after the elements you need to reference:

<body>
<h2>React with ES5</h2>
 <div id="app"></div>
 <script src="dist/bundle.js"></script>
</body>

New WoSign/StartCom certificates issued after Jan 1st 2017 blocked on Apple products

My first 1 year free SSL certificate with StartSSL is about to expire this month, so time to renew for another year. At this point last year I wasn’t sure what would happen at this point 1 year later, but appears you just apply for another new certificate, and then replace it on the servers where you are using it.

 

However, once I had requested my new certificate and uploaded it to my OpenShift account, Chrome blocked access to my site with a ‘certificate revoked’ error. I bit of digging turned up this article. Due to a number of security related issues with the Certificate Authority WoSign and later their undisclosed purchase of StartCom/StartSSL, it appears use of certificates from either of these companies are now blocked on all Apple products if issued after Jan 1st 2017, and also on Firefox and Chrome too. More info on Wikipedia here, and Mozilla here and here.

Cookie blocking and using third party logons (like OpenID)

It’s one thing to block cookies because you don’t want to be tracked, but in most cases cookies provide essential functionality for some sites, like sites using a logon via another third party site, like OpenID.

Trying to logon with your Google account to the Kinja network of sites for example doesn’t work if you’re blocking third party cookies in Chrome. The logon fails silently. To work around this (and presumably for other similar sites too), just add a ‘Cookie and site data exception’ in your Chrome settings, in this case for [*.]kinja.com

Packet Radio with Debian Hamradio Pure Blend

I stumbled across this concept of ‘Debian Pure Blends‘ a couple of days back. These are Debian distros that are configured with software preinstalled for a specific purpose, like graphic design, and astronomy. The Ham Radio distro caught my eye as it’s preconfigured with ax25 and Direwolf for Packet Radio.

The trouble is, while it has these included in the distro so you get them out of the box, it doesn’t seem they’re configured, and worse, the ax25 support doesn’t appear to work with Direwolf.

Here’s a few notes of my experimenting:

Direwolf uses a direwolf.conf file in your home directory which you customize with your callsign and setup to connect with your soundcard input and output. There doesn’t seem to be a copy of this file anywhere on the filesystem. The file is usually created if you’re building/installing from source by running ‘make install-conf’. I searched my fresh Debian install and couldn’t find a copy of direwolf.conf anywhere, so already being familiar with Direwolf, I decided to uninstall the pre-installed version (apt-get remove direwolf) and build/install from source unstead. See my previous notes on how to do this.

Immediately ran into the libasound library missing:

/usr/bin/ld: cannot find -lasound
 collect2: error: ld returned 1 exit status
 Makefile.linux:257: recipe for target 'fsk_fast_filter.h' failed
 make: *** [fsk_fast_filter.h] Error 1

This is fixed by installing libasound:

apt-get install libasound2-dev

 

Edit /etc/ax25/axports and add a line like this:
1 YOURCALL-1 1200 255 2 2m packet

Starting up direwolf for the first time:

 kev@kh-debian:/etc/ax25$ direwolf -t 0 -p
 Dire Wolf version 1.3

Reading config file /home/kev/direwolf.conf
 Audio device for both receive and transmit: default (channel 0)
 Channel 0: 1200 baud, AFSK 1200 & 2200 Hz, E+, 44100 sample rate.
 ERROR can't open device /dev/ttyUSB0 for channel 0 PTT control.
 Permission denied
 Note: PTT not configured for channel 0. (Ignore this if using VOX.)
 Ready to accept KISS client application on port 8001 ...
 Ready to accept AGW client application 0 on port 8000 ...
 Virtual KISS TNC is available on /dev/pts/1
 WARNING - Dire Wolf will hang eventually if nothing is reading from it.
 Created symlink /tmp/kisstnc -> /dev/pts/1

Looks like /dev/ttyUSB0 cannot be opened for my PTT on my Rigblaster Plug n Play.

Following instructions from here, as root, I did:

usermod -a -G dialout kev

and then logged out and logged back in again. That fixed that issue.

The input volume was low, so I bumped up the mic slider in the top right to about half way, and now the input volume is better:

KG6SJT-10 audio level = 43(20/19) [NONE] |||||||__
 [0.3] KG6SJT-10>ID:Network Node (YCARES)
 Unknown message type N, motorcycle

 

Next up, starting Direwolf and then starting up my ax25 stack with kissattach and mkiss (which I’ve covered before here), I was getting a Permission Denied error:

kev@kh-debian:~$ sudo kissattach /dev/ptmx 1 44.56.4.118
AX.25 port 1 bound to device ax0
Awaiting client connects on
/dev/pts/4

Followed by:

kev@kh-debian:~$ sudo mkiss /tmp/kisstnc /dev/pts/4
 mkiss: open: Permission denied

I posted a question about this on the Direwolf group on Yahoo Groups here. Since it looks like mkiss is getting permission denied accessing /tmp/kisstnc from Direwolf, I started Direwolf with a sudo and this avoided this error. Direwolf shouldn’t need to run with sudo permissions so something’s not quite right, but this did allow me to get up and running, and then I could ‘axcall 1 kberr’ to make a connection to nearest packet node.

To get to this point I could have installed a vanilla version of Debian, Direwolf from source, and ax25, and I probably would have got to the same point in about the same about of time, but when I have time I’ll take a look at the other apps that get preinstalled.

Learning React and Flux – how many articles and references do you need before you can build a working example?

As an experienced developer of some 21 years, I have no problem in stating that learning React and Flux has a steep learning curve. It’s complex (until you understand it). If anyone else tries to tell you anything different I’d question if they know what they are talking about. They probably don’t. In fact they’re flat out lying if they say it’s anything but complex. The official Facebook documentation for Flux is terrible. I challenge anyone to build a working React app using Flux using the solely the Facebook Flux docs and no other sources and no other prior knowledge of how to build a React app using Flux. You won’t be able to. There’s too much information that’s missing. You might be able to create Actions and send them to your Dispatcher, but you won’t get to the point of having a working Flux event flow through View Controller, creating an Action, sending it to the Dispatcher, the Store, emitting events, and triggering a Component to update based on Store changes.

In learning Flux, I’d say I went through a substantial number of articles piecing together snippets of different approaches before I got to the point where I got the concept, and then many more to get to the point of actually having a working simplest case app up and running. In addition, I’ve also worked through a React and Flux tutorial on PluralSight, and part of part of another similar course on Udemy, and also watched numerous presentations on YouTube.

The trickiest part I found was that the docs and many articles talk about each of the individual parts of Flux, creating Actions, creating the Dispatcher, creating a Store, but what seems to be missing is the key part of how do you hook them all up to together, so the one way event flow works as it should. Miss out any one part and nothing happens. Your app just doesn’t work. Or you get obscure errors and you’ll have no idea what they’re talking about.

Here’s a summary of the best articles I’ve found that were the most useful:

http://blog.andrewray.me/flux-for-stupid-people/

https://discuss.reactjs.org/t/whats-the-best-flux-tutorial/51

https://scotch.io/tutorials/getting-to-know-flux-the-react-js-architecture

https://scotch.io/tutorials/creating-a-simple-shopping-cart-with-react-js-and-flux

https://brigade.engineering/what-is-the-flux-application-architecture-b57ebca85b9e#.8twu5mlke

https://medium.com/@nosherwan/flux-stores-with-es6-syntax-d2182552091e#.ozap6h8sb

  • parts of this article don’t work because you get at least the first error below, but it was useful in showing registering a Component to listen for events from a Store

 

Here’s a list of articles and posts for working round specific (weird) errors that I ran into:

Understanding binding ‘this’ to access setState() in ES6, to avoid this error:

Uncaught TypeError: this.setState is not a function

http://stackoverflow.com/questions/33381756/this-setstate-is-not-a-function
http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback
Why this.setState is undefined in React ES6 class? https://github.com/goatslacker/alt/issues/283

  • the magic answer from user troutowicz: “React components using ES6 classes no longer autobind this to non React methods. In your constructor, add:this.onChange = this.onChange.bind(this)"

What JavaScript voodoo is this!

Understanding this error when attempting to output state in the render() for a component: “Uncaught Error: Objects are not valid as a React child”

  • this error is particularly obscure. It turns out the ‘object’ in question was a property object where I was referencing part of the object parent properties to display in a render() using { } but the property I needed was nested further down. So
    { this.state.labelValue }

gave the error above, this referencing the property data correctly (in my case) like this worked:

  { this.state.labelValue.labelValue.value }

This was hinted by this post:
http://stackoverflow.com/questions/33117449/invariant-violation-objects-are-not-valid-as-a-react-child

I finally got to a working example, simplest case example, which you can see on my Github here. I feel like I’ve just earned my Flux badge 🙂