【问题标题】:Test rendering component with child props使用子道具测试渲染组件
【发布时间】:2019-11-14 18:17:25
【问题描述】:

我有一个包含其他组件的组件。在浏览器中看起来不错,但在单元测试期间我遇到了错误。我不知道为什么。我尝试使用.map() 方法进行渲染,但没有成功。感谢您的帮助!

Error: Uncaught [Invariant Violation: Objects are not valid as a React child (found
: object with keys {$$typeof, render, attrs, componentStyle, displayName, foldedComponentIds, styledComponentId, target, withComponent, warnTooManyClasses, toString}). If you meant to render a collection of children, use an array instead.

AppBarTop.js

const AppBarTopWrapper = styled.div`
  background: ${props => props.theme.color.backgroundSecondary};
  border-bottom: 1px solid ${props => props.theme.color.line};
  padding: 2rem 2rem 0rem 2rem;
  color: ${props => props.theme.color.secondaryText};
`
const AppBarTop = ({ children }) => (
  <AppBarTopWrapper>{children}</AppBarTopWrapper>
)

AppBarTop.propTypes = {
  children: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
}

export default AppBarTop

测试

const Head = styled.div
function renderTitle(props) {
  return renderWithRouter(
    <AppBarTop>
      <Head>
        <UpwardButton level={2} />
        <Title level={1} {...props.message} />
      </Head>
    </AppBarTop>,
    {
      withStore: true,
    },
  )
}

const testFormattedMessage = text => ({
  id: 'test',
  defaultMessage: text,
})

describe('<Heading />', () => {
  it('Expect to not log errors in console', () => {
    const spy = jest.spyOn(global.console, 'error')
    console.log(renderTitle({ message: testFormattedMessage('test title') }))
    renderTitle({ message: testFormattedMessage('test title') })
    expect(spy).not.toHaveBeenCalled()
  })It looks like your post is mostly code; please add some more details.

})

【问题讨论】:

  • Title 组件长什么样子?

标签: javascript reactjs jestjs


【解决方案1】:

styled.div 返回 template function 而不是组件。因此在您的代码中

const Head = styled.div
function renderTitle(props) {
  return renderWithRouter(
    <AppBarTop>
      <Head>
        <UpwardButton level={2} />
        <Title level={1} {...props.message} />
      </Head>
    </AppBarTop>,
    {
      withStore: true,
    },
  )
}

Head 不是一个组件(而是一个常规函数),即它不是一个有效的 React 子组件。将&lt;Head&gt; 替换为&lt;div&gt;,或者使用空字符串调用模板函数:const Head = styled.div`` 就足够了。

【讨论】:

    猜你喜欢
    • 2021-09-25
    • 2017-11-20
    • 1970-01-01
    • 1970-01-01
    • 2017-06-10
    • 2020-01-20
    • 2021-04-07
    • 2021-04-23
    • 2021-11-07
    相关资源
    最近更新 更多