2017-10-13 104 views
0

我想用笑话来测试我的组件,但是当我运行它,我得到 '无法从“Router.js”阵营组件测试用玩笑

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

找到模块“反应路由器/路由器”如果我启动开发服务器,我的应用程序正在正常工作。在的package.json

我开玩笑的配置是这样的:

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

回答

2

您将要覆盖moduleDirectories,你不包括默认的,这是["node_modules"]。您包括<rootDir>/node_modules而不是相同,因为它只会查看项目根目录中的node_modules,而"node_modules"遵循Node.js的模块分辨率。 Node.js的行为是在当前目录中查找node_modules,如果未找到该模块,它会在其父目录(../node_modules)中查找等等,直到找到该模块或到达文件系统的根目录为止。欲了解更多详情,请登录Loading from node_modules Folders

重要的区别是,如果更改默认行为,嵌套模块会中断。在你的情况react-router-dom使用react-router as a dependency,而node_modules可能是这样的:

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

在这个例子中,node_modules在根目录仅包含jestreact-router-dom,所以它不会找到react-router

注:NPM开始第3版提升依赖,结果是这样的:

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

又见npm v3 Dependency Resolution

如果确实使用严重过时的npm版本,应立即升级。但是你永远不应该依赖这种行为,并且总是包含默认的模块分辨率。

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