テスト

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} />