为什么 ref.current.focus() 在通过 @testing-library/react-native 库运行测试时不起作用?



我正试图为我的react本机应用程序编写一些测试。我的应用程序中的一个组件在家长Pressable收到按压后聚焦TextInput。我正在使用一个ref来识别和聚焦TextInput元素。

当我通过expo运行我的应用程序时,我想要的功能运行得很好,但我的测试失败了,因为似乎没有调用onFocus事件。

通过@testing-library/react-native库运行测试时,为什么不调用ref.current.focus()

这是我的代码:

Foo.js

import {Pressable, TextInput} from "react-native";
import {useRef} from "react";
const Foo = (props) => {
const inputRef = useRef()
return (
<Pressable testID={"pressable"} onPress={() => inputRef.current.focus()}>
<TextInput ref={inputRef} testID={"input"} onFocus={props.onFocus} />
</Pressable>
)
}
export default Foo;

Foo.test.js

import { render, screen, fireEvent } from '@testing-library/react-native';
import Foo from "./foo";
test('onFocus is called after press', () => {
const mockFocus = jest.fn();
render(<Foo onFocus={mockFocus} />)
// fireEvent(screen.getByTestId("input"), 'focus');
fireEvent.press(screen.getByTestId("pressable"));
expect(mockFocus).toHaveBeenCalled()
});

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

Error: expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls:    0

我在RNTL GitHub页面上创建了一个问题,并收到了一个贡献者的响应。复制和粘贴在这里,方便任何可能偶然发现这个线程的人参考。

这应该是我们用于渲染的React测试渲染器不支持CCD_ 3。查看#106了解更多详细信息。

由于focus()触发onFocus事件的行为可能涉及到本机端(从JS端(的往返,那么实际上无法使用RNTL测试此类行为,因为我们不运行本机代码(请参阅此处查看详细信息(。

这给你留下了以下选择:

  1. 调用fireEvent.focus手动触发相关的onFocusTextInput。如果focus断言是在更大的考验中迈出一步
  2. 使用createNodeMockref创建函数传递给render方法,更多详细信息请点击此处。建议您只想断言按下按钮触发CCD_ 13

最新更新