【发布时间】:2017-07-01 06:12:49
【问题描述】:
我使用react 和styled-components 和jest enzyme 进行测试。由于来自styled-components 的theme,我在测试一个不断出错的主题组件时遇到了麻烦。
我的组件是:
const Wrapper = styled.header`
position: fixed;
top: 0;
left: 0;
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: space-between;
width: 100%;
height: 64px;
background-color: ${({ theme }) => theme.colors.main.default};
color: ${({ theme }) => theme.colors.main.text};
`
我的测试是:
it('should render a <header> tag', () => {
const renderedComponent = shallow(<Wrapper />)
expect(renderedComponent.type()).toEqual('header')
})
Jest 给了我这个错误:
<Wrapper /> › should render a <header> tag
TypeError: Cannot read property 'main' of undefined
at Object.<anonymous>._styledComponents2.default.header.theme (app/containers/AppBar/Wrapper.js:13:182)
基本上,它会引发错误,因为 theme 未定义,因此它无法读取其中的 colors 属性。如何将主题传递给我的组件?
【问题讨论】:
-
您找到解决问题的方法了吗?
-
你解决过这个问题吗?
-
您好,很抱歉耽搁了这么久!与此同时,jest-styled-components 出现了一些实用程序。他们为主题推荐的只是将其作为道具传递。您还可以在 jest 中围绕
shallow方法创建一个包装器来自动执行此操作。 (Source)
标签: reactjs jestjs enzyme styled-components