ruk·si

⚛️ React
Setup

Updated at 2017-08-05 01:02

Install node v8.0.0+.

brew install nvm  # Node version manager
nvm install 8
nvm use 8

Create a project and install bunch of dependencies.

mkdir reactoid
cd reactoid
npm init -f
npm install \
  react \
  react-dom \
  prop-types \ # prop-types is not always needed in production but it's small
  babel-preset-env \                        # Target specific browsers
  babel-preset-react \                      # React stuff for Babel
  babel-plugin-transform-class-properties \ # Adds static properties
  babel-plugin-transform-imports            # Allow partial imports
npm install --save-dev \
  react-test-renderer \
  enzyme \
  jest \
  babel-jest

Create .babelrc. This configures Babel compilation. Targets last two versions of browsers and browsers that have more than 5% of market share. transform-imports stuff is extra that you might not need.

{
  "presets": [
    [
      "env",
      {
        "targets": { "browsers": ["last 2 versions", "> 5%" ] },
        "useBuiltIns": true
      }
    ],
    "react"
  ],
  "plugins": [
    "transform-class-properties",
    [
      "transform-imports",
      {
        "react-bootstrap": {
          "transform": "react-bootstrap/lib/${member}",
          "preventFullImport": true
        },
        "lodash": {
          "transform": "lodash/${member}",
          "preventFullImport": true
        }
      }
    ]
  ]
}

Add the following configuration to package.json. Defines how jest will run the tests.

{
  "scripts": {
    "test": "jest"
  },
  "jest": {
    "transform": {
      "^.+\\.jsx?$": "babel-jest"
    },
    "testPathIgnorePatterns": [
      "/node_modules/"
    ]
  }
}

Create example React component.

// ./src/Foo.jsx
import React, {Component}  from 'react';
import PropTypes from 'prop-types';

export default class Foo extends Component {
  render = () => (
    <div>
      {this.props.name}
    </div>
  );
}

Foo.propTypes = {
  name: PropTypes.string.isRequired,
};

Create a test for the component. Test files should be as close as possible to the actual file as being tested.

// ../src/Foo.test.jsx
import React from 'react';
import {shallow} from 'enzyme';
import Foo from '../src/Foo';

it('smoke test', () => {
  const wrapper = shallow(<Foo name="John" />);
  expect(wrapper.text()).toMatch(/John/);
});

Run the test.

npm test