简体   繁体   中英

Testing with DOM Manipulating Libraries in React

I use a library, OpenSheetMusikDisplay, with React that dynamically adds a few Elements below a target to the DOM. I use a ref to a div as the target element, which works fine. I myself need to add additional elements to the DOM, based on the libraries state. Basically I overlay the rendered sheet with some divs, which need to be children of one of the elements the library added for proper positioning.

I want to test this component using Enzyme, but the only wrapper that finds the overlays is the Cheerio one which, as far as I can see, does not support triggering input events. The overlays are there to be clicked on, so I need to have a test for this behavior.

My Question either if there is another way to test for event handling with dynamically added elements or if there is more React like way to handle post-processing libraries that directly manipulate the DOM?

I solved it by using the DOM Api directly.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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