typescript - 如何使用 TypeScript、Jest 和 Enzyme 在 React 中测试按钮点击

标签 typescript react-native jestjs react-navigation enzyme

我正在使用 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 源代码中看到该行为 herehere .

因此 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/

相关文章:

c# - "VsTsc"任务无法用其输入 > 参数初始化

reactjs - 使用React Component的代理时查找失败

reactjs - 为什么我的 api 模拟会返回 404 错误?

typescript - 如何使用严格类型的有效负载发出事件? | Vue 3 Composition API + TypeScript

node.js - 错误 TS1259 : Module '"./node_modules/@types/express/index "' can only be default-imported using the ' esModuleInterop' 标志

javascript - 运行 ngFor 时组件内的类函数给出错误(不是函数)

javascript - react-sound-强制React组件更新并定位?

javascript - 如何在不手动一一添加的情况下为组件中的每个元素绑定(bind)相同的事件?

react-native - Textinput 最小长度 React native

typescript - 如何使用 Jest 模拟模拟模块的方法?