首页 > 解决方案 > 是否可以从 React 测试渲染器中删除主题?

问题描述

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

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

到目前为止,我唯一的想法是将每个测试包装在 a 中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>
`;

标签: reactjsreact-nativeunit-testingjestjsreact-native-elements

解决方案


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

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

1. 可以使用 spyOn 将 mock 实现附加到 withTheme

jest.setup.js( setupFilesAfterEnv )
import RNE from 'react-native-elements';

const mockHOC = // ....;
jest.spyOn(RNE, 'withTheme').mockImplementation(mockHOC)

2.你可以尝试定义一个全局mock

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

推荐阅读