当我使用玩笑来测试react组件时,它会抛出“ Invariant Violation:元素类型无效:预期为字符串(对于内置组件)”

问题描述 投票:0回答:1

我的代码是

import React, {Fragment} from 'react'
import ReactTooltip from 'react-tooltip'
import PropTypes from 'prop-types'

class Tooltip extends React.Component {
  childRef = React.createRef();

  render() {
    const props = this.props;
    const child = React.Children.only(props.children);

    const trigger = React.cloneElement(
      child,
      {ref: this.childRef, 'data-tip': this.props.title}
    )

    if (!props.title) {
      return trigger
    }

    return (
      <Fragment>
        {trigger}
        <ReactTooltip place={props.placement} effect="solid"/>
      </Fragment>
    )
  }
}

Tooltip.propTypes = {
  title: PropTypes.string,
  children: PropTypes.element.isRequired,
  placement: PropTypes.string,
}

Tooltip.defaultProps = {
  placement: 'bottom',
}

export default Tooltip

我的测试是:

import React from 'react'
import {mount} from "enzyme"

import {Tooltip} from "../../../../../main/js/app/components/ui/Tooltip"
describe('Tooltip', () => {
    let props ,tooltip
    beforeEach(() => {
        props = {
            title: 'test title',
            placement: 'bottom',
            children: <div/>
        }
        tooltip= mount(<Tooltip {...props}/>)
    })

    it('should render', () => {
        // jest.fn(React.Children.only(props.children))
        // const child = React.Children.only(props.children);
        // const  reactTooltip =tooltip.find(ReactTooltip)
       // expect(reactTooltip).toContain("bottom")
    })
})

当我运行测试时,它会引发错误:不变违规:元素类型无效:预期为字符串(对于内置组件)或类/函数(对于复合组件),但得到:未定义。您可能忘记了从定义的文件中导出组件,或者可能混淆了默认导入和命名导入。

reactjs jest
1个回答
0
投票

如果您要导入命名的导出,则应解决此问题:

import Tooltip from "../../../../../main/js/app/components/ui/Tooltip"
© www.soinside.com 2019 - 2024. All rights reserved.