简体   繁体   English

如何在 React 组件的 risklySetInnerHTML 内容中使用酶测试点击事件

[英]How to test a click event with enzyme in a React component's dangerouslySetInnerHTML content

I have a component that just renders customer entered HTML.我有一个组件,它只呈现客户输入的 HTML。 This HTML can contain links.此 HTML 可以包含链接。 The click events are intercepted.点击事件被拦截。 How can I test this in Enzyme?我如何在酶中测试这个?

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; }}
      />
    );
  }
}

I was able to solve it by attaching the mount to the DOM.我能够通过将安装附加到 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();

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM