2017-02-13 73 views
4

我使用reactstyled-componentsjestenzyme为我的测试。我遇到了麻烦,因为themestyled-components,测试主题组件不断出现错误。酶主题呈现风格的组件

我的部分是:

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') 
}) 

玩笑给了我这个错误:

<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属性。我如何将主题传递给我的组件?

+0

你找到任何解决问题了吗? – rels

+0

你曾经解决过这个问题吗? – DavidWorldpeace

+0

嗨,很抱歉,很长的延迟!与此同时,一些公用事业公司推出了带有风格的组件。 他们推荐的主题只是将它作为道具传递。你也可以创建一个围绕“浅”方法的封装来自动执行。 ([Source](https://github.com/styled-components/jest-styled-components#theming)) – Dispix

回答

0

鉴于这种......

${({ theme }) => theme.colors.main.default};

...而这个错误...

TypeError: Cannot read property 'main' of undefined

...它看起来对我来说,props.theme内部存在该风格的组件,但主题没有colors属性。我会看看主题定义或者设置ThemeProvider来解决问题的根源。

0

我通过创建一个解决方法辅助函数来解决此问题。我得到的主题对象包含黑暗与光明的主题:

const CHANNEL = '__styled-components__'; 
    const broadcast = createBroadcast(themes.dark); 

    const nodeWithThemeProp = node => { 
     return React.cloneElement(node, { [CHANNEL]: broadcast.subscribe }); 
    }; 

    export function mountWithTheme(node, { context, childContextTypes } = {}) { 
     return mount(
     nodeWithThemeProp(node), 
     { 
      context: Object.assign({}, context, {[CHANNEL]: broadcast.subscribe}), 
      childContextTypes: Object.assign({}, {[CHANNEL]: createBroadcast(themes.dark).publish}, childContextTypes) 
     } 
    ); 
    } 

现在我可以在包装部件的状态和主题preseted: mountWithTheme(<Component {...props} />)

+0

嗨,谢谢你的回答,你在哪里导入createBroadcast? – JimmyLv

+0

从'../../node_modules/styled-components/lib/utils/create-broadcast'导入createBroadcast; @JimmyLv对不起,没有检查这个 –