我目前正在为使用react-test-renderer
实现的组件编写测试,遇到的一个问题是尝试测试在我的Animated.ScrollView
上滚动时调用的回调函数。 / p>
这是我目前使用通用命名的简洁版本:
组件
export class MyComponent extends React.Component<MyComponentProps, MyComponentState> {
public componentWillMount() {
this.index = 0;
this.routeSelectionAnimation = new Animated.Value(0);
}
public componentDidMount() {
this.routeSelectionAnimation.addListener(({ value }) => {
// some work is done before the following line
// the function I want to test is being called
this.props.onIndexUpdate(index);
});
}
public render() {
const scrollAnimation = Animated.event(
[{
nativeEvent: {
contentOffset: {
x: this.routeSelectionAnimation,
},
},
},
],
{ useNativeDriver: true },
);
// * more processing *
return (
<Animated.ScrollView
horizontal={true}
scrollEventThrottle={1}
showsHorizontalScrollIndicator={false}
snapToInterval={...}
pagingEnabled={true}
onScroll={scrollAnimation} // what matters is this
style={styles.scrollView}
>
{other components}
</Animated.ScrollView>
);
}
这在设备上正常工作,当ScrollView滚动时,调用了道具onIndexUpdate(int)
传递的函数。
我想测试这种行为,但是我似乎无法模拟ScrollView上的滚动。我正在考虑做类似的事情:
const props = {
onIndexUpdate: jest.fn(),
};
const getTestInstance = () => {
return TestRenderer.create(
<MyComponent onIndexUpdate={props.onIndexUpdate} />
).root;
};
describe("Animated.ScrollView", () => {
it("calls function", () => {
const instance = getTestInstance();
const scrollView = instance.findByType(Animated.ScrollView);
scrollView.instance.scrollToEnd({animated: false});
expect(props.onIndexUpdate).toHaveBeenCalledTimes(3);
});
});
但是它不起作用。结果是TypeError: scrollView.instance.scrollToEnd is not a function
清楚地表明我在看这个错误...
我非常感谢您提供有关如何解决此问题或以更正确的方式进行测试的信息。
答案 0 :(得分:0)
您错过了打印声明,这就是为什么它不起作用的原因。您应该输入:
print scrollView.instance.scrollToEnd({animated: false});