Skip to content

Commit

Permalink
[test] Adds some mouse captor unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
jacomyal committed Oct 2, 2024
1 parent 6a7b7bd commit cb96f95
Showing 1 changed file with 82 additions and 0 deletions.
82 changes: 82 additions & 0 deletions packages/test/unit/sigma/mouse.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { userEvent } from "@vitest/browser/context";
import Graph from "graphology";
import { SerializedGraph } from "graphology-types";
import Sigma from "sigma";
import { createElement } from "sigma/utils";
import { afterEach, beforeEach, describe, expect, test } from "vitest";

interface SigmaTestContext {
sigma: Sigma;
graph: Graph;
container: HTMLDivElement;
}

function wait(timeout: number): Promise<void> {
return new Promise<void>((resolve) => setTimeout(resolve, timeout));
}

const STAGE_WIDTH = 200;
const STAGE_HEIGHT = 400;

const GRAPH: Pick<SerializedGraph, "nodes" | "edges"> = {
nodes: [
{ key: "n1", attributes: { x: 0, y: 0, size: 5 } },
{ key: "n2", attributes: { x: 50, y: 50, size: 5 } },
],
edges: [{ source: "n1", target: "n2" }],
};

beforeEach<SigmaTestContext>(async (context) => {
const graph = new Graph();
graph.import(GRAPH);
const container = createElement("div", { width: `${STAGE_WIDTH}px`, height: `${STAGE_HEIGHT}px` }) as HTMLDivElement;
document.body.append(container);

context.sigma = new Sigma(graph, container, {
zoomDuration: 30,
inertiaDuration: 30,
doubleClickZoomingDuration: 30,
});
context.graph = graph;
context.container = container;
});

afterEach<SigmaTestContext>(async ({ sigma }) => {
sigma.kill();
sigma.getContainer().remove();
});

describe("Sigma mouse management", () => {
test<SigmaTestContext>("it should zoom to the center when user double-clicks in the center", async ({
sigma,
container,
}) => {
const position = { x: STAGE_WIDTH / 2, y: STAGE_HEIGHT / 2 };

await userEvent.dblClick(container, { position });
await wait(sigma.getSetting("doubleClickZoomingDuration") * 1.1);

expect(sigma.getCamera().getState()).toEqual({
x: 0.5,
y: 0.5,
angle: 0,
ratio: 1 / sigma.getSetting("doubleClickZoomingRatio"),
});
});

test<SigmaTestContext>("it should zoom to the mouse position when user double-clicks in the center", async ({
sigma,
container,
}) => {
const position = { x: STAGE_WIDTH * 0.2, y: STAGE_HEIGHT * 0.7 };
const originalMouseGraphCoordinates = sigma.viewportToFramedGraph(position);

await userEvent.dblClick(container, { position });
await wait(sigma.getSetting("doubleClickZoomingDuration") * 1.1);

const newMouseGraphCoordinates = sigma.viewportToFramedGraph(position);
(["x", "y"] as const).forEach((key) =>
expect(newMouseGraphCoordinates[key]).toBeCloseTo(originalMouseGraphCoordinates[key], 6),
);
});
});

0 comments on commit cb96f95

Please sign in to comment.