UNPKG

@gravity-ui/graph

Version:

Modern graph editor component

86 lines (85 loc) 3.25 kB
import { Component } from "../../../lib/Component"; import { GraphComponent } from "./index"; class TestGraphComponent extends GraphComponent { getEntityId() { return "test-id"; } subscribeGraphEvent(eventName, handler, options) { return this.onGraphEvent(eventName, handler, options); } subscribeRootEvent(eventName, handler, options) { return this.onRootEvent(eventName, handler, options); } } function createTestComponent(root) { const graphOff = jest.fn(); const graphOn = jest.fn().mockReturnValue(graphOff); const hitTestRemove = jest.fn(); const fakeGraph = { on: graphOn, hitTest: { remove: hitTestRemove, update: jest.fn(), }, // The rest of Graph API is not needed for these tests }; const rootEl = root ?? document.createElement("div"); const parent = new Component({}, undefined); parent.setContext({ graph: fakeGraph, root: rootEl, canvas: document.createElement("canvas"), ctx: document.createElement("canvas").getContext("2d"), ownerDocument: document, camera: { isRectVisible: () => true, }, constants: {}, colors: {}, graphCanvas: document.createElement("canvas"), layer: {}, affectsUsableRect: true, }); const component = new TestGraphComponent({}, parent); return { component, graphOn, graphOff, rootEl, hitTestRemove, }; } describe("GraphComponent event helpers", () => { it("subscribes to graph events via onGraphEvent and cleans up on unmount", () => { const { component, graphOn, graphOff } = createTestComponent(); const handler = jest.fn(); component.subscribeGraphEvent("camera-change", handler); expect(graphOn).toHaveBeenCalledTimes(1); expect(graphOn).toHaveBeenCalledWith("camera-change", handler, undefined); Component.unmount(component); expect(graphOff).toHaveBeenCalledTimes(1); }); it("subscribes to root DOM events via onRootEvent and cleans up on unmount", () => { const rootEl = document.createElement("div"); const addSpy = jest.spyOn(rootEl, "addEventListener"); const removeSpy = jest.spyOn(rootEl, "removeEventListener"); const { component } = createTestComponent(rootEl); const handler = jest.fn((event) => { // Use event to keep types happy expect(event).toBeInstanceOf(MouseEvent); }); component.subscribeRootEvent("click", handler); expect(addSpy).toHaveBeenCalledTimes(1); const [eventName, addListener] = addSpy.mock.calls[0]; expect(eventName).toBe("click"); expect(typeof addListener).toBe("function"); const event = new MouseEvent("click"); rootEl.dispatchEvent(event); expect(handler).toHaveBeenCalledTimes(1); Component.unmount(component); expect(removeSpy).toHaveBeenCalledTimes(1); const [removedEventName, removeListener] = removeSpy.mock.calls[0]; expect(removedEventName).toBe("click"); expect(typeof removeListener).toBe("function"); }); });