我有一个使用onTouchStart和onTouchEnd的组件,我不知道如何测试它。
下面是代码的小吃,但是代码片段如下:
export default function TouchComponent({
children,
onStart = doNothing,
onEnd = doNothing
}: TouchComponentProps): React.ReactElement {
return (
<View
onTouchStart={(e) => onStart()}
onTouchEnd={(e) => onEnd()}
>{children}</View>
);
}
const doNothing = () => {};
interface TouchComponentProps {
children?: React.ReactNode;
onStart?: () => void;
onEnd?: () => void;
}查看文档,没有列出任何用于onTouchStart/onTouchEnd的方法,但是这种方法阵列似乎暗示它有其他可以调用的方法,但是它看起来在这里不起作用,因为fireEvent["onTouchStart"](myComponent);失败了,错误地说:TypeError: _reactNative.fireEvent.onTouchStart is not a function。
我已经搜索过了,但似乎找不到任何关于测试onTouchStart和onTouchEnd的文档或其他问题,那么如何激发这些事件呢?
发布于 2022-02-26 13:23:38
在问完这个问题后,我马上就想出了答案。在我的情况下,我可以这样引用它们:
import TouchComponent from "../TouchComponent ";
import { render, fireEvent } from "@testing-library/react-native";
it("Invokes onTouchStart and onTouchEnd", () => {
const { getByTestId } = render(
<TouchComponent
onStart={() => {
console.log("onTouchStart invoked");
}}
onEnd={() => {
console.log("onTouchEnd invoked");
}}
testID="my-component" />);
const myComponent = getByTestId("my-component");
// Passing empty {} data, but may need to supply for other use cases.
fireEvent(myComponent, "onTouchStart", {});
fireEvent(myComponent, "onTouchEnd", {};
});
// Console:
// console.log
// onTouchStart invoked
// console.log
// onTouchEnd invokedhttps://stackoverflow.com/questions/71276872
复制相似问题