所以,我已经使用了emotion-js一段时间了,我喜欢它!但我真的很讨厌e2e测试。所有选择器看起来都是这样的:div > div > div > p,因为emotion注入的类名是随机生成的字符串。因此,我想将data-属性与DisplayName注入到每个元素中,以便能够以更干净的方式测试它们:[data-test-id*="DateButton"]或类似的东西。所以我写了一个简单的包装:https://gist.github.com/sergeyvlakh/3072a4e2e27456bda853a1e1a213a568
我就是这样用的:
import Injector from './injector';
export default props =>
(
<Injector>
<MyReactTree />
</Injector>
)这里的问题是我不是“动态”注入数据属性。我想像使用HoC一样使用recompose:export default Injector(App)
或者即使使用动态道具名,比如:export default Injector('data-test-id')(App)。在这种情况下,But...children for Injector将是未定义的,因此我不知道如何处理:)
更新:多亏了remix23我这样做了:https://gist.github.com/sergeyvlakh/f99310cdef018c06451333a36e764372
但是,我强烈建议使用他的代码。
发布于 2019-03-19 09:29:00
您可以使用React.cloneElement(element, newPropsToMerge, newChildren)将道具注入任何React元素。
您可以通过访问每个元素、子元素等等,递归地跟踪幼童。
也许成本更高,但更直截了当,这也是可行的:
function Injector(Target) {
class InjectedTarget extends Component {
render() {
const { chilren, ...rest } = this.props;
return (
<Target
data-test-id={Target.DisplayName}
{...rest}
>
{React.Children.map(children, (child) => {
const isComponent =
child &&
child.type &&
typeof child.type !== 'string' &&
Object.prototype.isPrototypeOf.apply(
React.Component.prototype,
[child.type.prototype]
);
if (!isComponent) {
return child;
}
return React.createElement(Injector(child.type), { ...child.props, 'data-test-id': Target.DisplayName });
})}
</Target>
);
}
}
return InjectedTarget;
}我认为这将是非常完美的性能方面的,但这是为了测试对吗?
https://stackoverflow.com/questions/55237050
复制相似问题