【发布时间】:2020-10-15 04:43:54
【问题描述】:
我正在尝试为我正在制作的库编写一些测试。这不是一个 creat-react-app 项目,而是使用 babel 从头开始构建的东西。我正在使用 jest,我遇到了这个问题。我看到了类似的问题,但没有像这样。我的 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';
即使我注释掉反应导入,我也会收到此错误:
Cannot find module 'react' from 'src/MyComponent.js'
Require stack:
src/MyComponent.js
__tests__/MyComponent.js
> 1 | import React from 'react';
这不仅发生在 react 中,还发生在测试中导入的任何节点模块,或测试导入的任何模块中。我不明白。 jest 不知道在 node_modules 文件夹中查找这些模块吗?我的 package.json 中没有任何 jest.config.js 或任何 jest 属性 - 我认为我不需要一个来指定 jest 应该在 node_moduldes 文件夹中查找这些模块。我是否需要设置一些配置来开玩笑地在 node_modules 中查找这些类型的导入?我觉得这里有一个简单的解决方法在暗示我。感谢阅读。
编辑:Mocha 给我一个类似的问题
我想我会尝试通过使用 mocha 来绕过整个问题。使用"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 文件中的某些内容可能会干扰吗?无需将这些文件复制到这篇文章中,您可以在此处的 repo 中查看它们以及整个项目目录:https://github.com/slutske22/react-esri-leaflet
【问题讨论】:
标签: reactjs unit-testing testing jestjs