9

我正在使用reactwith styled-components,并jest enzyme用于我的测试。我在测试一个由于themefrom而不断出错的主题组件时遇到了麻烦styled-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属性。如何将主题传递给我的组件?

4

2 回答 2

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

现在我可以获取包装组件的状态和预设的主题: mountWithTheme(<Component {...props} />)

于 2017-03-29T15:23:25.590 回答
-1

鉴于这种...

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

...而这个错误...

TypeError: Cannot read property 'main' of undefined

...在我看来,样式组件props.theme 中确实存在,但主题没有colors属性。我会查看主题定义或ThemeProvider问题根源的设置。

于 2017-03-04T00:32:28.583 回答