我正在使用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来测试我的组件的渲染结果,以断言是否正确提供了这些类属性,但是我收到以下错误:
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 Snapshot看到)是:
<h1
class="heading">
<i
class="fa fa-question" />
This is a test
</h1>
我怎样才能让Enzyme认识到该类在启用react-html-attrs时有效?
更新
记录render.html()
时,我可以看到Enzyme完全忽略了类属性:
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'
}