Enzyme expects an adapter to be configured

前端 未结 15 1435
太阳男子
太阳男子 2020-12-24 04:53

I created a new React application by create-react-app and I wanted to write a unit test to a component named \"MessageBox\" that I created in the application. This is the un

相关标签:
15条回答
  • As Priyank said, if you are using Create React App, it will pick up the configuration from src/setupTests.js.

    Add:

    import { configure } from 'enzyme'
    import Adapter from 'enzyme-adapter-react-16'
    
    configure({ adapter: new Adapter() })
    
    0 讨论(0)
  • 2020-12-24 05:08

    Create a file named setupTests.js in the root of your project. jest will automatically look for this file before running any test suits. Add the following content to the file.

    import Enzyme from 'enzyme';
    import Adapter from 'enzyme-adapter-react-16';
    
    Enzyme.configure({adapter:new Adapter()})
    

    Note: the filename should be exactly the same.no need to import this setupTests.js file into your test files.it will work automatically

    0 讨论(0)
  • 2020-12-24 05:09

    For me when using React with create-react-app I had to make sure the file name was correct. The file has to be src/setupTests.js with an s at the end of Tests.

    Inside setupTests.js is the following:

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

    When running npm run test it auto finds the setupTests.js file. There is no need to import it into each test file.

    0 讨论(0)
  • 2020-12-24 05:10

    For everyone who read this in the future, setupTestFrameworkScriptFile is deprecated in favor of setupFilesAfterEnv by the documentation, in new versions. We can add our file like this:

    "setupFiles": [
        "<rootDir>/src/setupTests.js"
    ]
    
    0 讨论(0)
  • 2020-12-24 05:12

    You need to use the import like this:

    import Adapter from 'enzyme-adapter-react-16';
    

    This way: (import * as Adapter from ...) returns a message "TypeError: Adapter is not a constructor."

    0 讨论(0)
  • 2020-12-24 05:14

    A lot of answers are saying import setupTests.js into your test file. Or configure enzyme adapter in each test file. Which does solve the immediate problem.

    But long term, if you add a jest.config.js file to the project root. You can configure it to run a setup file on launch.

    jest.config.js

    module.exports = {
      setupTestFrameworkScriptFile: "<rootDir>/src/setupTests.ts"
    }
    

    This tells Jest to run setupTest.ts every time it's launched.

    This way if you need to add polyfills or add global mock like localstorage, you can add it to your setupTests file and its configured everywhere.

    The Enzyme docs don't cover integration with Jest, so it is confusing to fuse these two together.

    0 讨论(0)
提交回复
热议问题