【问题标题】:How can I solve "cannot find module" when npm testnpm测试时如何解决“找不到模块”
【发布时间】:2020-07-20 19:24:10
【问题描述】:

我正在使用 create-react-app。当我输入“npm test”时,出现“找不到模块”错误。我虽然 jest 已经安装在 create-react-app 中。以下是我的 package.json。有什么想法吗?

{
  "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"
    ]
  }
}

【问题讨论】:

  • 你还有create-react-app设置的测试文件吗?也许给我们您的文件目录结构、完整错误消息以及生成该错误消息的文件的快照,可能会有所帮助。 Jest 很可能正在运行,但随后在您的一个测试文件中遇到了障碍。

标签: javascript reactjs testing create-react-app


【解决方案1】:

我正在使用我自己的入门包,但我想问题是一样的。只是开玩笑看不到我们包含的模块。 首先安装yarn add identity-obj-proxy -Dnpm install identity-obj-proxy -D。“-D”标志适用于我的操作系统 Ubuntu 20.04,其他操作系统应使用“--save-dev”标志或类似的东西。 然后,您应该在“create-react-app”中找到您的“jest.config.js”和部分“moduleNameMapper”设置,如下面的我的配置。 与 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: [],
};

【讨论】:

    猜你喜欢
    • 2022-07-22
    • 2021-08-27
    • 1970-01-01
    • 2019-09-10
    • 2022-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多