Enzyme expects an adapter to be configured

前端 未结 15 1559
太阳男子
太阳男子 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条回答
  •  -上瘾入骨i
    2020-12-24 05:32

    Using the latest version of the libraries, I've faced the same error reported in every answer of this question. Error: TypeError: Adapter is not a constructor.

    I've grouped all the necessary steps in order to proper test your ReactJS component using Enzyme (I've used Jest but it might work with Mocha as well, in that case, just switch the main test package):

    1) Libraries (package.json):

    "dependencies": {
        "jest": "^24.6.0",
        (...)
    }
    "devDependencies": {
        "chai": "^4.2.0",
        "enzyme": "^3.7.0",
        "enzyme-adapter-react-16": "^1.7.0",
       (...)
    }
    

    2) TEST SETUP: You can setup the Enzyme in every test. But as type_master_flash wisely suggested, you can add a script to do that. In order to do so, create a new setting in your package.json file at the same level of the sessions scripts, dependencies, etc:

    Jest Version 23.x (or previous):

    "devDependencies": { 
         (...) 
     },
    "jest": {
        "setupTestFrameworkScriptFile": "./tests.setup.js"
     },
    

    After Jest 24.0 version: According to Jest Documentation, "setupTestFrameworkScriptFile is deprecated in favor of setupFilesAfterEnv".

    "devDependencies": { 
         (...) 
     },
    "jest": {
        "setupFilesAfterEnv": ["./tests.setup.js"]
     },
    

    This file can be anywhere you prefer and you can name it as you wish. Just remember to setup the proper file location. In the current example I've stored my file in the root of my project.

    3) tests.setup.js: As I've discovered in Enzyme: TypeError: Adapter is not a constructor, the problem here is that we cannot "import '' a module with a default export". The proper way of configuring your file is:

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

    Just that and you are good to test your components.

    Cheers and hope this helps.

提交回复
热议问题