Skip to content

Instantly share code, notes, and snippets.

@busypeoples
Last active May 13, 2019 13:07
Show Gist options
  • Star 38 You must be signed in to star a gist
  • Fork 10 You must be signed in to fork a gist
  • Save busypeoples/409a34199a3dd7ceacffe25ac6c10547 to your computer and use it in GitHub Desktop.
Save busypeoples/409a34199a3dd7ceacffe25ac6c10547 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.

@jasan-s
Copy link

jasan-s commented Feb 26, 2017

I get the error that describe is not defined. Where do I set the ui to BDD

@jasan-s
Copy link

jasan-s commented Feb 27, 2017

also my mocha can't find paths to my components

@Ramyace4455
Copy link

Ramyace4455 commented Jun 7, 2017

Hello Jasan, Check out this link for Getting started with React & Mocha
Best Regards,
ReactJS Online Training in India

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