Jest snapshot test adds a "_class" word into React HOC in snapshot on CI but not on my machine

224 views Asked by At

I have a React component importing another React HOC.

My React HOC:

import { withRouter } from "react-router";
...
const InnerComponent: FC<any> = (props): ReactElement => {
...
}

const withData = compose(
  graphql(SOME_QUERY, {
    props: mapProps,
    options,
  }),
  injectIntl
);

export default withRouter(withX(withData(InnerComponent)));

My React Component:

export const OuterComponent: FC<any> = (props): ReactElement => {
    ...
    return (
    ...
    <InnerComponent />
    ...
)}

This is an excerpt from my test spec file (I use enzyme & jest):

const component = shallow(<OuterComponent {...props} />)
expect(component).toMatchSnapshot()

Locally, everything works fine. The part where my InnerComponent should be rendered is represented like this in the snapshot:

<withRouter() />

When I check-in my code and let it run on CI, snapshot test fails because that line in the snapshot CI generates looks like this:

<withRouter(_class) />

I am sure that enzyme and jest versions are same on CI and my machine. I even tried to update jest and enzyme on my machine but never got a snapshot having this weird _class word.

Where does this _class come from and how can I avoid it, or how can make sure that my local setup also generates it during snapshot creation?

1

There are 1 answers

1
schlingel On

This problem can be avoided by setting proper displayName for our custom HOCs. In this case, the withX HOC didn't have any displayName. I changed it to look like below so that the HOC in snapshot is generated with same name both in local machine and in build server.

export function withX(WrappedComponent) {  
  class WithX extends React.Component {
    render() {
      ...     
      return <WrappedComponent {...this.props} />
    }
  }
  WithX.displayName = `WithX(${getDisplayName(WrappedComponent)})`
  return WithX
}

function getDisplayName(WrappedComponent) {
  return WrappedComponent.displayName || WrappedComponent.name || 'Component'
}

This still doesn't explain why the HOC had no name in local machine but had the name _class on build server, though.