我查看了许多有关测试库 fireEvent 问题的 StackOverflow 问题,在每种情况下,该帖子似乎都是通过修复 props 处理不当或类似问题而解决的。
但是,我似乎无法发现我的代码有任何问题,我想知道这是否可能是一个配置问题。我期望我的模拟函数已被调用,但是,它没有被调用,我不确定为什么。任何帮助将非常感激。我已在下面尽可能地将代码简化为示例案例。
Foo.js
import {TextInput} from "react-native";
const Foo = (props) => {
return <TextInput testID={"test"} onChange={() => props.onChange()} />
}
export default Foo;
Foo.test.js
import { render, screen, fireEvent } from '@testing-library/react-native';
import Foo from "./foo";
test('onChange works properly', () => {
const onChangeMock = jest.fn();
render(<Foo onChange={onChangeMock} />)
fireEvent.changeText(screen.getByTestId("test"), 'myTest');
expect(onChangeMock).toHaveBeenCalled();
})
运行此测试输出:
Error: expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls: 0
最佳答案
经过一些实验,我发现在 react native 应用程序中,更改 TextInput 组件会触发 OnChange 和 OnChangeText 事件。这意味着您可以将函数链接到 onChange 或 OnChangeText(尽管每个函数中包含的事件对象的结构不同。有关详细信息,请参阅此 SO answer)。
<TextInput testID={"test"} onChange={() => props.onChange()} />
对比
<TextInput testID={"test"} onChangeText={() => props.onChange()} />
但是,在 @testing-library/react-native 中使用 fireEvent 只会触发指定的事件,而不会触发姊妹事件。这意味着如果您正在监视组件中的 onChange 事件,则必须使用以下内容:
fireEvent(screen.getByTestId("test"), 'change', {target: {value: 'abc'}});
如果您正在监视 onChangeText 事件,则必须使用以下内容:
fireEvent.changeText(screen.getByTestId("test"), 'abc');
关于react-native - 为什么 @testing-library/react-native fireEvent 不调用我的 onChange 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73410630/