【问题标题】:Testing with DOM Manipulating Libraries in React在 React 中使用 DOM 操作库进行测试
【发布时间】:2020-09-10 07:53:44
【问题描述】:

我使用一个库 OpenSheetMusikDisplay 和 React,它可以动态地将目标下方的一些元素添加到 DOM。我使用 div 的 ref 作为目标元素,效果很好。我自己需要根据库状态向 DOM 添加其他元素。基本上,我用一些 div 覆盖渲染的工作表,这些 div 需要是库添加的元素之一的子元素,以便正确定位。

我想使用 Enzyme 测试这个组件,但唯一能找到覆盖的包装器是 Cheerio 包装器,据我所知,它不支持触发输入事件。叠加层可以点击,所以我需要对此行为进行测试。

我的问题是,是否有另一种方法来测试动态添加元素的事件处理,或者是否有更多类似 React 的方法来处理直接操作 DOM 的后处理库?

【问题讨论】:

    标签: javascript reactjs enzyme


    【解决方案1】:

    我直接使用 DOM Api 解决了。

    import React from 'react';
    import enzyme from 'enzyme';
    import Adapter from 'enzyme-adapter-react-16';
    
    enzyme.configure({ adapter: new Adapter() });
    
    function doSomeDomManipulation(element: Element) {
      const child = document.createElement('div');
      child.classList.add("some-class");
      element.appendChild(child);
    }
    
    class Foo extends React.Component<{}, {}>{
      divRef: React.RefObject<HTMLDivElement>;
      
      constructor(props: {}) {
        super(props);
        this.divRef = React.createRef()
      }
    
      render() { 
        return <div ref={this.divRef}></div>;
      }
    
      componentDidMount() {
        doSomeDomManipulation(this.divRef.current!);
      }
    }
    
    describe("Foo", () => {
      const root = document.createElement('div');
      const wrapper = enzyme.mount(<Foo/>, {
        attachTo: root
      });
    
      it('has a div with class "some-class"', () => {
        const length = root.querySelectorAll("some-class").length;
        expect(length).toBe(1);
      });
    });
    

    【讨论】:

      猜你喜欢
      • 2011-12-02
      • 2013-04-16
      • 1970-01-01
      • 2019-12-31
      • 2020-10-19
      • 2023-03-24
      • 1970-01-01
      • 2010-10-24
      • 1970-01-01
      相关资源
      最近更新 更多