如何在React组件的dangerouslySetInnerHTML内容中使用酶测试click事件

时间:2017-07-13 07:00:03

标签: reactjs enzyme

我有一个只提供客户输入HTML的组件。此HTML可以包含链接。拦截点击事件。我怎样才能在酶中测试它?

class Html extends React.Component {
  componentDidMount() {
    this.htmlContainer.addEventListener('click', this.handleTap, true);
  }

  componentWillUnmount() {
    this.htmlContainer.removeEventListener('click', this.handleTap, true);
  }

  handleTap = (event) => {
    // do stuff ...
  }

  render() {
    return (
      <div
        dangerouslySetInnerHTML={{ __html: this.props.html }}
        ref={(domElm) => { this.htmlContainer = domElm; }}
      />
    );
  }
}

1 个答案:

答案 0 :(得分:0)

我能够通过将坐骑连接到DOM来解决它。

// The Component

function CustomHtml({ html, trackInteraction }) {
    const ref = useRef<?HTMLDivElement>();

    const trackClick = useCallback(() => {
        trackInteraction();
    }, [trackInteraction]);

    useEffect(() => {
        const elements = ref.current?.querySelectorAll('[data-click-track]') || [];

        elements.forEach(element => {
            element.addEventListener('click', trackClick);
        });

        return () => {
            elements.forEach(element => {
                element.removeEventListener('click', trackClick);
            });
        };
    }, [trackClick]);

    return <div ref={ref} dangerouslySetInnerHTML={{ __html: html }} />;
}

// The Test

it('should call mock on click on inner html', () => {

    const trackInteractionMock = jest.fn();

    const body = document.querySelector('body');
    body.appendChild(document.createElement('div'));

    const wrapper = mount(
        <CustomHtml html="<span data-click-track>click me</span>" trackInteraction={trackInteractionMock} />,
        { attachTo: body.firstChild }
    );

    const span = document.querySelector('[data-click-track]');
    const event = new Event('click');
    span.dispatchEvent(event);

    expect(trackInteractionMock).toHaveBeenCalledWith();

});