如何在 React-Native 项目中使用 Jest 测试样式化组件?

Posted

技术标签:

【中文标题】如何在 React-Native 项目中使用 Jest 测试样式化组件?【英文标题】:How to test styled-components with Jest in React-Native project? 【发布时间】:2021-11-25 20:54:48 【问题描述】:

在我的项目中,我有一个带有 styled-components 样式的组件。我想用 jest 对其进行测试:

describe('<Button/> tests', () => 
    it('should render button', () => 
        const testingComponent =  renderer.create(<Button/>);
    )
);

此代码失败:

 ● Test suite failed to run

    TypeError: _styledComponents.default.View is not a function

      1 | import styled from 'styled-components';
      2 |
    > 3 | const Container = styled.View`
        |                          ^
      4 |   flex: 1;
      5 |   align-self: center;
      6 | `;

所以开玩笑不认识styled.View,我不知道为什么。我做错了什么以及如何测试我使用 styled-components 设置样式的组件?

【问题讨论】:

【参考方案1】:

为了避免此类错误,需要以这种方式指定样式组件:

const Container = styled(View)

这个语法帮助了我

【讨论】:

以上是关于如何在 React-Native 项目中使用 Jest 测试样式化组件?的主要内容,如果未能解决你的问题,请参考以下文章