【问题标题】:Jest styled-components 4.1.1 test are brokenJest styled-components 4.1.1 测试被破坏
【发布时间】:2019-05-02 10:25:51
【问题描述】:

最近我将 styled-components 更新到 4.1.1 并且大部分组件测试都被破坏了。我只是创建一个哑组件来进行哑测试,看看它是否取决于其他测试是如何进行的,或者仅仅是样式组件的当前版本。

给出这个 Button 组件:

import styled from 'styled-components';

const Button = styled.button`
  color: red;
`;
export default Button;

这里是相关测试:

import React from 'react';
import renderer from 'react-test-renderer';
import 'jest-styled-components';
import Button from './Button';

test('it works', () => {
  const tree = renderer.create(<Button />).toJSON();
  expect(tree).toMatchSnapshot();
});

输出是:

Invariant Violation: Unable to find node on an unmounted component.

可能是最新版本的 styled-components 和一些其他依赖导致的?

我没有在官方文档中找到任何东西。

【问题讨论】:

  • 您使用的是哪个版本的jest-styled-components
  • jest-styled-components@6.3.1

标签: reactjs unit-testing jestjs styled-components


【解决方案1】:

我在使用 react-test-renderer 和样式化组件时遇到了无穷无尽的问题。我发现解决这个问题的方法是使用另一个名为 react-testing-library 的 npm 模块

然后代替

const tree = renderer.create(<Button />).toJSON();

使用

const tree = render(<Button />).toJSON();

然后

expect(tree).toMatchSnapshot();

这应该可行!

【讨论】:

    【解决方案2】:

    你的所有 React 依赖项都更新和版本同步了吗? reactreact-domreact-test-rendererreact-is 都应该在同一个版本上,最好在 16.4 以上。

    【讨论】:

      猜你喜欢
      • 2019-05-11
      • 2017-11-01
      • 2020-01-24
      • 2015-01-08
      • 2017-11-22
      • 2020-12-17
      • 2018-03-14
      • 2020-05-04
      • 1970-01-01
      相关资源
      最近更新 更多