使用TypeScript,Jest和Enzyme在React中进行单元测试:无法调用可能是“未定义”的对象

J. *_*ers 5 unit-testing typescript jestjs react-native enzyme

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

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

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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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);
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

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

Cannot invoke an object which is possibly 'undefined'.
Run Code Online (Sandbox Code Playgroud)

我怎样才能解决这个问题?

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

if (typeof wrapper.find(Button).prop("onPress") !== undefined) {
  wrapper.find(Button).prop("onPress")({} as any);
}
Run Code Online (Sandbox Code Playgroud)

但这也不起作用。

Bri*_*ams 9

您可以像这样使用非空断言运算符

wrapper.find(Button).prop("onPress")!({} as any);
Run Code Online (Sandbox Code Playgroud)

...或者将处理程序分配给一个变量并在像这样的守卫后面调用它:

const handler = wrapper.find(Button).prop("onPress");
if (handler) {
  handler({} as any);
}
Run Code Online (Sandbox Code Playgroud)

  • 我只是更仔细地看了一下测试。试图强制组件以通常不会的方式重新渲染,因此对 `handlePress` 的监视是一个 *XY 问题*。由于`handlePress` 只是一个不需要测试的内部实现细节,间谍应该在作为道具传递的`navigation.navigate` 上。 (2认同)