【问题标题】:HOC which passes all props通过所有道具的HOC
【发布时间】:2020-02-21 13:32:55
【问题描述】:

我正在考虑编写一些 React 的 util(可能是 HOC),它允许我测试这种代码:

    const wrapper = enzyme
      .mount(
        withTestTheme(
          <JsonInput
            onChange={onChange}
            onValueChange={mockOnValueChange}
            value={exampleJsonStringValidated}
          />),
      );

withTestTheme 是一个提供主题属性的包装器,但它在测试期间让我出现问题,因为它会导致访问我想要测试的根组件时出现问题。对一些有用的工具有什么想法可以更容易地测试上面的代码吗?

withTestTheme 下方提供主题 - 明暗:

export const withTestTheme = (Component: React.ReactChild) => (
  <ThemeProvider theme={TestTheme}>
  {Component}
</ThemeProvider>
);

【问题讨论】:

  • 你能告诉我 withTestTheme 是做什么的吗?图书馆或定制?如果它是自定义的,请分享代码。
  • “它会导致访问我要测试的根组件出现问题” - 你在这里是什么意思?它会阻止您访问.find(YourComponentConstructor)吗?还是您的意思是访问wrapper.instance()wrapper.setState()(无论如何最好避免)?
  • 当然,我解释一下。我的问题是 console.log(wrapper.find(JsonInput)) 是空的,因为 withTestTheme 是一个包装器。我想检查以下测试:expect(wrapper.find(JsonInput).hasClass(':valid')).toEqual(true);并且由于 withTestTheme 我不能因为包装器只能访问根。我想以某种方式使 JsonInput 成为包装器的根,同时使用 withTestTheme 功能。

标签: reactjs testing jestjs enzyme higher-order-components


【解决方案1】:

解决我的问题的代码:

export const withTestThemeWrapper = (props: { children: React.ReactElement }) => (
  <ThemeProvider theme={TestTheme}>
    {props.children}
  </ThemeProvider>
);

【讨论】:

    猜你喜欢
    • 2019-03-07
    • 1970-01-01
    • 2018-07-23
    • 2020-03-10
    • 2021-04-01
    • 1970-01-01
    • 2021-04-12
    • 1970-01-01
    • 2020-01-17
    相关资源
    最近更新 更多