Skip to content

Instantly share code, notes, and snippets.

@r17x
Last active April 22, 2019 11:34
Show Gist options
  • 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
├─ [email protected]
└─ [email protected]
   └─ [email protected]
# if list like this, fix with install babel-core
$ yarn add --dev [email protected]
# run, again list of babel-core
$ yarn list babel-core
├─ [email protected]
├─ [email protected]
│  └─ [email protected]
├─ [email protected]
│  └─ [email protected]
└─ [email protected]
   └─ [email protected]

# 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