Skip to Content

测试

🌐 Testing

有很多选项可以测试 React 应用。如果你想测试 React Flow 应用,我们推荐使用 Cypress Playwright 。React Flow 需要测量节点以渲染边缘,并为此依赖于渲染的 DOM 元素。

🌐 There are plenty of options to test a React application. If you want to test a React Flow application, we recommend to use Cypress  or Playwright . React Flow needs to measure nodes in order to render edges and for that relies on rendering DOM elements.

使用 Cypress 或 Playwright

🌐 Using Cypress or Playwright

如果你正在使用 Cypress 或 Playwright,则不需要额外的设置。你可以参考 Cypress 入门指南 Playwright 入门指南 

🌐 If you are using Cypress or Playwright no additional setup is needed. You can refer to the getting started guide for Cypress here  and for Playwright here .

使用 Jest

🌐 Using Jest

如果你正在使用 Jest ,你需要模拟一些功能以便能够运行你的测试。你可以通过将此文件添加到你的项目中来实现。在 setupTests 文件中(或在 beforeEach 内部)调用 mockReactFlow() 将触发必要的覆盖。

🌐 If you are using Jest , you need to mock some features in order to be able to run your tests. You can do that by adding this file to your project. Calling mockReactFlow() in a setupTests file (or inside a beforeEach) will trigger the necessary overrides.

// 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,因为它在浏览器之外无法工作:

🌐 If you want to test mouse events with jest (for example inside your custom nodes), you need to disable d3-drag as it does not work outside of the browser:

<ReactFlow nodesDraggable={false} panOnDrag={false} {...rest} />
Last updated on