测试工具提示的 onHover 事件

Test onHover event of a tooltip

我正在使用 React 测试库来测试这个组件:

export default class A extends React.Component {
    constructor(props) {
        super(props);
        this.titleParagraphRef = React.createRef();
        this._tooltipTimer = null;
        this.state = { shouldPopupBeEnabled: false, isTooltipShown: false };

        this._showTooltip = this._showTooltip.bind(this);
        this._hideTooltip = this._hideTooltip.bind(this);
    }

    componentDidMount() {
        const { scrollWidth, clientWidth } = this.titleParagraphRef.current;
        const shouldPopupBeEnabled = scrollWidth > clientWidth;
        this.setState({ shouldPopupBeEnabled });
    }

    _showTooltip() {
        const { tooltipShowTime } = this.props;
        this._tooltipTimer = setTimeout(
            () => {
                this.setState({ isTooltipShown: true });
            }, tooltipShowTime,
        );
    }

    _hideTooltip() {
        clearTimeout(this._tooltipTimer);
        this.setState({ isTooltipShown: false });
    }

    render() {
        const { shouldPopupBeEnabled, isTooltipShown } = this.state;
        const { name, tooltipShowTime, ...rest } = this.props;

        return (
            <ToolTip
                message={name}
                toolTipPosition="top"
                messageStyleName="warning-tool-tip"
                popoverOpen={shouldPopupBeEnabled && isTooltipShown}
            >
                <div
                    ref={this.titleParagraphRef}
                    onMouseOver={this._showTooltip}
                    onMouseOut={this._hideTooltip}
                    onFocus={this._showTooltip}
                    onBlur={this._hideTooltip}
                    {...rest}
                    data-testid="title-tooltip"
                >
                    {name}
                </div>
            </ToolTip>
        );
    }
}

我想测试的是,当我将鼠标悬停在标题上时,会显示工具提示。为此,我编写了这个测试:

    test('When on hover, tooltip should be displayed', async () => {
        const { getByTestId } = _renderToolTip();
        const titleElement = getByTestId('title-tooltip');
        fireEvent.mouseOver(titleElement);
        expect(titleElement).toMatchSnapshot();
    });

    function _renderToolTip() {
        return render(
            <A name="VERY VERY VERY VERY VERY LONG TEXT" tooltipShowTime={50} />,
        );
    }

但是它不起作用。生成的快照不包含工具提示代码。我也尝试使用 asFrament,结果相同。该组件在浏览器中运行良好。知道如何测试此 mouseOver 事件吗?

由于在显示工具提示之前依赖 setTimeout 延迟,因此您需要修改测试以使其等待鼠标悬停时出现的任何元素,然后再对其断言:https://testing-library.com/docs/guide-disappearance/#waiting-for-appearance