enzyme-matchers icon indicating copy to clipboard operation
enzyme-matchers copied to clipboard

jest-enzyme not working with create-react-app

Open sarneetk opened this issue 6 years ago • 3 comments

I have an app based on create-react-app. I imported jest-enzyme in my src/setupTests.js:

import { configure } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'

configure({adapter: new Adapter()})

import 'jest-enzyme'

when I run my tests, I am seeing the following error:

Test suite failed to run
    ReferenceError: expect is not defined
      7 | 
      at Object.<anonymous> (node_modules/jest-enzyme/lib/index.js:34:1)

sarneetk avatar Feb 11 '19 23:02 sarneetk

I'm not familiar with CRA but I guess this is due the the Jest config key used, setupFiles for enzyme. Whereas jest-enzyme needs to be configured later in the process. setupFilesAfterEnv.

pascalduez avatar Feb 12 '19 07:02 pascalduez

@pascalduez setupFilesAfterEnv triggers this error:

We detected setupFilesAfterEnv in your package.json.

Remove it from Jest configuration, and put the initialization code in src/setupTests.js.
This file will be loaded automatically.

If I remove setupFilesAfterEnv and just include the testEnvironment key, I get this error:


Out of the box, Create React App only supports overriding these Jest options:

  • collectCoverageFrom
  • coverageReporters
  • coverageThreshold
  • coveragePathIgnorePatterns
  • extraGlobals
  • globalSetup
  • globalTeardown
  • moduleNameMapper
  • resetMocks
  • resetModules
  • snapshotSerializers
  • transform
  • transformIgnorePatterns
  • watchPathIgnorePatterns.

These options in your package.json Jest configuration are not currently supported by Create React App:

  • testEnvironment

If you wish to override other Jest options, you need to eject from the default setup. You can do so by running npm run eject but remember that this is a one-way operation. You may also file an issue with Create React App to discuss supporting more options out of the box.

FrankSalad avatar Oct 29 '19 00:10 FrankSalad

I was able to solve by following this tutorial Specifically, instead of changing package.json I created src/setupTests.js and inside I put:

import { configure } from "enzyme"
import Adapter from "enzyme-adapter-react-16"
configure({ adapter: new Adapter() })

Hope this helps 👍

FrankSalad avatar Oct 29 '19 00:10 FrankSalad