javascript - Jest 配置

标签 javascript react-native jestjs

我正在将 Jest 测试框架添加到我的 React Native 项目中。我收到以下错误:

Failed to get mock metadata: /Users/me/Documents/Development/project/node_modules/global/window.js

我的测试文件如下所示:

import 'react-native'
import React from 'react'
import { MyComponent } from '../components/MyComponent'

import renderer from 'react-test-renderer'

it('renders correctly', () => {
  const tree = renderer.create(<MyComponent />).toJSON()
  expect(tree).toMatchSnapshot()
})

还有我的 package.json 中的 Jest 配置:

"jest": {
    "preset": "jest-react-native",
    "testPathIgnorePatterns": ["/node_modules/", "/example/", "/lib/"],
    "testRegex": "(/tests/.*|\\.(test|spec))\\.(js|jsx)$",
    "automock": "true",
    "unmockedModulePathPatterns": [ "lodash" ],
    "transformIgnorePatterns": [
      "node_modules/(?!@exponent/ex-navigation",
      ")"
    ]
  }

我查看了http://facebook.github.io/jest/docs/manual-mocks.html#content按照错误提示的建议。

最佳答案

我认为 package.json 中的 jest 配置有问题。

这是一个示例 Jest 配置片段:

"jest": {
    "preset": "react-native",
    "cacheDirectory": "./cache",
    "coveragePathIgnorePatterns": [
      "./app/utils/vendor"
    ],
    "coverageThreshold": {
      "global": {
        "statements": 80
      }
    },
    "transformIgnorePatterns": [
      "/node_modules/(?!react-native|react-clone-referenced-element|react-navigation)"
    ]
  }

预设:预设是模仿 React Native 应用程序环境的节点环境。由于它不加载任何 DOM 或浏览器 API,因此大大缩短了 Jest 的启动时间。

cacheDirectory:它可以帮助您大大提高测试速度。它通过创建已编译模块的缓存来实现这一点,这样下次运行测试时就不必编译node_modules。

coveragePathIgnorePatterns:定义覆盖率报告要跳过的文件。

coverageThreshold:定义所有测试通过的阈值限制。如果覆盖范围小于定义的限制,测试将失败。这帮助我们在任何时间点都保持良好的覆盖范围。

transformIgnorePatterns:我们在这里传递所有需要转译的 NPM 模块。这些模块基本上都是 ES6/7 模块。

PS:我写了一篇关于如何为react-native项目设置jest的博客。这是网址:http://rahulgaba.com/react-native/2017/05/19/Jest-test-suite-with-superpowers.html

关于javascript - Jest 配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40873125/

相关文章:

javascript - .defaultProps 是否适用于无状态 React 组件?

php - 服务器 header 、引荐来源网址等

ios - 我应该将 App.xcarchive、DistributionSummary.plist、ExportOptions.plist、Packaging.log 提交到公共(public)存储库吗?

php - JQuery中发现PHP返回AJAX错误

javascript - 在 props 赋值中使用扩展运算符时 React Native 接收错误 : "In this environment the target of assign must be an object

react-native - 我可以在平面列表中使用 ItemSeparatorComponent 中的组件吗?

unit-testing - 当模块未模拟时,如何在 Jest 中模拟导入的命名函数

mocking - 使用 axios 拦截器模拟 axios

javascript - Slick 的轮播图片之间的空间

javascript - 双击两个 INS 标签中的单词 JavaScript window.getSelection