[英]React TestUtils doesn't work with decorators or how to mock higher order functions using rewire
我有一个更高阶的组件:
import React from 'react';
function withMUI(ComposedComponent) {
return class withMUI {
render() {
return <ComposedComponent {...this.props}/>;
}
};
}
和一个组件:
@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>
);
}
}
和使用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'));
});
// ...
});
和使用TestUtils
另一个(失败)测试:
// ...
it('should also work', () => {
let elem = TestUtils.findComponentWithTag(profile, 'div');
// throws can't find a match
console.log(elem);
});
如果我删除@withMUI装饰器,它按预期工作。 那么为什么装饰器会影响TestUtils.findComponentWithTag
,我该怎样才能使这个工作呢?
我如何模拟withMUI
函数? 使用babel-plugin-rewire 。 还是重新连线?
你可以使用'babel-plugin-remove-decorators'插件
首先安装插件,然后创建一个包含以下内容的文件,让我们称之为'babelTestingHook.js'
require('babel/register')({
'stage': 2,
'optional': [
'es7.classProperties',
'es7.decorators',
// or Whatever configs you have
.....
],
'plugins': ['babel-plugin-remove-decorators:before']
});
如下所示运行测试将忽略装饰器,您将能够正常测试组件
mocha ./tests/**/*.spec.js --require ./babelTestingHook.js --recursive
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.