如何使用@testing-library/reat-native 测试react-native 中的TextInput?

Iro*_*aad 5 javascript reactjs react-native react-testing-library

我试图通过在输入字符串后检查其值来测试 TextInput,但它不起作用。任何帮助,将不胜感激。

这是代码:

import React from 'react'
import { TextInput } from 'react-native'
import { fireEvent, render } from "@testing-library/react-native"

test('<TextInput/>, () => {
  const { getByTestId } = render( <TextInput testID="input" /> );
  const input = getByTestId("input");
  fireEvent.changeText(input, "123");
  expect(input.value).toBe("123");
})
Run Code Online (Sandbox Code Playgroud)

测试失败并显示以下消息:

Expected: "123"
Received: undefined
Run Code Online (Sandbox Code Playgroud)

Die*_*ura 17

我认为你的例子不起作用,因为你没有控制输入。尝试添加一个value和 一个onChangeText函数。就像是:

function Example() {
  const [value, setValue] = useState('')
  return <TextInput value={value} onChangeText={setValue} testID="input" />
}

test('Should apply the value when changing text', () => {
  const { getByTestId } = render(<Exampler />);
  const input = getByTestId('input');
  fireEvent.changeText(input, '123');
  expect(input.props.value).toBe('123');
});
Run Code Online (Sandbox Code Playgroud)

另外,您需要检查input.props.value而不是input.value 希望它有帮助。


Emm*_*rai -1

我将提出一些建议来帮助您找到解决方案,

  • 你确定TextInput有一个名为 的道具吗testID?您随后使用getByTestId,这需要data-testid元素上的值。所以请先确认这一点。
  • 您可以尝试以其他方式查找该元素。可能使用getByPlaceholderText或类似。

一旦你可以正确地获取元素,并且在之后fireEvent,值肯定应该被更新,并且断言将会成功。