我怎样才能让 Enzyme 识别 react-html-attrs 插件?

How can I get Enzyme to recognise the react-html-attrs plugin?

我正在使用 Jest 来测试我的 React 组件。我启用了 react-html-attrs 插件,允许我使用 class 而不是 className。这是通过 Webpack 的模块加载器 属性 配置的:

{
  test: /\.js$/,
  exclude: /node_modeules|bower_components/,
  loader: 'babel-loader',
  query: {
    presets: ['react', 'es2015', 'stage-0'],
    plugins: [
      'react-html-attrs',
      'transform-decorators-legacy',
      'transform-class-properties',
      'babel-polyfill'
    ],
  }
}

我想使用 Enzyme 来测试我的组件的呈现结果,以便断言是否正确提供了这些 class 属性,但我收到以下错误:

console.error node_modules\fbjs\lib\warning.js:36
 Warning: Unknown DOM property class.
  Did you mean className?

   in h1
   in Heading

这是我的测试脚本:

it('loads the correct icon', () => {
  const render = shallow(
    <Heading icon="fa-question" text="This is a test" />
  );

  const el = render.find('i');

  expect(el.hasClass('fa-question')).toBe(true);
});

标题组件本身是这样的:

return (
  <h1 class="heading">
    {icon ? <i class={"fa " + icon}></i> : ""} {text}
  </h1>
)

...输出(通过 react-test-renderer 快照看到)是:

<h1
  class="heading">
  <i
    class="fa fa-question" />

  This is a test
</h1>

如何让 Enzyme 识别 class 在启用 react-html-attrs 的情况下有效?


更新

在记录 render.html() 时,我可以看到 Enzyme 完全忽略了 class 属性:

console.info src\js\components__tests__\Heading.js:40
 <h1><i></i> This is a test</h1>

更新 2

这是我在 package.json:

中的 Jest 配置
"jest": {
  "modulePaths": [
    "./src/js"
  ],
  "moduleFileExtensions": [
    "js"
  ],
  "moduleDirectories": [
    "node_modules",
    "bower_components",
    "shared"
  ],
  "moduleNameMapper": {
    "\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
    "\.(css|less)$": "<rootDir>/__mocks__/styleMock.js"
  },
  "unmockedModulePathPatterns": [
    "node_modules/react/",
    "node_modules/enzyme/"
  ]
}

由于 Jest 不使用 webpack 配置,您需要将 babel 配置添加到它将读取的源中。 .babelrc 文件是一个很好的地方,因为 webpack 也会在那里寻找 babel-loader.

的配置

因此,将此添加到您的 .bablerc 应该会有所帮助:

{
    "presets": [
        "es2015",
        "react",
        "stage-0"
    ],
    "plugins": [
        "react-html-attrs",
        "transform-decorators-legacy",
        "transform-class-properties",
        "babel-polyfill"
    ]
}

然后,您也可以清理您的 webpack 配置:

{
  test: /\.js$/,
  exclude: /node_modeules|bower_components/,
  loader: 'babel'
}