我正在使用 TypeScript 构建一个 React Native 应用程序。我正在使用 Jest 和 Enzyme 进行组件测试。我也在使用 React Navigation
我正在努力编写用于单击我的按钮的单元测试。
这是组件的代码(只是渲染函数):
render() {
const { navigation } = this.props;
return (
<View style={styles.container}>
<Button
raised
title={strings.painButtonTitle}
buttonStyle={styles.painButton}
titleStyle={styles.title}
onPress={() => navigation.navigate("QuestionsScreen")}
/>
</View>
);
}
现在是单元测试。
describe("interaction", () => {
let wrapper: ShallowWrapper;
let props: Props;
beforeEach(() => {
props = createTestProps({});
wrapper = shallow(<HomeScreen {...props} />);
});
describe("clicking the Pain Button", () => {
it("should navigate to the 'QuestionsScreen'", () => {
wrapper.find("Button").simulate("click");
expect(props.navigation.navigate).toHaveBeenCalledTimes(1);
});
});
});
这会失败并声明 navigation.navigate
函数 - 使用 jest.fn() 模拟 - 从未被调用。
我假设它与为按钮提供错误功能有关。问题是,我不能不这样做,因为我需要使用参数 "QuestionsScreen"
进行调用。所以我不能做像 onPress={this.navigation.navigate)
这样的事情,然后奇迹般地调用 "QuestionsScreen"
,可以吗?
我怎样才能通过这个测试?
最佳答案
"Common Gotchas" section for simulate
说“即使名称暗示这模拟了一个实际事件,.simulate() 实际上会根据您给它的事件定位组件的 Prop 。例如,.simulate('click') 实际上会获得 onClick Prop 并调用它。”
可以在 Enzyme
源代码中看到该行为 here和 here .
因此 wrapper.find("Button").simulate("click");
行最终尝试调用 Button 的
不存在,所以它基本上什么都不做。onClick
Prop
This post来自 Airbnb 开发者的建议直接调用 props 并避免 simulate
。
这是一个修改后的测试,它直接调用 onPress
属性:
it("should navigate to the 'QuestionsScreen'", () => {
wrapper.find(Button).props().onPress({} as any);
expect(props.navigation.navigate).toHaveBeenCalledTimes(1); // SUCCESS
});
关于typescript - 如何使用 TypeScript、Jest 和 Enzyme 在 React 中测试按钮点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52692824/