我指的是这个github项目,我试图编写一个KeyPad.js组件的简单测试。
我已经看到了这方面的问题,建议的解决方案之一是将主题作为组件的支柱。这个溶液不适用于酶。
在我的例子中,问题在于子组件通过ThemeProvider接收主题,并且为了能够使测试工作正常进行,我需要向所有组件添加主题支持。
示例:
const tree = renderer.create(
<KeyPad
theme={theme}
cancel={()=> true}
confirm={()=> true}
validation={()=> true}
keyValid={()=>true} />
).toJSON();
expect(tree).toMatchSnapshot();键盘的渲染方法会像这样变化,到处都是主题道具
render() {
let { displayRule, validation, label, confirm, cancel, theme, keyValid, dateFormat } = this.props
return (
<Container theme={theme}>
<Content theme={theme}>
<Header theme={theme}>
<CancelButton theme={theme} onClick={cancel}>
<MdCancel />
</CancelButton>
<Label>{label}</Label>
<ConfirmButton theme={theme} onClick={() => confirm(this.state.input)} disabled={!validation(this.state.input)}>
<MdCheck />
</ConfirmButton>
</Header>
<Display
theme={theme}
value={this.state.input}
displayRule={displayRule}
dateFormat={dateFormat}
cancel={this.cancelLastInsert} />
<Keys>
{[7, 8, 9, 4, 5, 6, 1, 2, 3, '-', 0, '.'].map( key => (
<Button
theme={theme}
key={`button-${key}`}
theme={theme}
click={(key) => this.handleClick(key) }
value={key}
disabled={!keyValid(this.state.input, key, dateFormat)} />
))}
</Keys>
</Content>
</Container>
)
}我不喜欢这个解决方案。有人能帮我吗?
谢谢
发布于 2017-12-05 22:38:09
我只需对回调的props参数进行重构,并为theme添加一个默认值。这样,您可以从theme访问的任何支柱都不会随Cannot read property ... of undefined一起抛出并返回undefined。它会搞乱你的风格,但我认为你在单元测试中对此并不太在意。
...
color: ${({ theme = {} }) => theme.background};
...发布于 2017-11-29 14:21:36
据我所知,这是完全合理的。库中的每个组件都有一个主题支柱,因此您可以这样设置它。
幸运的是,它不使用上下文,否则您将离家更远。为什么不使用上下文:https://reactjs.org/docs/context.html
如果你不用道具做这件事,你最终会把组件耦合到另一个外部库。Redux或mobx商店。这意味着它不再是一个真正的组件。
尽管看起来糟透了。如果您真的想要制作一个单独的组件,这是一种方法。
https://stackoverflow.com/questions/47401401
复制相似问题