首页 > 解决方案 > Jest 快照测试在 CI 快照中的 React HOC 中添加了一个“_class”字,但在我的机器上没有

问题描述

我有一个导入另一个 React HOC 的 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)));

我的反应组件:

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

这是我的测试规范文件的摘录(我使用酶和玩笑):

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

在本地,一切正常。我的 InnerComponent 应该被渲染的部分在快照中是这样表示的:

<withRouter() />

当我签入我的代码并让它在 CI 上运行时,快照测试失败,因为快照 CI 生成的该行如下所示:

<withRouter(_class) />

我确信 CI 和我的机器上的酶和开玩笑版本是相同的。我什至尝试在我的机器上更新 jest 和酵素,但从来没有得到包含这个奇怪_class词的快照。

_class是从哪里来的,我该如何避免它,或者如何确保我的本地设置也在创建快照期间生成它?

标签: reactjsjestjsenzymesnapshot-testing

解决方案


这个问题可以通过displayName为我们的自定义 HOC 设置适当的来避免。在这种情况下,withXHOC 没有任何displayName. 我将其更改为如下所示,以便在本地计算机和构建服务器中生成具有相同名称的快照中的 HOC。

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'
}

不过,这仍然不能解释为什么 HOC 在本地机器上没有名称,但_class在构建服务器上有名称。


推荐阅读