Cannot find module 'enzyme' from 'setupTests.ts'

12,053

You should do yarn add enzyme and you'll be good! Or npm i enzyme if you're using npm.

@types/enzyme is used to get typescript interfaces but not the actual enzyme package!

Share:
12,053
troglodyte07
Author by

troglodyte07

Updated on June 22, 2022

Comments

  • troglodyte07
    troglodyte07 almost 2 years

    I want to use enzyme to perform unit tests in my React project with TypeScript.

    I used documentation on adding tests to create-react-app - runnning tests

    I created a setupTests.ts file in /src

    setupTests.ts

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

    And I wrote a test

    App.test.ts

    import React from 'react';
    import { shallow } from 'enzyme';
    import App from './App';
    
    it('renders without crashing', () => {
      shallow(<App />);
    });
    
    

    A test using react-dom works fine if I comment the line which configures adapter in setupTests.ts

    setupTests.ts

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

    App.test.ts

    import React from 'react';
    import ReactDOM from 'react-dom';
    import App from './components/Dashboard';
    
    it('renders without crashing', () => {
      const div = document.createElement('div');
      ReactDOM.render(<App />, div);
    });
    

    package.json

    {
      "name": "sampleapp",
      "version": "0.1.0",
      "private": true,
      "dependencies": {
        "@material-ui/core": "^3.9.2",
        "@material-ui/icons": "^3.0.2",
        "@types/enzyme": "^3.9.1",
        "@types/enzyme-adapter-react-16": "^1.0.5",
        "@types/enzyme-to-json": "^1.5.3",
        "@types/jest": "24.0.11",
        "@types/node": "11.12.0",
        "@types/react": "16.8.8",
        "@types/react-dom": "16.8.3",
        "@types/react-redux": "^7.0.5",
        "@types/react-router-dom": "^4.3.1",
        "@types/redux-thunk": "^2.1.0",
        "axios": "^0.18.0",
        "react": "^16.8.5",
        "react-dom": "^16.8.5",
        "react-redux": "^6.0.1",
        "react-router-dom": "^5.0.0",
        "react-scripts": "2.1.8",
        "redux": "^4.0.1",
        "redux-thunk": "^2.3.0",
        "typescript": "3.3.4000"
      },
      "scripts": {
        "start": "react-scripts start",
        "build": "react-scripts build",
        "test": "react-scripts test",
        "eject": "react-scripts eject"
      },
      "eslintConfig": {
        "extends": "react-app"
      },
      "browserslist": [
        ">0.2%",
        "not dead",
        "not ie <= 11",
        "not op_mini all"
      ]
    }
    

    The test is supposed to run successfully. But it is failing and giving me an error

    Cannot find module 'enzyme' from 'setupTests.ts'