开玩笑:找不到模块“反应”,和其他node_modules

时间:2020-10-15 04:43:54

标签: reactjs unit-testing testing jestjs

我正在尝试为正在制作的库编写一些测试。这不是一个creat-react-app项目,而是由babel从头开始构建的项目。我正在开玩笑,并且遇到了这个问题。我看到了类似的问题,但没有类似的问题。我的package.json脚本中有"test": "jest"。我的根文件夹中有一个__tests__目录。我的一个测试文件名为Component.js,从一些简单的导入开始:

import React from 'react';
import { MyComponent } from '../src/MyComponent.js';

运行npm run test时出现此错误:

Cannot find module 'react' from '__tests__/MyComponent.js'

    > 1 | import React from 'react';

即使我注释了react import,我也会收到此错误:

Cannot find module 'react' from 'src/MyComponent.js'

    Require stack:
      src/MyComponent.js
      __tests__/MyComponent.js

    > 1 | import React from 'react';

这不仅发生在react上,还发生在测试中导入的任何节点模块或测试中导入的任何模块中。我不明白难道不知道要在node_modules文件夹中寻找这些模块吗?我的package.json中没有任何jest.config.js或任何jest属性-我不认为我需要指定jest应该在node_moduldes文件夹中查找这些模块。我是否需要设置一些配置以便于开玩笑,以便在node_modules中查找这些类型的导入?我觉得这里有一个简单的解决方法,在暗示着我。感谢您的阅读。

编辑:摩卡给了我类似的问题

我想我会尝试通过使用摩卡来绕过整个问题。使用"mocha": "mocha --require @babel/register '**/__tests__/*' -R spec"的测试脚本,我得到一个类似的错误:

Error: Cannot find module 'react'
Require stack:
- /Users/seth/Documents/GitHub/react-esri-leaflet/__tests__/MyComponent.js
- /Users/seth/Documents/GitHub/react-esri-leaflet/node_modules/mocha/lib/esm-utils.js
- /Users/seth/Documents/GitHub/react-esri-leaflet/node_modules/mocha/lib/mocha.js
- /Users/seth/Documents/GitHub/react-esri-leaflet/node_modules/mocha/lib/cli/one-and-dones.js
- /Users/seth/Documents/GitHub/react-esri-leaflet/node_modules/mocha/lib/cli/options.js
- /Users/seth/Documents/GitHub/react-esri-leaflet/node_modules/mocha/bin/mocha
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:713:15)

这到底是怎么回事?这些测试库不应该在我的rootFolder / node_modules中查找这些东西吗?我的package.json或webpack.config.js文件中的某些内容可能会干扰吗?您无需将这些文件复制到这篇文章中,而是可以在此处的仓库中查看它们以及整个项目目录:https://github.com/slutske22/react-esri-leaflet

1 个答案:

答案 0 :(得分:0)

我对这个问题的思考越多,我越意识到这是一个peerDependencies问题。开玩笑找不到的依赖项全部是peerDependencies。如果我要通过travisci运行我的软件包,它将运行npm installnpm test,并且它将永远不会安装这些依赖项,也无法在测试中使用它们。

由于this question,我将所有peerDependencies复制到devDependencies,重新运行npm install,然后测试开始工作。

如果有人遇到这种特殊情况,我会把它留在这里,而不是删除问题。