首页 > 解决方案 > 如何在 ReactNative 中模拟子 textInput 的自动对焦道具

问题描述

大家好,我刚刚开始使用 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 次

快照:通过 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-nativemockingjestjs

解决方案


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

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


推荐阅读