Unit Testing React Components

Run the test with npm run test --silent.

package.json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
{
"name": "jsxtest",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {},
"devDependencies": {
"babel-preset-es2015": "^6.3.13",
"babel-preset-react": "^6.3.13",
"babel-register": "^6.4.3",
"extend-tape": "^1.1.0",
"react": "^0.14.6",
"react-addons-test-utils": "^0.14.6",
"tap-spec": "^4.1.1",
"tape": "^4.4.0",
"tape-jsx-equals": "^1.0.0"
},
"scripts": {
"test": "tape -r babel-register ./modules/__test__/*.js | tap-spec"
},
"babel": {
"presets": ["react", "es2015"]
},
"author": "",
"license": "MIT"
}
.\modules\hello.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import React from 'react';


class Hello extends React.Component {

handleClick(event) {
this.setState({honorific: 'Overlord'})
}

constructor(props) {
super(props);
this.state = {honorific: 'Captain'};
}

render() {
return <h1 onClick={this.handleClick.bind(this)}>Hello {this.state.honorific} {this.props.name}</h1>;
}
}


export default Hello;
.\modules\__test__\hello.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import {createRenderer} from 'react-addons-test-utils';
import tape from 'tape';
import addAssertions from 'extend-tape';
import jsxEquals from 'tape-jsx-equals';
import React from 'react';
import Hello from '../hello';


// extend tape with jsxEqual assertion:
const test = addAssertions(tape, {jsxEquals});


test('Hello Component', (t) => {
const renderer = createRenderer();

// initial rendering
renderer.render(<Hello name="Jim Bob" />);
let actualElement = renderer.getRenderOutput();
let expectedElement = <h1 onClick={function noRefCheck() {}}>Hello Captain Jim Bob</h1>;

// simulate click
renderer.getRenderOutput().props.onClick();
let clickedElement = renderer.getRenderOutput();
let clickedExpectedElement = <h1 onClick={function noRefCheck() {}}>Hello Overlord Jim Bob</h1>

// fail cakes
let unexpectedElement = <h1>Hello Private Jim Bob</h1>;

// compare output with the expected result:
t.jsxEquals(actualElement, expectedElement, "this should work");
t.jsxEquals(clickedElement, clickedExpectedElement, "this should work");
t.jsxEquals(actualElement, unexpectedElement, "this should die");
t.end();
});