Triangle.js meetup - TypeScript with React

Doug Miller of Citrix

Toolset

Starter project

TypeScript

{
  "compilerOptions": {
    "jsx": "react",
    "module": "commonjs",
    "target": "es5",
    "baseUrl": ".",
    "types": [ "webpack-env" ]
  }
}
tsconfig.json

Managing type definitions

Use npm scope

npm install @types/react

Alternate

https://github.com/typings/typings

Basic Typing example

const greeting: string = 'Hello';
interface IProps {

}

Generics

function returnTypedPromise<T>(value: t) {
}

Adding React

All React TypeScript files must:

  • have .tsx extension.
  • have React in scope.

Styling

Aphrodite will give info about available CSS classes.

Testing with Jest and Enzyme

Jest

  • Uses API and verifiers from Jasmine.
  • Offers automocking (no longer default, makes tests slower).
  • Runs tests in parallel.
  • Sandboxed environment for each test.
  • Works with and compile-to-JS language using preprocessor.
  • Snapshot testing: check that returned value matches stored example.

Enzyme

React test renderer.

  • Allows shallow rendering to focus tests.
  • API to get and set state and props on a component
  • Fires React lifecycle methods
    • componentDidMount not fires with shallow rendering.

Example

jest.unmock('./Example');

describe('Example', () => {
  it('Renders counterSFC', () => {
    const view = shallow(<Example />);
    expect(view.find(ExampleSFC).length).toBe(1);
  });
});