Where should the enzyme setup file be written?
Asked Answered
C

6

46

Yesterday I upgraded my React project to v16.0, but I found that Enzyme had some problems

    Error: 
      Enzyme Internal Error: Enzyme expects an adapter to be configured, but found none. To
      configure an adapter, you should call `Enzyme.configure({ adapter: new Adapter() })`
      before using any of Enzyme's top level APIs, where `Adapter` is the adapter
      corresponding to the library currently being tested. For example:
      import Adapter from 'enzyme-adapter-react-15';
      To find out more about this, see http://airbnb.io/enzyme/docs/installation/index.html

    at validateAdapter (spec/components/page_components/SongListItem/index.spec.js:9:1141986)
    at getAdapter (spec/components/page_components/SongListItem/index.spec.js:9:323041)
    at new ReactWrapper (spec/components/page_components/SongListItem/index.spec.js:9:622193)
    at mount (spec/components/page_components/SongListItem/index.spec.js:9:2025476)
    at UserContext.<anonymous> (spec/components/page_components/SongListItem/index.spec.js:9:1235741)

And I found a solution on the official website

// setup file
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

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

But I have a problem: Where should the enzyme setup file be written? In front of each test file?

I tried to add the above code to one of the test files, But there is still a problem

 Internal error: attempt to prepend statements in disallowed (non-array) context at C:/Users/killer/workspace/react/NetEase-Cloud-Music-Web/spec/components/page_components/SongListItem/index.spec.js

This is the address of my project

Catawba answered 8/10, 2017 at 3:52 Comment(0)
Q
63

I had a similar issue

If you are using jest to run your tests, you can create a test-setup.js file and add the snippet from the enzyme docs:

// test-setup.js
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

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

then add a setupTestFrameworkScriptFile key in your jest configuration and point to that file. For example, if your jest configuration is in package.json:

// package.json
{
    ...,
    "jest": {
        "setupTestFrameworkScriptFile": "<rootDir>/test-setup.js"
    }
}

from the jest docs https://facebook.github.io/jest/docs/en/configuration.html#setuptestframeworkscriptfile-string:

The path to a module that runs some code to configure or set up the testing framework before each test. Since setupFiles executes before the test framework is installed in the environment, this script file presents you the opportunity of running some code immediately after the test framework has been installed in the environment.

This will execute after your jest environment is initialised, but before your enzyme tests are executed

For people using create-react-app
You need to run yarn eject or npm run eject, then you will see jest configuration in your package.json.
In addition, setupTestFrameworkScriptFile is currently deprecated in favor of setupFilesAfterEnv.

Quesnay answered 8/10, 2017 at 6:30 Comment(3)
I Tried this and still got the same adapter error, already 3 hour in this issue. Somebody has some other approach?Schulein
No need to eject for modern create-react-app versions. It will execute src/setupTests by default. If it does not, you can still pass it as a CLI argument to the test script of your package.json react-scripts test --setupFilesAfterEnv='./src/setupTests.ts'Efrenefron
Seconding MrKey's comment-- see @VinceOPS answer below for more info.Widgeon
I
23

For people using create-react-app, the expected path for your setup file is src/setupTests.js. See the documentation (README) on GitHub:

Initializing Test Environment

Note: this feature is available with [email protected] and higher. If your app uses a browser API that you need to mock in your tests or if you just need a global setup before running your tests, add a src/setupTests.js to your project. It will be automatically executed before running your tests.

(As create-react-app does not handle, at least in v1.4.1, the option setupTestFrameworkScriptFile in package.json).

Impolitic answered 18/10, 2017 at 12:45 Comment(0)
F
7

Update jun 2019

Whoever using CRA(create-react-app), src/setupTests.js won't work! Create jest.config.js file in project root folder and paste the content below,

module.exports = {
    "moduleNameMapper": {
      "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
      "\\.(scss|sass|css)$": "identity-obj-proxy"
    },
    "setupFilesAfterEnv": ["<rootDir>/src/setupTests.js"]
}

ModuleNameMapper will avoid static files import statements (optional).

Since setupTestFrameworkScriptFile has been deprecated, so we have to use setupFilesAfterEnv property value as array.

Ensure you have setupTests.js file located in your project src folder or specify your setupTests.js file location in your project.

More Info

setupTests.js file should have below content,

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

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

This setup works for react 16

Filomena answered 13/6, 2019 at 9:22 Comment(5)
Any commands to be run post this setup?? I get the same error even after the setup that you have asked to do.Mustache
Good one ;) No other command to be ran for me other than npm run testMinx
Might help to install latest react versions following enzymejs.github.io/enzymeMinx
And make check I do not keep a unsupported key in "jest" entry from your package.jsonMinx
And finally my .eslintrc refers to jest as well to avoid issues with unrecognised "it": "env": { "browser": true, "jest": true },Minx
P
4

No need to ad a configuration to package.json. Just ad a "setupTests.js" file under "src" folder and add the lines

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

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

if you try to add configuration jest will be throwing an error like this.

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

Pompea answered 26/5, 2021 at 10:9 Comment(0)
C
3

I had a similar issue with React v16 throwing Enzyme internal error. You have to put the following code in src/setupTests.js:

import Enzyme from "enzyme";
import EnzymeAdapter from "enzyme-adapter-react-16";

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

Configure jest in package.json file. Add the following line:

  "jest": {
    ...
    "setupFilesAfterEnv": [
      "<rootDir>/src/setupTests.js"
    ],
    ...
  },
Coucher answered 13/1, 2020 at 14:12 Comment(0)
F
0

For those, who repeatedly facing issues with React 16 (Functional) and Jest with Enzyme libraries.

So, package.json is for react-scripts test is:

{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/user-event": "^14.2.0",
    "axios": "^0.19.0",
    "bootstrap": "^4.6.0",
    "react": "^16.14.0",
    "react-dom": "^16.14.0",
    "react-router-dom": "^5.0.1",
    "react-scripts": "3.0.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --setupFilesAfterEnv='<rootDir>/setupTests.js'",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "enzyme": "^3.11.0",
    "enzyme-adapter-react-16": "^1.15.6",
    "jest": "^24.7.1"
  }
}

src/setupTests.js mentions are:

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

though Home/index.jsx component and Home/index.test.js are available in same directory, thus:

import React from "react"
import Home from "./index"
import { shallow } from "enzyme"

describe("Shallow Home Page", () => {
  it("Home Component Check", () => {
    let home_wrapper = shallow(<Home />)
    console.log("home_wrapper is", home_wrapper.debug())
    expect(home_wrapper.exists(".text-center")).toEqual(true)
  })
})

So, what you are waiting for, let's do -

npm run test

Hope this would help manyone.

Flann answered 17/6, 2022 at 6:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.