首页 > 解决方案 > 错误:未捕获 [不变违规:对象作为 React 子对象无效

问题描述

为组件编写渲染测试并且无法解决此错误:

Error: Uncaught [Invariant Violation: Objects are not valid as a React child (found: object with keys {$$typeof, type, compare, displayName, muiName}). If you meant to render a collection of children, use an array instead...

我知道这一定很简单,但我正在疏远。这是我的测试文件的样子:

import React from 'react';
import { render } from '@testing-library/react';

import DashboardCard from '../index';

const CardWithProps = () => (
  <DashboardCard title="title">
    <div>child</div>
  </DashboardCard>
);

describe('<DashboardCard />', () => {
  it('Expect to not log errors in console', () => {
    const spy = jest.spyOn(global.console, 'error');
    render(<CardWithProps />);
    expect(spy).not.toHaveBeenCalled();
  });
});

仪表板卡:

import React from 'react';
import T from 'prop-types';

import { CardContainer, StyledSpan } from './styledComponents';

const DashboardCard = ({ children, title }) => (
  <CardContainer>
    <StyledSpan>{title}</StyledSpan>
    {children}
  </CardContainer>
);

DashboardCard.propTypes = { children: T.node.isRequired, title: T.string.isRequired };

export default DashboardCard;

卡片容器:

import styled from 'styled-components';

export const CardContainer = styled.article`
  background-color: white;
  padding: 2rem 4rem 1rem;
`;

标签: reactjsjestjsreact-testing-library

解决方案


推荐阅读