Monthly Archives: June 2019

animejs

I was working on some code to display a green circle with a tick (for success) and a red circle with a cross (for failure) within rows in ag-Grid to denote whether service calls succeeded or failed for each row of data. Having the graphics seemed good but what I really wanted was to animate the display of these graphics to make it obvious to the user that these graphics changes/updated.

animejs looked to be a perfect solution to the problem.

There’s lots of great examples using animejs here.

Obviously to begin with I’ve created a React application using the standard scaffolding, and then using yarn installed anime, i.e.

yarn add animejs
yarn add @types/animejs

We’ll create a standard React component (SuccessFailureComponent.tsx) for displaying our new animated component.

import React from 'react';
import anime from "animejs";

interface SuccessFailureProps {
    success: boolean;
}

export class SuccessFailureComponent 
   extends React.Component<SuccessFailureProps, {}> {
      render() {
         // to be implemented
      }
}

In this code we’ve added the property success, which when true will display the green circle with a tick and when false the red circle with the cross.

To begin with we’ll add the following code to draw our graphics to the render function

const backColour = this.props.success ? 
   "#0c3" : 
   "red";
const symbol = this.props.success ? 
   "M9 16l5 5 9-9": 
   "M9 9l14 14 M23 9L9 23";

return (
   <svg className="status" xmlns="http://www.w3.org/2000/svg"
      width="32"
      height="32"
      viewBox="0 0 42 42">
      <circle className="circle"
         cx="16"
         cy="16"
         r="16"
         fill={backColour}/>
      <path d={symbol}
         fill="none"
         stroke="white"
         stroke-width="2.5"   
         stroke-linecap="round"/> :
   </svg>
);

In the above we use the Scalable Vector Graphics element to wrap drawing primitives to first draw a circle with the required fill colour and then using the symbol const which is the drawing of a tick or cross.

If we run the React app at this point (assuming we’ve also added the following component to the App.tsx render method

<SuccessFailureComponent success={false}/>
<SuccessFailureComponent success={true}/>

then we’ll see the two SVG graphics displayed.

Animating our graphics

We’ve come all this way in a post about animation and not animated anything, so let’s now do that. Back in the component, add

componentDidMount() {
   var timeline = anime.timeline({ 
      autoplay: true
   });

   timeline
      .add({
         targets: '.status',
         scale: [{ 
            value: [0, 1], 
            duration: 600, 
            easing: 'easeOutQuad' }
         ]
      });
}

When the application is refreshed you’ll see the graphics scale from nothing to full sized.

In the first line we create the anime timeline which has parameters which will simply start the animation immediately. We then use the add function with the target “status” (our SVG element) to scale the SVG from nothing to full sized with a duration of 600ms. Finally we specify the easing function to use.

We can also add more animation transitions to the timeline, for example the following additions to the timeline code (above) will result in the icons moving right by 10 pixels then returning to where they started

.add({
   targets: '.status',            
   translateX: 10
})
.add({
   targets: '.status',
   translateX: 0
});

Or maybe we’d like to just spin the graphics using

.add({
   targets: '.status',            
   rotate: 360
});

There’s more than just the timeline function, there’s also stagger which allows the animation of multiple elements. Also keyframes which allows us to create an array of keyframes for our animations.

This easings.net is a great resource for seeing how different easing functions might look. If you want to (for example) add a little bounce back to the easing try, easeOutBack.

The anime documentation also has some great examples along with the documentation of fairly simple transitions.

React and CSS

There are several ways to use CSS within React applications.

Inline CSS

We can create a structural type as a variable or const (more likely), for example

const style = {
  background: 'red',
  width: '100px',
  color: 'white'
};

export const MyStyledDiv: React.SFC<{}> = ({
}) => <div style={style}>Hello World</div>

In this case we’re using React.SFC just to reduce the code to a minimal, but fully fledged Components would work in the same way within the render function.

Style based components

With style based components we in essence create a component from the style using the back tick syntax along with the prefix styled.{element type}, so for example

const DivStyle = styled.div`
  background: red;
  width: 100px;
  color: white;
`;

export const MyStyledDiv: React.SFC<{}> = ({
}) => <DivStyle>Hello World</DivStyle>

CSS Modules

We can create separate files for our css (known as CSS Module StyleSheets).

In this case we create a .css file, for example MyStyledDiv.module.css which uses standard CSS syntax, so for example here my file

.myDivStyle {
    background-color: red;
    width: 100px;
    color: white;
}

Now in our component we import the CSS in much the same way as importing components, for example

import styles from './MyStyledDiv.module.css';

export const MyStyledDiv: React.SFC<{}> = ({
}) => <div className={styles.myDivStyle}>Hello World</div>

These style sheets are locally scoped to the component which imports them which helps us to reduce possible name clashes etc.

Standard CSS files

In this case we have standard CSS files, here we have a file named myStyleDiv.css with the following (which is the same as our module.css contents)

.myDivStyle {
    background-color: red;
    width: 100px;
    color: white;
}

Now we again import the CSS like this

import './MyStyledDiv.css';

export const MyStyledDiv: React.SFC<{}> = ({
}) => <div className="myDivStyle">Hello World</div>

Emotion

We can also use third party library’s such as emotion.

Here’s the same example using emotion

const DivStyle = styled.div(props => ({
  background: 'red',
  width: '100px',
  color: 'white'
}))

export const MyStyledDiv: React.SFC<{}> = ({
}) => <DivStyle>Hello World</DivStyle>

Jest (a little bit more)

We’ve covered rudimentary use of Jest as part of React testing, also in a stand alone, now let’s look a little more in depth at common testing requirements.

Unit Test

We write tests using Jest like this

test('Some test description', () => {
});

Note: there are various aliases such as “it”, “fit”, “xit” or “xtest” that can be used in place of “test”.

Obviously the “Some test description” text should be something meaningful, i.e. what is being tested, any specific inputs and what’s the expectation. Ofcourse how much or how little you write as a description is upto the developer. I tend to write what method is being tested, with any special conditions and expected outcome simply because when the tests run I get a good set of information on what’s working and what’s not, however this is down to the developer’s specific tastes.

We can group tests together within a describe function which may allow you to reduce the verbosity of your test descriptions as well as logically group tests, for example

describe('fetch component', () => {
    test("missing URL, expect empty response", () => {
    });

    test("missing invalid, expect error", () => {
    });
});

Note: there are a couple of aliases such as “fdescribe” and “xdescribe” which can be used in place of “describe”.

The output of the Jest test runner would be something like this

fetch component
   √ missing URL
   √ missing invalid

Timeout

The test function also accepts a third argument which can be a timeout (specified in milliseconds). The default timeout is 5 seconds. So for example

test("missing URL, expect empty response", () => {
}, 100);

Paramterized tests

Jest supports paramterized tests using the each function, so for example

test.each`
   input         | output
   ${1}          | ${10} 
   ${5}          | ${50} 
   ${10}         | ${100} 
  `("should return $output when $input is used", ({input, output}) => {
   expect(input * 10).toBe(output);
});

Using a “table”-like layout of data, the first row made up of column names which map to the input(s) and output along with subsequent rows of inputs and outputs to match against delimited using the pipe | operator.

You can also pass in arrays instead of a table structure, i.e.

test.each([[1, 10], [5, 50], [10, 100]])
   (`should return %i when %i is used`, (input, output) => {
   expect(input * 10).toBe(output);
});

We can also supply parameters using the each function of describe meaning we can pass the same parameters through multiple tests. Here’s an example of the above two way of passing parameterized data, but using describe

describe.each`
  input         | output
  ${1}          | ${10} 
  ${5}          | ${50} 
  ${10}         | ${100} 
  `("multiplication with input $input, output $output", ({input, output}) => {

  test("should match", () => {
    expect(input * 10).toBe(output);
  });
})  

describe.each([[1, 10], [5, 50], [10, 100]])
(`multiplication %i, %i`, (input, output) => {

  test("should match", () => {
    expect(input * 10).toBe(output);
  });
});

Only run these tests

During development we might wish to turn off tests whilst we work on a specific set of tests, we can use the only function on either describe or test to basically just run those tests with only specified. For example the following syntax (followed by the normal describe and test parameters)

describe.only 
describe.only.each
test.only
test.only.each

Skipping tests

We can run only certain tests and the opposite (i.e. run all tests except these), skipping tests using the skip

describe.skip
describe.skip.each
test.skip
test.skip.each

Todo

With @types/jest version 24 the todo function was added to test. With this we might have ideas for our tests and want to quickly create stub methods, so we would write

test.todo('multiple number test');

No function should be supplied to a todo test and the Jest tester runner will show the test as a “todo” test within it’s output.

Lifecycle functions

Most unit testing frameworks include the ability to carry out some process before or after a test, for example setting up a test and cleanup, Jest is no different – including beforeAll, beforeEach, afterAll and afterEach functions.

As the names suggest, beforeAll and afterAll are invoked before the tests start and after the tests all complete, respectively. As you’ll have worked out beforeEach and afterEach will be invoked before and after each test is run, respectively.

All life cycle functions accept a function to invoke and an optional timeout.

Expectations

Obviously these previously mentioned tests will all succeed unless we include expectations/assertions. Jest includes the expect function which you’ll often pass the value your system under test returned (or set) along with a function such as toBe which is what you expect the value to be, for using our previous multiplication test

expect(input * 10).toBe(output);

There’s a whole host of functions around expect listed here “Expect”.

TypeScript utility types

Whilst looking into the NonNullable<> type I noticed there’s a bunch of utility types. These types are used to construct other types.

I’m having trouble at this time understanding the use cases for some of these types, so will solely cover those that I can see use cases for.

Starting point

Let’s create a simple interface which we’ll start off with

interface Person {
    name: string;
    age: number;
}

Partial<T>

Use case

We might have a type T with one or more mandatory fields, Partial<T> takes a type T and produces a new type where all fields are optional, so using

type PartialPerson = Partial<Person>;

will create

interface PartialPerson {
    name?: string;
    age?: number;
}

Required<T>

Use case

The opposite to Partial<T> we may have a type with one or more optional fields and we want to produce a type with mandatory fields, so using

interface PartialPerson {
    name?: string;
    age?: number;
}

type RequiredPerson = Required<PartialPerson>

will create

interface RequiredPerson {
    name: string;
    age: number;
}

Readonly<T>

Use case

In some cases we might have a type T and wish to generate a new type where all those fields are marked as readonly, so using

type ReadonlyPerson = Readonly<Person>;

will create

interface ReadonlyPerson {
    readonly name: string;
    readonly age: number;
}

Record<K, T>

Use case

We might wish to generate a new type with fields of type T.

The Record<K, T> takes two types and produces a new type per value passed into the type parameter K of type parameter T, so for example

type RecordPerson = Record<'mother' | 'father', Person>;

will create

interface RecordPerson {
    mother: Person;
    father: Person;
}

Pick<T, K>

Use case

We might have a type T and wish to generate a new type made up of just selected fields.

The Pick<T, K> takes a type T and keys, K, as a union from T. The new type will then be made up of the fields declared in K, for example

type PickPerson = Pick<Person, 'name'>

will create

interface PickPerson {
    name: string;
}

ReturnType<T>

Use case

Useful in situations where we have a function and we want to get the type being returned by the function.

The ReturnType takes a type function T and returns the return type from the function, so let’s create the following code

function getPerson() : Person {
    return { name: "Scooby", age: 12 }
}

type ReturnsPerson = ReturnType<typeof getPerson>;

Prettier with ESLint

Prettier is (as it says on their website) am opiniated code formatter.

To begin with I’m going to extend the code from the last post ESLint with airbnb rules. Carry out the following steps

  • yarn add prettier -D
  • yarn add eslint-config-prettier -D

    This line will disable rules that conflict with Prettier

  • yarn add eslint-plugin-prettier -D>
  • Open .eslintc.js and update/add the following value to each key
    plugins: ['prettier']
    
    extends: [
       'prettier',
       'plugin:prettier/recommended'
    ]
    
    rules:  {
       'prettier/prettier': 'error'
    }
    
  • Run yarn lint which we added in the ESLint with airbnb rules post.

The first thing you might notice, as I did, that the ESLint rules required a single quote for strings whereas Prettier requires double quotes, obviously this is not too good if you started running this tool against existing projects, so we want a way to disable such rules in Prettier.

Create a file named .prettierrc.js and place the following code in it

module.exports = {
    singleQuote: true
};

See Prettier configuration for more info.

ESLint with airbnb rules

I’ve covered using lint with TypeScript in my post Using ESLint on TypeScript files.

In this post I’m going to configure up a React application and set-up the project to use Airbnb’s ruleset for ESLint. The Airbnb ruleset appears (but I may be wrong) to be one of the most complete sets and appears to be a bit of a standard for devs.

So let’s create an application and install all the packages we need

  • yarn create react-app your-app-name –typescript
  • yarn add eslint -D
  • yarn add eslint-config-Airbnb -D
  • yarn add eslint-plugin-import -D
  • yarn add eslint-plugin-jsx-a11y -D
  • yarn add eslint-plugin-react -D
  • Add the following to the package.json file, scripts section
    "lint": "eslint --ext .js,.jsx,.ts,.tsx ."
    
  • Add file .eslintignore to the root folder with the following
    build/**/*
    **/*.d.ts
    
  • Add the file .eslintrc.js to the root foldr also, with the following
    module.exports =  {
        parser:  '@typescript-eslint/parser',  // Specifies the ESLint parser
        plugins: ['@typescript-eslint'],
        extends:  [
          'plugin:react/recommended',  // Uses the recommended rules from @eslint-plugin-react
          'plugin:@typescript-eslint/recommended',  // Uses the recommended rules from @typescript-eslint/eslint-plugin
          'airbnb-typescript',
        ],
        parserOptions:  {
            ecmaVersion:  2018,  // Allows for the parsing of modern ECMAScript features
            sourceType:  'module',  // Allows for the use of imports
            ecmaFeatures:  {
            jsx:  true,  // Allows for the parsing of JSX
            },
        },
        rules:  {
        },
        settings:  {
          react:  {
            version:  'detect',  // Tells eslint-plugin-react to automatically detect the version of React to use
          },
        },
      };
    

If all worked, you can no run yarn lint and should see (probably) a fair few errors and warnings. We haven’t even added our own code yet!

Let’s clean a couple of things up first. The serviceWorker.ts file is generated via the React scaffolding, so me might simply want to add the filename to the .eslintignore file, that file looks like this now

build/**/*
**/*.d.ts
serviceWorker.ts

This will greatly reduce the errors/warnings. After re-running lint I have two errors and a warning within the file App.test.tsx, one of which suggest function it (the aliased test function) is not defined.

We have choices here, we can switch the rule to a warning or turn it off, we can add the file to the .eslintignore or we can add a comment block to the top of the file like this

/* eslint-disable */

Now, running lint will ignore this file.

In fact we could using the above with the following to disable a block of code from lint

/* eslint-enable */

We could also disable specific rules across a file/block using

/* eslint no-undef: "off" */

Next up I have index.tsx with an error, ‘document is not defined’. In this case I do not wish to ignore the whole file so we can ignore the specific line of code by placing this comment on the line above the document usage

// eslint-disable-next-line

This is fine but is fairly coarse in that it will ignore any other issues on that line, so we might prefer to disable the next line specific rule, i.e.

// eslint-disable-next-line no-undef

After these changes I ran lint again and had yet more errors and warnings, now in App.tsx. In my case lint states 1 error may be potentially fixable with the –fix option, so let’s see by running yarn lint –fix and then I fix the remaining errors and warnings myself.

At this point you may have had at least one error or warning which you consider to be too strict. The Airbnb rules are quite extensive and therefor quite strict. If you’re wanting to change the rule’s severity or turn the rule off, just go to the .eslintrc.js file and change the code specific to the rule that you want to edit. For example, if you’re coming from C# you might prefix your interfaces with I, by default this is classed as an error – let’s the rule off using

rules:  {
   '@typescript-eslint/interface-name-prefix': 'off'
}

or maybe you would prefer your project moves away from the I prefix but don’t want this to cause an error, then we can change ‘off’ to ‘warn’. So the three states we can set rules to are ‘off’, ‘warn’ and ‘error’.

References

Airbnb JavaScript Style Guide
ESLint Rules

React pure component

I’m using the Airbnb style guide with eslint and one warning mentioned that a very simple Component subclass with no properties or state but it just has a render method, should probably be written as a pure component.

Below is an example of a pure component in it’s most simplistic and minimal form.

import React, { ReactElement } from 'react';

const MyButton = (): ReactElement => (
  <div>My Button</div>
);

export default MyButton;

React also comes with a PureComponent base class, hence we could write

class MyButton extends React.PureComponent {
   render() {
      <div>My Button</div>
   }
}

This is slightly different to our function version of a pure component in that it also handles properties and state, see the documentation for more information.

In both cases, these changes from a standard React Component result in performance increases, so very much worth baring in mind if your components are able to be written in these ways.

Getting started with Redux in React

Lot’s of Getting started posts at the moment, and probably a lot more to come. This one’s on using Redux with React and TypeScript.

Let’s create a sample application…

  • yarn create react-app {insert app name} –typescript
  • yarn add redux
  • yarn add react-redux
  • yarn add @types/react-redux
  • We can now delete the App.* files and the *.svg
  • Add folder components to src and also reducers
  • In src/components add Counter.tsx (we’re going to recreate the redux example component for in a tsx). Here’s the code
    import React, { Component } from 'react';
    
    interface CounterProps {
        value: number;
        onIncrement: () => void;
        onDecrement: () => void;
    }
    
    export default class Counter extends Component<CounterProps, {}> {
        constructor(props: CounterProps) {
            super(props);
            this.incrementAsync = this.incrementAsync.bind(this);
            this.incrementIfOdd = this.incrementIfOdd.bind(this);
        }
    
        incrementIfOdd() {
            if (this.props.value % 2 !== 0) {
              this.props.onIncrement()
            }
          }
        
        incrementAsync() {
          setTimeout(this.props.onIncrement, 1000)
        }
    
        render() {
            const { value, onIncrement, onDecrement } = this.props
            return (
              <p>
                Clicked: {value} times
                {' '}
                <button onClick={onIncrement}>
                  +
                </button>
                {' '}
                <button onClick={onDecrement}>
                  -
                </button>
                {' '}
                <button onClick={this.incrementIfOdd}>
                  Increment if odd
                </button>
                {' '}
                <button onClick={this.incrementAsync}>
                  Increment async
                </button>
              </p>
            );
        }
    }
    
  • Now in src/reducers add the file counterReducer.ts and put the following code into it
    export default (state: number = 0, action: any) => {
        switch (action.type) {
          case 'INCREMENT':
            return state + 1
          case 'DECREMENT':
            return state - 1
          default:
            return state
        }
    }
    
  • Finally, replace the contents of the index.tsx with the following
    import React from 'react';
    import ReactDOM from 'react-dom';
    import './index.css';
    import * as serviceWorker from './serviceWorker';
    import { Provider } from 'react-redux'
    import { createStore } from 'redux'
    import counter from './reducers';
    import Counter from './components/Counter';
    
    const store = createStore(counter);
    
    const render = () => {
        ReactDOM.render(
            <Provider store={store}>
                <Counter
                    value={store.getState() as number}
                    onIncrement={() => store.dispatch({ type: 'INCREMENT' })}
                    onDecrement={() => store.dispatch({ type: 'DECREMENT' })}
                />,
            </Provider>, 
            document.getElementById('root'));
    }
    
    render();
    store.subscribe(render);
    
    serviceWorker.unregister();
    
  • If everything is correct you should be able to execute yarn start and see the web page with +, – buttons etc. and clicking + or – will increment and decrement the displayed counter.

That’s a lot to take in, so what have we actually done?

Redux supplied a storage container for our application state. In the index.tsx file we create a store passing our reducer (src/reducers/counterReducer.ts) Reducers are called in response to the store.dispatch calls. In this case within index.tsx we dispatch the actions with the type set to strings INCREMENT and DECREMENT. The reducer receives these messages then makes state changes (although not actually changing the state directly but returning a new state).

As the Redux documentation on reducers states, “Remember that actions only describe what happened, but don’t describe how the application’s state changes”.

The next piece of code to look at is

store.subscribe(render);

We’ve wrapped the render code for the application in the render function. Subscribe then allows us to listen to messages on the redux store and calls the render function to render changes. The following part of the Counter code within the index.tsx file then simply assigns the current store state to the Counter value property

value={store.getState() as number

There’s not lot to really say about the Counter component which is standard React code for displaying buttons etc. and exposing properties as used in index.tsx.

More…

This is a simplistic example. Redux documentation states that it’s not advisable to write the store.subscribe code but instead use the connect function provided by React Redux for this functionality.

In this instance we create a src/containers folder and add the file CounterContainer.ts, here’s the code

import {  connect } from 'react-redux'
import Counter from './../components/Counter';

const mapStateToProps = (state: any) => {
    return {
        value: state as number
    }
}

const mapDispatchToProps = (dispatch: any) => {
    return {
        onIncrement: () => dispatch({ type: 'INCREMENT' }),
        onDecrement: () => dispatch({ type: 'DECREMENT' }),
    }
}

export const CounterLink = connect(
    mapStateToProps,
    mapDispatchToProps
)(Counter);

export default CounterLink;

Here we write code to map state to properties and dispatch to properties (if we don’t handle either of these we simply supply a null in place of the function in the connect function.

As you can probably see, in mapStateToProps, the state is supplied and we simply apply it to the value property (which is on our Counter). In mapDispatchToProps we link the onIncrement and onDecrement to the dispatch functions.

Finally in index.tsx replace the Counter component with our newly created and exported CounterLink, i.e. here the new index.tsx

import React from 'react';
import ReactDOM from 'react-dom';
import * as serviceWorker from './serviceWorker';
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import counterReducer from './reducers/counterReducer';
import CounterLink from './containers/CounterContainer';

const store = createStore(counterReducer);

ReactDOM.render(
    <Provider store={store}>
        <CounterLink />
    </Provider>, 
    document.getElementById('root')
);

serviceWorker.unregister();

TypeScript’s never type, what’s the point ?

At first the never type may seem a slightly odd, possibly even pointless type. It can be used to denote that a function never returns, such as an infinite loop or a function simply throws an Error, hence again, never returns. These use cases don’t seem that useful, but you get the idea. The never type denotes that something should never occur.

Where never becomes a lot more useful is in situations where something should never occur in your application’s control flow, specifically regarding choice operators such as switch statements and if..else when used for exhaustive checks.

Let’s look at an example of this…

You have an type Choice which is currently made up of a union of three values, which looks like this

type Choice = 'A' | 'B' | 'C';

Let’s now create a simple function which returns a string based upon the choice value

function makeChoice(choice: Choice) {
  switch(choice) {
    case 'A': return 'A selected'
    case 'B': return 'B selected'
    case 'C': return 'C selected'
  }
  // should never reach
}

makeChoice('C');

We’re handling all the possible values of the union and all is fine with the world.

TypeScript correctly transpiles the code and if we mistakenly replace the change makeChoice(‘C’) to makeChoice(‘D’) (not included in the union) TypeScript reports the error Argument of type ‘”D”‘ is not assignable to parameter of type ‘Choice’.

What happens is – if we had a default case or if the options within the switch were exhausted and the instruction pointer made it to the comment part of the function – which in this case should never occur (as all values in the union are handled). This is where the never type comes in once all options are exhausted the choice variable in essence becomes a type never. I know, it seems strange, but read on…

So, what if we add a new value to the Choice union, let’s say ‘D’, then we have a bit of a problem, TypeScript will transpile without error but our case statement is not handling the new value and hence this may get into production without warning.

Let’s make this a little more obvious by changing our code to this

function makeChoice(choice: Choice) {
  switch(choice) {
    case 'A': return 'A selected'
    case 'B': return 'B selected'
    case 'C': return 'C selected'
  }
  let c: never = choice;
}

Note: Assuming unused variables are not set as errors in your preferred linter then everything will compile and appear without error.

What’s happening here is that the transpiler knows that all choice options are exhausted, hence choice (if you like) changes to become of type never. Hence the line of code let c: never = choice; is valid as this line/instruction should never occur.

What happens it we add a new choice, so we now add ‘D’ to the Choice union and TypeScript will now report an error. This is because the choice variable may now have another value which is not handled by the switch statement and we’ll get the following error “Type ‘”D”‘ is not assignable to type ‘never'”. Which is good because now when we transpile time we’ll be alerted to a potential issue.

Prior to adding the let c: never = choice if we transpile the code to JavaScript we get the following code, which if we change ‘C’ to ‘D’ will not report any problem (which could be fine or could be bad depending upon our usage).

function makeChoice(choice) {
   switch (choice) {
      case 'A': return 'A selected';
      case 'B': return 'B selected';
      case 'C': return 'C selected';
   }
}
makeChoice('C');

So what we really want to do in our TypeScript file is throw an Error in place of the let c: never = choice, then this will catch non-exhaustive switch statements and will be transpiled into JavaScript to give us a runtime guard to highlight a potential issue.

Let’s create a simple function to handle this so our code now looks like this

function unreachable(param: never): never { 
   throw new Error('should not reach here')
}

function makeChoice(choice: Choice) {
  switch(choice) {
    case 'A': return 'A selected'
    case 'B': return 'B selected'
    case 'C': return 'C selected'
  }
  unreachable(choice);
}

which transpiles to almost exactly the same code.

As the function unreachable never returns, we mark it as such by using the never return type.

If we now try to pass ‘D’ to the function makeChoice in the JavaScript code, an exception will occur so we’re covered at runtime now as well as at tranpsile time.

Another example of using never is in the type NonNullable which is part of TypeScript.

type NonNullable<T> = T extends null | undefined ? never : T;

In this instance if the generic type T is null or undefined then never is returned, hence the following type will actually be of type never and this not assignable to

type A = NonNullable<null>;

Getting started with Storybook

Storybook allows us to prototype and test UI components in isolation from your application. We’re going to “get started” using Storybook with React, but it also supports Vue and Angular.

Let’s create the project and add required libraries.

Note, that the npx command should not be run from VSCode (or other Atom based editor by the sounds of it), I got an error EPERM: operation not permitted, unlink.

In the steps below we also install enzyme for test rendering. We’ll also add material-ui, just for the fun of it.

  • npx -p @storybook/cli sb init
  • yarn create react-app storybooksample –typescript
  • yarn add @types/storybook__react -D
  • yarn add @types/enzyme -D
  • yarn add enzyme -D
  • yarn add enzyme-adapter-react-16 -D
  • yarn add @types/enzyme-adapter-react-16 -D
  • yarn add @material-ui/core

The storybook “getting started” web page suggests we now run the following commands to check everything was installed correctly, so let’s do this, run

  • yarn test
  • yarn storybook

Let’s now remove the storybook generated code as we’ll replace this with our own code. So in the folder src/stories, delete index.js and add a file named setupTests.ts to the src folder, here’s the code for this file

import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

configure({ adapter: new Adapter() });

Before we go too much further let’s create a sample component that will use to demonstrate testing via storybook. In the src folder add a folder named components/LogButton and in this create a file named LogButton.tsx – the name’s unimportant ofcourse, this is just a sample component which will be a new Button component, but hopefully will help demonstrate how we can use storybook.

In LogButton.tsx place the following code

import React from 'react';
import Button from '@material-ui/core/Button';

interface LogButtonProps {
    onClick?: (e: React.MouseEvent<HTMLButtonElement>) => void;
}

export class LogButton extends React.Component<LogButtonProps, {}>{    
   render() {
      return (
         <div>
            <Button variant='contained' onClick={this.props.onClick}>Log</Button>
         </div>
      );
   }
}

Let’s now create a standard unit test for this component, this is not required for storyboard, but it’s good practise. In the same src/components/LogButton folder add the file LogButton.test.tsx and here’s a very simple test to got into this file

import React from 'react';
import { mount } from "enzyme";
import { LogButton } from "./LogButton";

test('Loading component should not throw error', () => {
    const logButton = mount(<LogButton />);
    expect(logButton.exists()).toBe(true);
});

This will just check that the component, when loaded, loads successfully. We can now run yarn test to verify this code works.

Now let’s get storybook up and running with our component.

In the .storybook folder, replace the config.js code with the following

import { configure } from '@storybook/react';

const req = require.context('../src', true, /.stories.(ts|tsx|js)$/)
const loadStories = () => req.keys().forEach(filename => req(filename));
configure(loadStories, module)

This will automatically load stories based upon the filename/extensions .stories.

Alongside LogButton.tsx and LogButton.test.tsx, add LogButton.stories.tsx. This will supply the code required to integrate into storybook and also allow us to write code to allow us to test the UI component via storybook.

import React from 'react';
import { storiesOf } from '@storybook/react';
import { LogButton } from './LogButton';
import { action } from '@storybook/addon-actions';

storiesOf('LogButton', module)
    .add("Log", () => <LogButton onClick={action('clicked')} />);

Now run yarn storybook and the storybook server and UI should display along with our LogButton now being the only component available. Selecting the “Log” story, when the LogButton is clicked the action will display the text “clicked”.

So what we’ve done is create a very simply component based upon a Button which we also declared some properties – well in this case we’ve created a single property, an onClick event. The story created for the button then hooks into the button’s click event and when used via storybook allows us to test the control in isolation via storybook’s UI. This is not a unit test or automated test so much as an interactive UI test where, as developers, we can verify our functionality. Let’s say the Button’s text changed when clicked, now we could start interacting with the button via storybook and confirm everything works as expected.

There’s a lot more to storyboard than the above, but this is a good starting point.