【问题标题】:React Native - How do I specify state in tests?React Native - 如何在测试中指定状态?
【发布时间】:2018-11-05 17:35:22
【问题描述】:

我目前正在开发一个使用本地状态来控制一些 UI 元素的 React Native 组件,即,只有当状态中的某些值设置为 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});
}

【问题讨论】:

  • 你能添加你的组件代码吗?
  • @gran33 我添加了一些示例组件代码来说明我的意思。如果您需要更多详细信息,请询问。

标签: reactjs react-native testing


【解决方案1】:

状态可以直接设置用于测试目的:

componentInstance.state.showForm = true;
componentInstance.forceUpdate();

【讨论】:

  • 太完美了,正是我需要的。 +1
猜你喜欢
  • 2018-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-24
  • 2016-08-08
  • 2021-06-03
  • 2023-04-11
  • 1970-01-01
相关资源
最近更新 更多