Ad

Test Rendering Component With Child Props

- 1 answer

I have component within I containment other components. In browser It looks like good but during unit testing I'm getting below an error. I don't know why. I have try render with .map() method but it didn't work. Thanks for help!

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

Test

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.

})
Ad

Answer

styled.div returns a template function rather than a component. Hence in your code

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

Head is not a component (but a regular function), i.e. it's not a valid React child. Replacing <Head> with <div>, or invoking template function with empty string: const Head = styled.div`` would be sufficient.

Ad
source: stackoverflow.com
Ad