2017-02-13 80 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對不起,沒有檢查這個 –