当我使用 jest 来测试 react 组件时,它会抛出"Invariant Violation:Element type is invalid: expected a string (for bui



我的代码是

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")
})
})

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

如果您尝试导入命名导出(Tooltipexport default Tooltip(,这应该可以修复它:

import Tooltip from "../../../../../main/js/app/components/ui/Tooltip"

但是,如果您只导入Tooltip类,则需要导出类组件本身,

export class Tooltip extends React.Component {
// the rest 
}

然后仅导入类组件,而不是默认导出。

import { Tooltip } from "../../../../../main/js/app/components/ui/Tooltip"

相关内容

最新更新