Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ultrox/c1bcfbc581d149a0b3b8a9c4786eff21 to your computer and use it in GitHub Desktop.
Save ultrox/c1bcfbc581d149a0b3b8a9c4786eff21 to your computer and use it in GitHub Desktop.
Mocha/Chai/Enyzme test setup with create-react-app

Basic setup for using Enzyme/Mocha/Chai with create-react-app

This is a temporary solution. Might change in the near future, this depends on how create-react-app will implement testing.

create-react-app quick-test-example

cd quick-test-example

npm run eject

npm install chai enzyme mocha react-addons-test-utils sinon --save-dev 

add test to package.json

 "scripts": {
    //...
    "test": "mocha --require ./testSetup.js --compilers babel-core/register ./test/*test.js",
    "test:watch": "npm test -- -w"
  }

add testSetup.js file

'use strict';

import jsdom from 'jsdom';

global.document = jsdom.jsdom('<html><body></body></html>');
global.window = document.defaultView;
global.navigator = window.navigator;

function noop() {
  return {};
}

// prevent mocha tests from breaking when trying to require a css file
require.extensions['.css'] = noop;
require.extensions['.svg'] = noop;

Add "The only React.js component test you'll ever need (Enzyme + Chai)" https://gist.github.com/thevangelist/e2002bc6b9834def92d46e4d92f15874

test/sometest.test.js

import React from 'react'
import { shallow } from 'enzyme'
import { expect } from 'chai'
import App from '../src/App'

const wrapper = shallow(<App />);

describe('(Component) App', () => {
  it('renders...', () => {
    expect(wrapper).to.have.length(1);
  });
});

Finally add a .babelrc file (for mocha to handle es6)

{
 "presets": ["react", "es2015"]
}

then run

npm run test

Start adding your tests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment