跳到主要内容

测试

有很多选项可以用来测试 React 应用程序。如果您想测试 React Flow 应用程序,我们建议使用 Cypress或 Playwright。 React Flow 需要测量节点才能渲染边缘,而这依赖于渲染 DOM 元素。

使用 Cypress 或 Playwright

如果您使用 Cypress 或 Playwright,则无需额外设置。您可以参考此处的 Cypress 入门指南和此处的 Playwright 入门指南。

使用 Jest

如果您使用 Jest,则需要模拟某些功能才能运行测试。您可以通过将此文件添加到您的项目中来做到这一点。在 setupTests 文件中(或 beforeEach 中)调用 mockReactFlow() 将触发必要的覆盖。

// To make sure that the tests are working, it's important that you are using
// this implementation of ResizeObserver and DOMMatrixReadOnly
class ResizeObserver {
callback: globalThis.ResizeObserverCallback;

constructor(callback: globalThis.ResizeObserverCallback) {
this.callback = callback;
}

observe(target: Element) {
this.callback([{ target } as globalThis.ResizeObserverEntry], this);
}

unobserve() {}

disconnect() {}
}

class DOMMatrixReadOnly {
m22: number;
constructor(transform: string) {
const scale = transform?.match(/scale\(([1-9.])\)/)?.[1];
this.m22 = scale !== undefined ? +scale : 1;
}
}

// Only run the shim once when requested
let init = false;

export const mockReactFlow = () => {
if (init) return;
init = true;

global.ResizeObserver = ResizeObserver;

// @ts-ignore
global.DOMMatrixReadOnly = DOMMatrixReadOnly;

Object.defineProperties(global.HTMLElement.prototype, {
offsetHeight: {
get() {
return parseFloat(this.style.height) || 1;
},
},
offsetWidth: {
get() {
return parseFloat(this.style.width) || 1;
},
},
});

(global.SVGElement as any).prototype.getBBox = () => ({
x: 0,
y: 0,
width: 0,
height: 0,
});
};

如果您想使用 jest 测试鼠标事件(例如在自定义节点内),您需要禁用 d3-drag,因为它在浏览器之外不起作用:

<ReactFlow nodesDraggable={false} {...rest} />