【问题标题】:how to mock autofocus prop of a child textInput in ReactNative如何在 React Native 中模拟子 textInput 的自动对焦道具
【发布时间】:2019-08-24 20:24:39
【问题描述】:

大家好, 我刚刚开始使用 react native 和测试。我有一个登录组件,它有 2 个文本输入,其中一个是自动对焦的。当我尝试运行我的测试时,它抱怨使用 findNodeHandle 的组件。

我尝试在谷歌上寻找类似问题的答案,但没有找到对我有用的东西,所以我想我在这里试试运气。

这是我的组件的渲染方法。

render() {
    return (
      <View style={styles.login}>
        <TextInput autoFocus={this.props.focus || true} onChange={uname => this.setState({ username: uname})} placeholder={'Username'} style={styles.input}/>
        <TextInput 
        onChange = {
          pwd => this.setState({
            password: pwd
          })
        }
        placeholder = {
          'Password'
        }
        style = {
          [styles.input,
          styles.password]
        }

        secureTextEntry = {true}
        />
      </View>
    )
  }

这是我正在尝试执行的测试

it('render a log in form', () => {
    expect(renderer.create(
        <Login focus={false}/>
    )).toMatchSnapshot();
});

当我运行测试时,这是我收到的输出:

通过测试/App-test.js

● 测试完成后无法登录。您是否忘记在测试中等待异步内容?

尝试记录“不支持在测试渲染器环境中调用 .focus()。相反,使用不依赖本机环境的替换来模拟使用 findNodeHandle 的组件。”。

在 BufferedConsole.warn (node_modules/@jest/console/build/BufferedConsole.js:224:10)

在 Component.focus (node_modules/react-native/jest/MockNativeMethods.js:11:13)

通过测试/Login.test.js

测试套件:2 个通过,共 2 个

测试:2 次通过,共 2 次​​p>

快照:1 个通过,共 1 个

时间:4.233s

运行所有测试套件。

● 测试完成后无法登录。您是否忘记在测试中等待异步内容?

尝试记录“不支持在测试渲染器环境中调用 .focus()。相反,使用不依赖本机环境的替换来模拟使用 findNodeHandle 的组件。”。

在 BufferedConsole.warn (node_modules/@jest/console/build/BufferedConsole.js:224:10)

在 Component.focus (node_modules/react-native/jest/MockNativeMethods.js:11:13)

在 6.16 秒内完成。

我希望有人能告诉我是什么导致了这个问题,以及如何在这种情况和未来的类似情况下防止它。 感谢大家花时间回答我的问题。

【问题讨论】:

    标签: react-native mocking jestjs


    【解决方案1】:

    将此代码添加到您的导入中(导入中的任何位置)

    import { findNodeHandle } from 'react-native';
    import TextInputState from 'react-native/lib/TextInputState';
    export function focusTextInput(node) {
      try {
        TextInputState.focusTextInput(findNodeHandle(node));
      } catch(e) {
        console.log("Couldn't focus text input: ", e.message)
      }
    };
    

    将以下行添加到您的构造函数

    this.focusNextField = this.focusNextField.bind(this);
    this.inputs = {};
    Add the following function to your class
    
    focusNextField(id) {
      this.inputs[id].focus();
    }
    

    编辑您的 TextInput 如下:

    <TextInput
      onSubmitEditing={() => {this.focusNextField('two');}}
      ref={ input => {this.inputs['one'] = input;}}
    />
    <TextInput
      onSubmitEditing={() => {this.focusNextField('three');}}
      ref={ input => {this.inputs['two'] = input;}}
    />
    

    参考这篇文章:ReactNative TextInput Focus

    【讨论】:

    • 这回答了一个不同于我的问题。我希望在测试中运行自动对焦而不显示任何错误,否则该组件实际上可以在模拟器中运行
    猜你喜欢
    • 2017-07-11
    • 2017-08-07
    • 1970-01-01
    • 1970-01-01
    • 2020-09-05
    • 2016-03-09
    • 1970-01-01
    • 1970-01-01
    • 2022-07-06
    相关资源
    最近更新 更多