请帮助,我有一个小的演示,我创建的。该代码在浏览器中运行良好,但在测试中失败。
下面是代码的作用:
Navigation组件的一部分。react-router实现所需的路由:/呈现HomePage,/modeler呈现ModelerPageModelerPage组件应该简单地呈现<h1>Home</h1> - -<h1>Home</h1>组件应该呈现 <h1>Modeler</h1> 以及一个初始化的建模器实例,它在 <h1>**.**之后由' modeler‘呈现到容器中--我指的是库bpmn.js (可以在这里找到:https://github.com/bpmn-io/bpmn-js)。下面是指向整个应用程序和工作演示的链接:https://codesandbox.io/s/jr89309w9
我的问题是,当我尝试在测试中加载建模器时,它会失败,并出现错误:
TypeError: Cannot read property 'appendChild' of null下面是我的modeler组件:
import React, { Component } from "react";
import BpmnJS from "bpmn-js/dist/bpmn-modeler.development.js";
import "bpmn-js/dist/assets/diagram-js.css";
import "bpmn-js/dist/assets/bpmn-font/css/bpmn-embedded.css";
class ModelerPage extends Component {
constructor(props) {
super(props);
this.viewer = new BpmnJS()
}
componentDidMount() {
const cont = document.querySelector('.container')
this.viewer.attachTo(".container");
}
componentWillUnmount() {
this.viewer.detach();
}
render() {
return (
<div>
<h1>Modeler</h1>
<div className="container"> </div>
</div>
);
}
}
export default ModelerPage;下面是我的测试:
import "../jest-setup";
import { mount } from "enzyme";
import React from "react";
import App from "./App";
it("renders an app with 2 routes, home and modeler page", async () => {
const wrapper = mount(
<MemoryRouter initialEntries={["/"]} initialIndex={0}>
<App />
</MemoryRouter>
);
const HomeTitle = <h1>Home</h1>;
const ModelerTitle = <h1>Modeler</h1>;
// Home title is rendered
expect(wrapper.contains(HomeTitle)).toEqual(true);
// When clicking the /modeler link
wrapper.find('[href="/modeler"]').simulate("click", { button: 0 });
// Modeler title is rendered
expect(wrapper.contains(ModelerTitle)).toEqual(true);
// Modeler container is rendered
expect(wrapper.html()).toMatch(/.bjs-container/);
});BpmJS库是在componentDidMount()中加载的,所以DOM应该已经准备好了,但是enzyme.mount()并没有真正重新创建DOM。
如何测试这类组件?
发布于 2018-07-20 21:55:59
解决这个问题很容易:
只需添加构造函数并实例化:React.createRef();,如下所示:
constructor(props) {
super(props);
this.myRef = React.createRef();
this.viewer = new BpmnJS()
}元素,而不是使用className,而是使用如下所示的ref={this.myRef}:
<div ref={this.myRef}> </div>这样就行了
https://stackoverflow.com/questions/51446742
复制相似问题