【问题标题】:Is it possible to remove theme from React test renderer?是否可以从 React 测试渲染器中删除主题?
【发布时间】:2020-04-15 08:47:48
【问题描述】:

我正在使用推荐的 react-test-renderer 在 React native 中编写一些单元测试,我们的一大堆组件都在使用 react-native-elements 库来提供控件。

然而,我发现,在我的小快照测试中,主题对象是大部分内容,因此更难看到实际更改。我想知道是否有人知道关闭此功能的方法?

到目前为止,我唯一的想法是将每个测试包装在 ThemeProvider 中,并为其提供一个空白主题,这是很多样板。

这是一个示例快照

exports[`LocationInfo renders correctly 1`] = `
<Text
  style={Object {}}
  theme={
    Object {
      "colors": Object {
        "disabled": "hsl(208, 8%, 90%)",
        "divider": "#bcbbc1",
        "error": "#ff190c",
        "grey0": "#393e42",
        "grey1": "#43484d",
        "grey2": "#5e6977",
        "grey3": "#86939e",
        "grey4": "#bdc6cf",
        "grey5": "#e1e8ee",
        "greyOutline": "#bbb",
        "platform": Object {
          "android": Object {
            "error": "#f44336",
            "primary": "#2196f3",
            "secondary": "#9C27B0",
            "success": "#4caf50",
            "warning": "#ffeb3b",
          },
          "ios": Object {
            "error": "#ff3b30",
            "primary": "#007aff",
            "secondary": "#5856d6",
            "success": "#4cd964",
            "warning": "#ffcc00",
          },
        },
        "primary": "#2089dc",
        "searchBg": "#303337",
        "secondary": "#8F0CE8",
        "success": "#52c41a",
        "warning": "#faad14",
      },
    }
  }
>
  KEY/100, Main Building
</Text>
`;

【问题讨论】:

    标签: reactjs react-native unit-testing jestjs react-native-elements


    【解决方案1】:

    您可以创建一个 HOC 的模拟,它传递收到的道具并可能添加一些模拟主题

    const mockHOC = WrappedComponent => {
      const ThemedComponent = (props) => (
        <WrappedComponent {...props} theme="omitted" />
      );
      ThemedComponent.displayName = `MockThemed(${WrappedComponent.displayName ||  WrappedComponent.name || 'Component'})`
      return ThemedComponent;
    };
    

    1。您可以使用 spyOn 将模拟实现附加到 withTheme

    jest.setup.js (setupFilesAfterEnv)
    import RNE from 'react-native-elements';
    
    const mockHOC = // ....;
    jest.spyOn(RNE, 'withTheme').mockImplementation(mockHOC)
    

    2。您可以尝试定义a global mock

    __mocks__/react-native-elements/config/withTheme.js
    const mockHOC = // ....;
    export default jest.fn(mockHOC)
    

    【讨论】:

    • @Ian 抱歉,但尚未测试我的答案
    • 别担心,这看起来是一个有趣的方法,所以我会去尝试一下 :) 谢谢
    • 不幸的是,这些方法不起作用。我认为因为导出定义为 default export withTheme(Text) 例如,withTheme HoC 在我有机会模拟它之前已经执行。
    猜你喜欢
    • 2021-09-01
    • 1970-01-01
    • 2021-03-28
    • 1970-01-01
    • 2012-01-02
    • 1970-01-01
    • 1970-01-01
    • 2017-04-08
    • 1970-01-01
    相关资源
    最近更新 更多