简体   繁体   English

在 React 中使用 DOM 操作库进行测试

[英]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.我使用 OpenSheetMusikDisplay 库和 React,它可以在目标下方动态添加一些元素到 DOM。 I use a ref to a div as the target element, which works fine.我使用 div 的 ref 作为目标元素,效果很好。 I myself need to add additional elements to the DOM, based on the libraries state.我自己需要根据库状态向 DOM 添加其他元素。 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.基本上,我用一些 div 覆盖渲染的工作表,这些 div 需要是库为正确定位而添加的元素之一的子元素。

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.我想使用 Enzyme 测试这个组件,但找到覆盖层的唯一包装器是 Cheerio,据我所知,它不支持触发输入事件。 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?我的问题是是否有另一种方法来测试动态添加元素的事件处理,或者是否有更多类似 React 的方法来处理直接操作 DOM 的后处理库?

I solved it by using the DOM Api directly.我是直接用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);
  });
});

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

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