【问题标题】:Jest - Snapshot test fail after adding '</React.Fragment>'开玩笑 - 添加 '</React.Fragment>' 后快照测试失败
【发布时间】:2020-02-24 17:28:45
【问题描述】:

我在运行 Jest 后收到以下错误。我没有太多使用 Jest 的经验,因此希望有人能提供有关此测试失败原因的信息。

结果: 笑话测试结果:

- Snapshot
+ Received
- <span
-   className="icon icon-dismiss size-2x "
-   style={
-     Object {
-       "color": "inherit",
+ <Fragment>
+   <span
+     className="icon icon-dismiss size-2x "
+     style={
+       Object {
+         "color": "inherit",
+       }
      }
-   }
-   title=""
- />
+     title=""
+   />
+ </Fragment>

  26 |     };
  27 |     const wrapper = shallow(<Icon {...props} />);
> 28 |     expect(toJson(wrapper)).toMatchSnapshot();
     |                             ^
  29 |   });
  30 | });

这是测试文件: 测试文件

Component.spec.jsx

describe('Snapshot test - <Icon />', () => {
  it('renders Icon correctly in clean state', () => {
    const props = {
      icon: 'dismiss',
    };
    const wrapper = shallow(<Icon {...props} />);
    expect(toJson(wrapper)).toMatchSnapshot();
  });
  it('renders Icon correctly when colour provided', () => {
    const props = {
      icon: 'dismiss',
      color: '#000000',
    };
    const wrapper = shallow(<Icon {...props} />);
    expect(toJson(wrapper)).toMatchSnapshot();
  });

});

这是组件文件: component.js


class Icon extends React.PureComponent<IconProps> {
  render() {
    const {
      className, icon, size, colour, style, title,
    } = this.props;

    return (
      <React.Fragment>
        {icon === 'spinner' ? <LoadingSpinnerSmall /> : (
          <span
            title={title}
            className={`${css.icon} ${css[`icon-${icon}`]} ${css[`size-${size}`]} ${className}`}
            style={{ color: colour === null ? 'initial' : colour, ...style }}
          />
        )
      }
      </React.Fragment>
    );
  }
}

export default Icon;

【问题讨论】:

  • 当您更改测试并在最后一次运行这些测试之后运行测试时会发生这种情况。尝试删除之前的快照,然后运行测试。
  • @AtinSingh 我在组件文件中添加了“”,从那以后测试就失败了。
  • 是的,这就是它失败的原因,因为您的组件发生了变化。查看错误。它说received + &lt;Fragment&gt; 尝试删除您的旧快照,然后尝试运行测试。
  • 谢谢 - 我会试试的
  • 告诉我它是否有效?

标签: javascript reactjs testing jestjs


【解决方案1】:

您的快照匹配测试结果

- Snapshot
+ Received
- <span
-   className="icon icon-dismiss size-2x "
-   style={
-     Object {
-       "color": "inherit",
+ <Fragment>
+   <span
+     className="icon icon-dismiss size-2x "
+     style={
+       Object {
+         "color": "inherit",
+       }
      }
-   }
-   title=""
- />
+     title=""
+   />
+ </Fragment>

这表明您的组件在您上次运行测试时有额外的代码,即&lt;Fragment&gt; 开始标记和&lt;/Fragment&gt; 结束标记。

要解决这个问题,只需删除旧快照并重新运行测试即可。

【讨论】:

    猜你喜欢
    • 2017-08-11
    • 1970-01-01
    • 2017-10-01
    • 2018-02-13
    • 2017-11-19
    • 2020-10-08
    • 2019-08-20
    • 1970-01-01
    • 2018-12-17
    相关资源
    最近更新 更多