我正在使用 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
属性 . 如何将主题传递给我的组件?
2 回答
鉴于这种...
${({ theme }) => theme.colors.main.default};
......而且这个错误......
TypeError: Cannot read property 'main' of undefined
...它看起来像
props.theme
确实存在于样式化组件中,但主题没有colors
属性 . 我会查看主题定义或问题来源的ThemeProvider
的设置 .我通过创建一个解决方法帮助函数来解决这个问题 . 我有主题对象,其中包含深色和浅色主题:
现在我可以获得包装器组件的状态和主题:
mountWithTheme(<Component {...props} />)