enzymejs / enzyme-matchers

Jasmine/Jest assertions for enzyme
MIT License
892 stars 115 forks source link

jest-enzyme not working with create-react-app #293

Open sarneetk opened 5 years ago

sarneetk commented 5 years ago

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)
pascalduez commented 5 years ago

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.

FrankSalad commented 5 years ago

@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 commented 5 years ago

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 👍