Article Image
Article Image
read

In part 1 we created a build system that lets us write an application using React.js components. Now let’s extend that.

Add a test framework

The first thing I want is to be able to write tests for the application, so I’m going to need a test library and a way of running the tests.

I’m going to use [Karma](

npm install –save-dev karma jasmine jasmine-core karma-webpack karma-jasmine karma-chrome-launcher

mkdir -p app/spec/js/react/components

./node_modules/.bin/karma init

I’m going to use Jasmine

npm install --save-dev jasmine-node

We need somewhere to put our tests;

mkdir spec

Configure npm to run our tests for us by adding a spec line to the scripts section of our package.json file;

  "scripts": {
    "build": "./node_modules/.bin/webpack --progress --profile --colors",
    "spec":  "./node_modules/.bin/jasmine-node spec/"
  },

Edit spec/test_spec.js and add the following content;

describe("A suite", () => (
  it("contains spec with an expectation", () => (
    expect(true).toBe(true)
  ))
))

Now we can run our test like this;

npm run spec

Testing our React component

Install the react test utilities;

npm install --save-dev fs jasmine-core react-addons-test-utils

Let’s write a test for our Hello component;

mkdir -p spec/react/components

Edit spec/react/components/hello_spec.js

var React = require('react');
var Hello = require('../../../app/src/js/react/components/hello.jsx');

describe("Hello", () => (
  it("Renders a message", () => (
    expect(true).toBe(true)
  ))
))

If we try to run our tests now, we’ll get an error [SyntaxError: Unexpected token <] because our test code is not being pre-processed by webpack and babel to turn JSX syntax into javascript.

We need to add a new entrypoint to webpack.config.js so that webpack will build our tests into something we can run;

Edit webpack.config.js;

# CONTENT
Blog Logo

David Salgado


Published

Image

Ronin on Rails

Give a man a fish and he’ll eat for a day.
Give a fish a man and he’ll eat for weeks.

Back to Overview