Skip to content

Instantly share code, notes, and snippets.

@ainalain
Last active February 9, 2021 17:39
Show Gist options
  • Save ainalain/f6af16a40296cc999a815f405444fcd4 to your computer and use it in GitHub Desktop.
Save ainalain/f6af16a40296cc999a815f405444fcd4 to your computer and use it in GitHub Desktop.
Setup environment for testing React components with mocha, sinon, enzyme and jsdom
/* This file helps you to setup an environment
* for testing a React app with Mocha.
* It provides transpiling and some global variables before
* Mocha runs all the tests.
* Usage example in npm script: "test": "mocha --require tools/testSetup.js test/*.test.js"
* The major part of this file I got from Cory House pluralsight-redux-starter repo:
* https://github.com/coryhouse/pluralsight-redux-starter/blob/master/tools/testSetup.js
*/
process.env.NODE_ENV = 'test';
/*
* if tests are running without webpack,
* register babel so that it will transpile ES6 to ES5 before our tests run.
* I make it in mocha.opts file.
* code: require('babel-register')();
*/
import sinon from 'sinon';
import expect from 'expect'; // import here your assertion library
import enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
enzyme.configure({ adapter: new Adapter() });
/*
* if you use css modules with sass and would like test css classes
*/
import hook from 'css-modules-require-hook';
import sass from 'node-sass';
hook({
extensions: [ '.scss', '.css' ],
generateScopedName: '[local]__[hash:base64:8]', //your preferred generated className
preprocessCss: ( data, file ) => sass.renderSync({ file }).css
});
//if you don't test styles, add next line (commented)
//require.extensions['.scss'] = function () {return null;}
// Disable webpack-specific features for tests since
// Mocha doesn't know what to do with them.
require.extensions['.png'] = function () {return null;};
require.extensions['.jpg'] = function () {return null;};
//add .svg right comprehension to mocha tests
import fs from 'fs';
require.extensions['.svg'] = function (module, filename) {
module.exports = fs.readFileSync(filename, 'utf8');
};
global.sinon = sinon;
global.expect = expect;
global.navigator = {
userAgent: 'node.js'
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment