简体   繁体   English

使用Jest进行组件测试

[英]React component testing with Jest

I want to test my components using jest, but when I run it i am getting `Cannot find module 'react-router/Router' from 'Router.js' 我想用玩笑来测试我的组件,但是当我运行它时,我从“ Router.js”得到“无法找到模块” react-router / Router”。

  at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:191:17)
  at Object.<anonymous> (node_modules/react-router-dom/Router.js:5:15)`

if I start development server my application is working corectly. 如果启动开发服务器,我的应用程序将正常运行。

My jest config in package.json looks like: 我在package.json中的笑话配置如下:

 "jest": {
    "testPathIgnorePatterns": [
      "/node_modules/"
    ],
    "moduleDirectories": [
      "<rootDir>/node_modules",
      "<rootDir>/src"
    ]
  }

You are overwriting moduleDirectories and you don't include the default, which is ["node_modules"] . 您正在覆盖moduleDirectories并且不包括默认值["node_modules"] You are including <rootDir>/node_modules instead, which is not the same, because that will only look into the node_modules in the root of your project, whereas "node_modules" follows the module resolution of Node.js. 您在包括<rootDir>/node_modules代替,这是不一样的,因为那样只会考虑的node_modules在你的项目的根目录,而"node_modules"遵循Node.js的的模块分辨率 The behaviour of Node.js is to look for node_modules in the current directory, if the module is not found it looks in its parent directory ( ../node_modules ) and so on until the module was found or the root of your file system is reached. Node.js的行为是在当前目录中查找node_modules ,如果找不到该模块,它将在其父目录( ../node_modules )中查找,依此类推,直到找到该模块或文件系统的根目录为到达。 For more details see Loading from node_modules Folders . 有关更多详细信息,请参阅node_modules文件夹加载

The important difference is that nested modules break if you change the default behaviour. 重要的区别是,如果更改默认行为,则嵌套模块会中断。 In your case react-router-dom uses react-router as a dependency , and the node_modules might look like this: 在您的情况下, react-router-dom使用react-router作为依赖项 ,而node_modules可能看起来像这样:

node_modules
├─ jest
└─ react-router-dom
    └─ node_modules
        └─ react-router

In this example, node_modules in the root directory only contains jest and react-router-dom , so it wouldn't find react-router . 在此示例中,根目录中的node_modules仅包含jestreact-router-dom ,因此不会找到react-router

Note: npm started hoisting dependencies with version 3 and the result would look like this: 注意:npm开始提升版本3的依赖关系,结果如下所示:

node_modules
├─ jest
├─ react-router-dom
└─ react-router

See also npm v3 Dependency Resolution . 另请参阅npm v3依赖性解析

If you are indeed using a severely outdated npm version, you should upgrade immediately. 如果确实使用了严重过时的npm版本,则应立即升级。 But you should never rely on that behaviour, and always include the default module resolution. 但是,您永远不要依赖该行为,并且始终包括默认的模块分辨率。

"jest": {
  "testPathIgnorePatterns": [
    "/node_modules/"
  ],
  "moduleDirectories": [
    "node_modules",
    "<rootDir>/src"
  ]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM