Ian
Ian

Reputation: 34539

Is it possible to remove theme from React test renderer?

I'm writing some unit tests in React native using the recommended react-test-renderer, a whole bunch of our components are using the react-native-elements library to provide controls.

What I'm finding however, is that in my small snapshot tests, that the theme object is most of the content, and makes it harder to see the actual changes. I'm wondering if anyone knows a way of turning this off?

The only idea I've so far, is to wrap every single test in a ThemeProvider and provide it with a blank theme, which is a lot of boilerplate.

Here's an example snapshot

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>
`;

Upvotes: 1

Views: 622

Answers (1)

Teneff
Teneff

Reputation: 32148

You can create a mock of the HOC which passes the received props and probably adding some mock theme

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

1. You can use spyOn to attach mock implementation to withTheme

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

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

2. You can try defining a global mock

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

Upvotes: 1

Related Questions