使用子道具测试渲染组件

时间:2019-11-14 10:05:49

标签: javascript reactjs jestjs

我在其他组件中包含组件。在浏览器中看起来不错,但是在单元测试期间,我遇到了一个错误。我不知道为什么我尝试使用.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.

})

1 个答案:

答案 0 :(得分:0)

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子代。将<Head>替换为<div>,或使用空字符串调用模板函数:const Head = styled.div``就足够了。