我指的是github project,我正在尝试编写一个简单的KeyPad.js组件测试 .
我已经看到在这个问题上打开了问题,一个建议的解决方案是将主题作为prop传递给组件 . 该解决方案不适用于酶 .
在我的情况下,问题是子组件通过ThemeProvider接收主题,并且能够进行测试工作,我需要向所有人添加主题道具 .
例:
const tree = renderer.create(
<KeyPad
theme={theme}
cancel={()=> true}
confirm={()=> true}
validation={()=> true}
keyValid={()=>true} />
).toJSON();
expect(tree).toMatchSnapshot();
KeyPad的渲染方法会像这样改变,主题道具无处不在
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>
)
}
我 don't 喜欢这个解决方案 . 有谁可以帮我这个?
谢谢
2 回答
就我所见,这是完全合理的 . 库中的每个组件都有一个主题道具,因此您可以像这样设置它 .
幸运的是它没有使用上下文,否则你会离家更远 . 为什么不使用上下文:https://reactjs.org/docs/context.html
如果你不使用道具,你将最终将组件耦合到另一个外部库 . 例如:Redux或mobx商店 . 这意味着它不再是真正的组件
尽管它看起来很糟糕 . 如果你真的想要制作一个单独的组件,那就是你要走的路 .
我只是解构回调的
props
参数并为theme
添加一个默认值 . 这样,您可以从theme
访问的任何道具都不会抛出Cannot read property ... of undefined
并返回undefined
. 它会弄乱你的风格,但我不认为你在单元测试中太在意它 .