{bit:magie}

Setup Jest and Enzyme

Using yarn create-react-app, avoiding eject

Setting up a test environment in a react app, which was booted by create-react-app.

Init the React project and add dependencies

Create the react app and add the enzyme dependencies

npx create-react-app

yarn add prop-types redux react-redux
yarn add enzyme jest-enzyme enzyme-adapter-react-16  check-prop-types --dev

depending on what to use, either

yarn add redux-thunk

or

yarn add redux-saga

and if axios is to be used

yarn add axios
yarn add moxios --dev

Write a src/setupTests.js

// For create-react-app booted projects this file must be named 'setupTests.js' 
// and located in the src directory, 
// so it will be loaded autmatically before a certain test file is loaded.
//

import Enzyme from 'enzyme'
import EnzymeAdapter from 'enzyme-adapter-react-16'

Enzyme.configure({
    adapter: new EnzymeAdapter(),
    disableLifecycleMethods: true
})

Write a testUtils/index.js

import checkPropTypes from 'check-prop-types';
import { createStore, applyMiddleware } from 'redux';

import rootReducer from '../src/reducers';
import { middlewares } from '../src/configureStore';

/**
 * Create a testing store with imported reducers, middleware, and initial state.
 *  globals: rootReducer, middlewares.
 * @param {object} initialState - Initial state for store.
 * @function storeFactory
 * @returns {Store} - Redux store.
 */
export const storeFactory = (initialState) => {
  const createStoreWithMiddleware = applyMiddleware(...middlewares)(createStore)
  return createStoreWithMiddleware(rootReducer, initialState);
}

/**
 * Return node(s) with the given data-test attribute.
 * @param {ShallowWrapper} wrapper - Enzyme shallow wrapper.
 * @param {string} val - Value of data-test attribute for search.
 * @returns {ShallowWrapper}
 */
export const findByTestAttr = (wrapper, val) => {
  return wrapper.find(`[data-test="${val}"]`);
}

export const checkProps = (component, conformingProps) => {
  const propError = checkPropTypes(
    component.propTypes,
    conformingProps,
    'prop',
    component.name);
  expect(propError).toBeUndefined();
}