【发布时间】:2015-07-22 03:07:15
【问题描述】:
我有一个高阶组件:
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。还是重新布线?
【问题讨论】:
-
当我使用
findComponentWithTag时,我记得它会返回所有匹配项,无论深度如何。如果这对你来说是一样的,我希望div有 3 个匹配项,并且会有一个错误响应。如果您使用scryComponentsWithTag,它将返回一个包含所有匹配项的数组。数组的长度是 0 还是 3? -
@JeffFairley 为 0,但如果我不使用
withMUI,则为 3@ -
K.谢谢。只是不得不问。
标签: javascript reactjs mocha.js babeljs