[英]Testing with DOM Manipulating Libraries in React
我使用 OpenSheetMusikDisplay 库和 React,它可以在目标下方动态添加一些元素到 DOM。 我使用 div 的 ref 作为目标元素,效果很好。 我自己需要根据库状态向 DOM 添加其他元素。 基本上,我用一些 div 覆盖渲染的工作表,这些 div 需要是库为正确定位而添加的元素之一的子元素。
我想使用 Enzyme 测试这个组件,但找到覆盖层的唯一包装器是 Cheerio,据我所知,它不支持触发输入事件。 可以点击叠加层,所以我需要对这种行为进行测试。
我的问题是是否有另一种方法来测试动态添加元素的事件处理,或者是否有更多类似 React 的方法来处理直接操作 DOM 的后处理库?
我是直接用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.