Jest styled-components 4.1.1 测试被破坏
Posted
技术标签:
【中文标题】Jest styled-components 4.1.1 测试被破坏【英文标题】:Jest styled-components 4.1.1 test are broken 【发布时间】: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
【参考方案1】:
我在使用 react-test-renderer 和样式化组件时遇到了无穷无尽的问题。我发现解决这个问题的方法是使用另一个名为 react-testing-library 的 npm 模块
然后代替
const tree = renderer.create(<Button />).toJSON();
使用
const tree = render(<Button />).toJSON();
然后
expect(tree).toMatchSnapshot();
这应该可行!
【讨论】:
【参考方案2】:你的所有 React 依赖项都更新和版本同步了吗? react
、react-dom
、react-test-renderer
和 react-is
都应该在同一个版本上,最好在 16.4 以上。
【讨论】:
以上是关于Jest styled-components 4.1.1 测试被破坏的主要内容,如果未能解决你的问题,请参考以下文章