I'm using Jest to test my React components. I have the react-html-attrs plugin enabled allowing me to use class
instead of className
. This is configured through Webpack's module loaders property with:
{
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'
],
}
}
I'm wanting to use Enzyme to test the rendered outcome of my components in order to assert whether these class
attributes are correctly provided, but I'm getting the following error:
console.error node_modules\fbjs\lib\warning.js:36
Warning: Unknown DOM property class.
Did you mean className?
in h1
in Heading
This is my test script:
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);
});
The Heading component itself is this:
return (
<h1 class="heading">
{icon ? <i class={"fa " + icon}></i> : ""} {text}
</h1>
)
...and the output (seen through a react-test-renderer Snapshot) is:
<h1
class="heading">
<i
class="fa fa-question" />
This is a test
</h1>
How can I get Enzyme to recognise that class
is valid with react-html-attrs enabled?
Update
When logging render
.html()
I can see that Enzyme has ignored the class
attributes completely:
console.info src\js\components__tests__\Heading.js:40
<h1><i></i> This is a test</h1>
Update 2
Here is my Jest config within package.json:
"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/"
]
}
Since Jest doesn't use the webpack config, you need to add your babel configuration to a source that it will read. The .babelrc file is a good place for this because webpack will also look there for configuration of the
babel-loader
.So, adding this to your .bablerc should help:
Then, you can clean up your webpack config as well: