Skip to content

Instantly share code, notes, and snippets.

@r17x
Last active April 22, 2019 11:34
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save r17x/e84ebbb3eae3c308b9a3b5f51c3043bf to your computer and use it in GitHub Desktop.
Save r17x/e84ebbb3eae3c308b9a3b5f51c3043bf to your computer and use it in GitHub Desktop.
Setup Test in ReactJs With Jest Enzyme & etc
  • create setupTests.js in src/setupTests.js (automatically CRA read setupTest.js)
// setupTests.js
import React from "react";
import Adapter from "enzyme-adapter-react-16";
import Enzyme, { configure, shallow, mount, render } from "enzyme";
import { createSerializer } from "enzyme-to-json";
import sinon from "sinon";

expect.addSnapshotSerializer(createSerializer({ mode: "deep" }));

configure({ adapter: new Adapter() });

global.React = React;
global.Enzyme = Enzyme;
global.shallow = shallow;
global.render = render;
global.mount = mount;
global.sinon = sinon;
  • update package.json
// package.json
"jest": {
    "snapshotSerializers": [
      "enzyme-to-json/serializer"
    ]
  }
  • install dependencies
$ yarn add --dev  enzyme enzyme-adapter-react-16 enzyme-to-json sinon
$ yarn add --dev jest babel-jest 
  • Example Error (if you test error)
[BABEL] {redacted}/src/setupTests.js: Unknown option: base.configFile. Check out http://babeljs.io/docs/usage/options/ for more information about options.
Resolution:

$ yarn list babel-core
├─ babel-core@6.26.3
└─ react-scripts@2.1.2
   └─ babel-core@7.0.0-bridge.0
# if list like this, fix with install babel-core
$ yarn add --dev babel-core@7.0.0-bridge.0
# run, again list of babel-core
$ yarn list babel-core
├─ babel-core@7.0.0-bridge.0
├─ babel-register@6.26.0
│  └─ babel-core@6.26.3
├─ jest-config@23.6.0
│  └─ babel-core@6.26.3
└─ jest-runtime@23.6.0
   └─ babel-core@6.26.3

# finally
$ yarn test
  • don't forget eslint
"plugin:jest/recommended"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment