我正在尝试从Jest React tutorial运行React示例但我收到错误
λ npm test
> ...
> jest
Found 1 matching tests...
FAIL __tests__\CheckboxWithLabel-test.js (0.551s)
npm ERR! Test failed. See above for more details.
npm ERR! not ok code 0
我几乎直接从示例中复制了代码。 package.json如下:
{
"dependencies": {
"react": "*",
"react-tools": "*"
},
"scripts":{
"test": "jest"
},
"jest": {
"scriptPreprocessor": "<rootDir>/preprocessor.js",
"unmockedModulePathPatterns": [
"<rootDir>/node_modules/react"
]
},
"devDependencies": {
"jest-cli": "~0.1.17"
}
}
有什么想法我可以做些什么来解决这些错误并成功运行示例测试?我很可能错过了一个重要的细节(或细节),但不完全确定是什么。哦,对于它的价值,我在Windows上运行它,如果这会影响到这一点。我真的想对我的反应组件进行一些测试(在那里也有一些麻烦,所以从基本的例子开始) - 任何帮助将不胜感激:)
答案 0 :(得分:26)
我在他们的github页面上创建了一个issue。等待发现它是否真的与Windows相关的问题
与此同时,最终通过指定模块的名称而不是相对路径来使其工作
"unmockedModulePathPatterns": ["react"]
答案 1 :(得分:5)
To anybody who ends up here on a search about this, @ron's github issue was ultimately resolved, and the conclusion was that unmockedModulePathPatterns expects an array of regex statments matching file paths, not necessarily the file paths themselves. This is why using the "relative" paths worked. From the Jest API docs:
An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them. If a module's path matches any of the patterns in this list, it will not be automatically mocked by the module loader.
This is useful for some commonly used 'utility' modules that are almost always used as implementation details almost all the time (like underscore/lo-dash, etc). It's generally a best practice to keep this list as small as possible and always use explicit jest.mock()/jest.dontMock() calls in individual tests. Explicit per-test setup is far easier for other readers of the test to reason about the environment the test will run in.
It is possible to override this setting in individual tests by explicitly calling jest.mock() at the top of the test file.
(https://facebook.github.io/jest/docs/api.html#config-unmockedmodulepathpatterns-array-string)
and from the issue itself:
unmockedModulePathPatterns are used internally by Jest to create a RegExp against which all required modules will be tested. As such, you need to provide a valid regex pattern. For example, this worked nicely for me :
> unmockedModulePathPatterns: [
> "node_modules\\" + path.sep + "react",
> "node_modules\\" + path.sep + "reflux",
> "node_modules\\" + path.sep + "react-router"
> ],
答案 2 :(得分:3)
<rootDir>
应替换为实际路径。看起来您没有要从哪个子目录开始,而在某些情况下,您可能只想在src/
路径中运行测试,因此您的package.json看起来更像是这样:
{
...
"jest": {
"rootDir": "src",
"scriptPreprocessor": "../jest/preprocessor.js" // Note: relative to src
}
...
}