yuhao zheng
yuhao zheng

Reputation: 41

How can I solve "cannot find module" when npm test

I am using create-react-app. When I input 'npm test', an error occurring "Cannot find module". I though jest is already installed in create-react-app. The following is my package.json. Any ideas?

{
  "proxy": "http://localhost:5000",
  "name": "276_project",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "axios": "^0.19.2",
    "bulma": "^0.9.0",
    "jwt-decode": "^2.2.0",
    "node-sass": "^4.14.1",
    "react": "^16.13.1",
    "react-bootstrap": "^1.2.2",
    "react-cart-components": "^2.1.0",
    "react-dom": "^16.13.1",
    "react-hook-form": "^5.7.2",
    "react-router-dom": "^5.2.0",
    "react-scripts": "3.4.1",
    "react-stripe-checkout": "^2.6.3",
    "react-toastify": "^6.0.6",
    "serve": "^11.3.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "heroku-postbuild": "npm run build"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Upvotes: 0

Views: 5586

Answers (1)

Goran_Ilic_Ilke
Goran_Ilic_Ilke

Reputation: 868

I m working with my own starter pack but i guess problem is the same.Simply jest cant see our included modules. First install yarn add identity-obj-proxy -D or npm install identity-obj-proxy -D."-D" flag here is for my OS Ubuntu 20.04,for other OS-es should use "--save-dev" flag or something like that. Then,you should find where in "create-react-app" is your "jest.config.js" and in part "moduleNameMapper" set as in mine config bellow. Works well with typescript && javascript.

module.exports = {
  preset: 'ts-jest',
  roots: ['<rootDir>/src'],
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
  transform: {
    '\\.(ts|tsx)$': 'ts-jest',
  },
  setupFiles: ['raf/polyfill'],
  testRegex: '/__tests__/.*\\.(ts|tsx|js)$',
  moduleNameMapper: {
    '^.+\\.(s?css|less|jpg|png|svg)$': 'identity-obj-proxy',
  },
  setupFilesAfterEnv: ['<rootDir>/src/setupTests.ts'],
  snapshotSerializers: [],
};

Upvotes: 1

Related Questions