【问题标题】:Enzyme render styled component with theme带有主题的酶渲染样式组件
【发布时间】:2017-07-01 06:12:49
【问题描述】:

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

【问题讨论】:

  • 您找到解决问题的方法了吗?
  • 你解决过这个问题吗?
  • 您好,很抱歉耽搁了这么久!与此同时,jest-styled-components 出现了一些实用程序。他们为主题推荐的只是将其作为道具传递。您还可以在 jest 中围绕 shallow 方法创建一个包装器来自动执行此操作。 (Source)

标签: reactjs jestjs enzyme styled-components


【解决方案1】:

我通过创建一个解决方法帮助函数来解决这个问题。我得到了包含深色和浅色主题的主题对象:

    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(&lt;Component {...props} /&gt;)

【讨论】:

  • 您好,感谢您的回答,您在哪里导入 createBroadcast?
  • 从'../../node_modules/styled-components/lib/utils/create-broadcast'导入createBroadcast; @JimmyLv 抱歉,没有检查这个
【解决方案2】:

鉴于此...

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

...还有这个错误...

TypeError: Cannot read property 'main' of undefined

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

【讨论】:

    猜你喜欢
    • 2019-02-24
    • 1970-01-01
    • 1970-01-01
    • 2019-02-16
    • 2015-03-09
    • 2018-03-24
    • 2021-11-09
    • 2020-05-08
    • 2018-07-08
    相关资源
    最近更新 更多