首页 文章

酶渲染风格的组件与主题

提问于
浏览
5

我正在使用 reactstyled-componentsjest enzyme 进行测试 . 由于来自 styled-componentstheme ,我在测试一个因错误而导致错误的主题组件时遇到了麻烦 .

我的组件是:

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 回答

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

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

相关问题