使用TypeScript,Jest和Enzyme在React中进行单元测试:无法调用可能是“未定义"的对象 [英] Unit testing in React with TypeScript, Jest and Enzyme: Cannot invoke an object which is possibly 'undefined'

查看:2122
本文介绍了使用TypeScript,Jest和Enzyme在React中进行单元测试:无法调用可能是“未定义"的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用TypeScript构建一个React Native应用程序.我正在使用Jest和Enzyme进行组件测试.我也在使用React Navigation

I'm building a React Native app with TypeScript. I'm doing my component tests using Jest and Enzyme. I'm also using React Navigation

在我的最后一篇中问题 Brian 向我解释了如何正确测试按钮的按下状态.我的问题是按钮onPress属性可能未定义.让我向您展示代码:

In my last question Brian explained to me how to correctly test the press of a button. My problem is that the buttons onPress prop may be undefined. Let me show you the code:

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>
    );
  }
}

这是我编写的用于测试与按钮的交互的测试:

And here is the test I write for testing the interaction with the button:

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);
    });
  });
});

问题出在这里,我的测试无法运行,因为短绒棉布说onPress可能未定义:

The problem is here that my test won't run, because the linter says that onPress may be undefined:

Cannot invoke an object which is possibly 'undefined'.

我该如何解决?

我尝试将代码包装在如下if语句中:

I tried wrapping my code in an if statement like this:

if (typeof wrapper.find(Button).prop("onPress") !== undefined) {
  wrapper.find(Button).prop("onPress")({} as any);
}

但这也不起作用.

推荐答案

您可以使用

You can either use the non-null assertion operator like this:

wrapper.find(Button).prop("onPress")!({} as any);

...或将处理程序分配给一个变量,然后像这样在警卫后面调用它:

...or assign the handler to a variable and call it behind a guard like this:

const handler = wrapper.find(Button).prop("onPress");
if (handler) {
  handler({} as any);
}

这篇关于使用TypeScript,Jest和Enzyme在React中进行单元测试:无法调用可能是“未定义"的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆