測試
有很多選項可以測試 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} />