React TestUtils doesn't work with decorators or how to simulate higher order functions using rewire
I have a higher order component:
import React from 'react';
function withMUI(ComposedComponent) {
return class withMUI {
render() {
return <ComposedComponent {...this.props}/>;
}
};
}
and component:
@withMUI
class PlayerProfile extends React.Component {
render() {
const { name, avatar } = this.props;
return (
<div className="player-profile">
<div className='profile-name'>{name}</div>
<div>
<Avatar src={avatar}/>
</div>
</div>
);
}
}
and a (passing) test using React.findDOMNode
describe('PlayerProfile', () => {
// profile is type of `withMUI`
let profile = TestUtils.renderIntoDocument(<OkeyPlayerProfile/>);
it('should work', () => {
let elem = React.findDOMNode(profile);
// logs successfully
console.log(elem.querySelectorAll('.player-profile'));
});
// ...
});
and another (failed) test using TestUtils
:
// ...
it('should also work', () => {
let elem = TestUtils.findComponentWithTag(profile, 'div');
// throws can't find a match
console.log(elem);
});
If I remove the @withMUI decorator it works as expected. So why is the decorator effect TestUtils.findComponentWithTag
and how can I make this work?
How can I fake a function withMUI
? using babel-plugin-rewire . or rewrite?
source to share
You can use the 'babel-plugin-remove-decorators' plugin
First install the plugin, then create a file with the following content, let's call it "babelTestingHook.js"
require('babel/register')({
'stage': 2,
'optional': [
'es7.classProperties',
'es7.decorators',
// or Whatever configs you have
.....
],
'plugins': ['babel-plugin-remove-decorators:before']
});
and running your tests as shown below will ignore decorators and you should be able to test components normally
mocha ./tests/**/*.spec.js --require ./babelTestingHook.js --recursive
source to share