【发布时间】:2018-10-08 10:14:03
【问题描述】:
我正在使用 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",可以吗?
我怎样才能让这个测试通过?
【问题讨论】:
标签: typescript react-native jestjs react-navigation enzyme