我正在使用 TypeScript 构建一个 React Native 应用程序。我正在使用 Jest 和 Enzyme 进行组件测试。我也在使用 React 导航
在我的最后一个问题中 https://stackoverflow.com/questions/52692824/how-to-test-a-button-click-in-react-with-typescript-jest-and-enzyme Brian https://stackoverflow.com/users/10149510/brian-lives-outdoors向我解释了如何正确测试按钮的按下情况。我的问题是按钮onPress
prop 可能是未定义的。让我向您展示代码:
export class HomeScreen extends Component<Props, object> {
// ... navigationOptions and stuff
handlePress = () => {
this.props.navigation.navigate("QuestionsScreen");
};
render() {
return (
<View style={styles.container}>
<Button
raised={true}
title={strings.painButtonTitle}
buttonStyle={styles.painButton}
titleStyle={styles.title}
onPress={this.handlePress}
/>
</View>
);
}
}
这是我为测试与按钮的交互而编写的测试:
describe("interaction", () => {
const props = createTestProps({});
const wrapper = shallow<HomeScreen>(<HomeScreen {...props} />);
describe("clicking the Pain Button", () => {
it("should navigate to the 'QuestionsScreen'", () => {
wrapper.instance().handlePress = jest.fn();
wrapper.find(Button).prop("onPress")({} as any);
expect(wrapper.instance().handlePress).toHaveBeenCalledTimes(1);
});
});
});
问题在于我的测试无法运行,因为 linter 说onPress
可能是未定义的:
Cannot invoke an object which is possibly 'undefined'.
我怎样才能解决这个问题?
我尝试将代码包装在 if 语句中,如下所示:
if (typeof wrapper.find(Button).prop("onPress") !== undefined) {
wrapper.find(Button).prop("onPress")({} as any);
}
但这也行不通。