How to unit test React JSX ES6 code with KARMA?
I use ES6 with Browserify and JSX. For compilation I use Babel. The following configuration works for me.
karma.conf.js
...frameworks: ['browserify', 'jasmine'],files: [ 'Component.js', // replace with your component '__tests__/Component-test.js'],preprocessors: { 'Component.js': 'browserify', './__tests__/Component-test.js': 'browserify'},browserify : { transform : ['babelify']},...
__tests__/Component-test.js
var React = require('react/addons');var TestUtils = React.addons.TestUtils;var Component = require('../Component.js');describe('Component', () => { it('should work', () => { var component = <Component />; TestUtils.renderIntoDocument(component); expect(component).toBeTruthy(); });});
If you have any questions let me know.
@zemirico answer did not work for me and is slightly outdated.
Here is my own setup that you can use for karma.conf.js
:
...frameworks: ['jasmine', 'browserify'],files: [ 'src/*', 'tests/*'],preprocessors: { 'src/*': ['browserify'], 'tests/*': ['browserify']},browserify: { debug: true, transform: ['babelify']}...
It uses babelify
instead of reactify
, and has other dependencies. Thus, .babelrc
in the project root is also needed:
{ presets: ['es2015', 'react']}
The setup also requires the dependencies below to be included in package.json
file:
"devDependencies": { "babel-preset-react": "^6.5.0", "babelify": "^7.2.0", "browserify": "^13.0.0", "jasmine-core": "^2.4.1", "karma": "^0.13.22", "karma-browserify": "^5.0.3", "karma-chrome-launcher": "^0.2.3", "karma-jasmine": "^0.3.8", "watchify": "^3.7.0", "babel-preset-es2015": "^6.6.0", "react": "^15.0.1", "react-addons-test-utils": "^15.0.1", "react-dom": "^15.0.1" }
Usage
Create a new React component in src/my-element.jsx
:
import React from 'react';export default class MyElement extends React.Component { constructor(props) { super(props); this.state = {isActive: false}; this.onClick = this.onClick.bind(this); } onClick() { this.setState({isActive: !this.state.isActive}); } render() { return ( <div onClick={this.onClick}>{this.state.isActive ? "I am active!" : "I am not active :("}</div> ); }}
Then, test it as such by creating spec in tests/my-element-spec.js
:
import React from 'react';import ReactDOM from 'react-dom';import TestUtils from 'react-addons-test-utils';import MyElement from '../src/my-element.jsx';describe('MyElement', () => { // Render a checkbox with label in the document const element = TestUtils.renderIntoDocument(<MyElement />); const elementNode = ReactDOM.findDOMNode(element); it('verity correct default text', () => { expect(elementNode.textContent).toEqual('I am not active :('); }); it ('verify text has been changed successfuly after click', () => { // Simulate a click and verify that it is now On TestUtils.Simulate.click(elementNode); // Verify text has been changed successfully expect(elementNode.textContent).toEqual('I am active!'); });});