我最近开始使用 React 开发组件,现在事情开始看起来不错,我想使用 Mocha 和 Enzyme 来测试它们。
这是我的提议/问题/要求回答:
我有一个 Fieldset 组件,其中包含一个“标题”道具和我使用 {this.props.children) 传递的其他组件(几个字段组件),如下所示:
零件:
export default class Fieldset extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<fieldset>
<p>{this.props.title || ""}</p>
{this.props.children}
</fieldset>
);
}
}
利用:
<Fieldset title="Log In">
<Field
label={<Label text="username" />}
input={
<TextInput
fieldName="username"
type="text"
placeholder="Enter your username"
state={this.props.state}
handleChange={this.props.handleInputChange}
/>
}
/>
<Field
label={<Label text="password" />}
input={
<TextInput
fieldName="password"
type="password"
placeholder="Enter your password"
state={this.props.state}
handleChange={this.props.handleInputChange}
/>
}
/>
测试:
我已经做了一些测试,例如
describe('<Fieldset />', () => {
let wrapper;
beforeEach(() => {
wrapper = mount(
<Fieldset
title="My title"
/>
)
});
it('should have a title variable in the props', () => {
expect(wrapper.props().title).to.equal('My title');
});
问题:
1) 将组件用作其他组件的道具,如 "input={ [TextInput title="blabla"] } 是一种好习惯吗?
2) 如何在我的 Test 中测试 {this.props.children} 的行为?
a:我是否应该使用类似的东西而不用担心节点太多,除非确保它等于我的节点变量的内容?
const node = <div>Hi</div>
beforeEach(() => {
wrapper = mount(
<Fieldset
title="My title"
{node}
/>
)
});
b:我是否应该使用模拟道具等导入其他组件(在本例中为 Field 组件)(就像真正使用带有子组件的组件)并使用它来测试 Fieldset 组件?出于此 Fieldset 测试的目的,我不会脱离上下文吗?
<Fieldset title="Log In">
<Field
label={<Label text="my label" />}
input={
<TextInput
fieldName="username"
type="text"
* etc etc *
/>
/>
</Fieldset>
感谢您帮助我找出测试组件的最佳方法。