Reactjs React Native-如何在测试中指定状态?
我目前正在开发一个React本地组件,该组件使用本地状态来控制某些UI元素,即,只有当状态中的某些值设置为Reactjs React Native-如何在测试中指定状态?,reactjs,react-native,testing,Reactjs,React Native,Testing,我目前正在开发一个React本地组件,该组件使用本地状态来控制某些UI元素,即,只有当状态中的某些值设置为true时,才会呈现某些元素。这些值根据零部件内的单击而变化 在使用react的TestRenderer进行测试时,有没有一种方法可以指定初始状态?如果没有,我怎么能去测试这个呢?我希望能够呈现特定状态的组件,并对其进行测试。非常感谢任何有帮助的意见 如有必要,我可以提供更多细节 提前谢谢 编辑:添加说明我的代码的示例。这不是我的组件代码,但它说明了它的行为: interface IMyCo
true
时,才会呈现某些元素。这些值根据零部件内的单击而变化
在使用react的TestRenderer
进行测试时,有没有一种方法可以指定初始状态?如果没有,我怎么能去测试这个呢?我希望能够呈现特定状态的组件,并对其进行测试。非常感谢任何有帮助的意见
如有必要,我可以提供更多细节
提前谢谢
编辑:添加说明我的代码的示例。这不是我的组件代码,但它说明了它的行为:
interface IMyComponentProps {
...
}
interface IMyComponentState {
showForm: boolean;
}
export class MyComponent extends React.Component<IMyComponentProps, IMyComponentState> {
constructor(props: any) {
super(props);
// showForm is initially false
this.state = {
showForm: false,
};
}
public render() {
// if showForm is true then render my form component
if (this.state.showForm) {
return <FormComponent />;
} else {
// otherwise render button that changes the state to showForm: true
// and causes a re-render
return <Button onClick={this.buttonClickFn} />;
}
}
private buttonClickFn = () => this.setState({...this.state, showForm: true});
}
接口IMyComponentProps{
...
}
接口IMY组件状态{
显示形式:布尔型;
}
导出类MyComponent扩展了React.Component{
构造器(道具:任何){
超级(道具);
//showForm最初是错误的
此.state={
展示形式:假,
};
}
公共渲染(){
//如果showForm为true,则呈现我的表单组件
if(this.state.showForm){
返回;
}否则{
//否则,将状态更改为showForm:true的渲染按钮
//并导致重新渲染
返回;
}
}
私有按钮CLICKFN=()=>this.setState({…this.state,showForm:true});
}
可以直接为测试目的设置状态:
componentInstance.state.showForm = true;
componentInstance.forceUpdate();
你能添加组件代码吗?@gran33我添加了一些示例组件代码来说明我的意思。如果你需要更多的细节,请询问。那太好了,正是我所需要的+1.