Skip to content

Commit

Permalink
added unit tests to useRenderer
Browse files Browse the repository at this point in the history
  • Loading branch information
ctw-joao-luis committed Jan 10, 2025
1 parent 6675cdd commit 1c5f878
Showing 1 changed file with 71 additions and 0 deletions.
71 changes: 71 additions & 0 deletions packages/suite-base/src/panels/Plot/hooks/useRenderer.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/** @jest-environment jsdom */

// SPDX-FileCopyrightText: Copyright (C) 2023-2024 Bayerische Motoren Werke Aktiengesellschaft (BMW AG)<[email protected]>
// SPDX-License-Identifier: MPL-2.0

import { createTheme } from "@mui/material/styles";
import { renderHook } from "@testing-library/react";

import useRenderer from "./useRenderer";
import { OffscreenCanvasRenderer } from "../OffscreenCanvasRenderer";

jest.mock("../OffscreenCanvasRenderer", () => {
return {
OffscreenCanvasRenderer: jest.fn().mockImplementation(function (this: any) {
this.setSize = jest.fn();
this.destroy = jest.fn();
}),
};
});

Object.defineProperty(HTMLCanvasElement.prototype, "transferControlToOffscreen", {
value: jest.fn().mockImplementation(() => ({
width: 0,
height: 0,
})),
});

describe("useRenderer hook", () => {
it("should create a renderer and attach canvas to the canvasDiv", () => {
const canvasDiv = document.createElement("div");
const theme = createTheme();

const { result, unmount } = renderHook(() => useRenderer(canvasDiv, theme));

expect(result.current).toBeInstanceOf(OffscreenCanvasRenderer);
expect(canvasDiv.querySelector("canvas")).not.toBeNull();

//unmounting the hook
unmount();

//Checking that the renderer was destroyed and canvas removed
expect(canvasDiv.querySelector("canvas")).toBeNull();
});

it("should not create renderer if canvasDiv is undefined", () => {
const theme = createTheme();

const { result } = renderHook(() => useRenderer(ReactNull, theme));

expect(result.current).toBeUndefined();
});

it("should correctly reinitialize the renderer if canvasDiv changes", () => {
const canvasDiv1 = document.createElement("div");
const canvasDiv2 = document.createElement("div");
const theme = createTheme();

const { result, rerender } = renderHook(({ div }) => useRenderer(div, theme), {
initialProps: { div: canvasDiv1 },
});

const initialRenderer = result.current;

// Switching canvasDiv
rerender({ div: canvasDiv2 });

expect(result.current).not.toBe(initialRenderer);
expect(result.current).toBeInstanceOf(OffscreenCanvasRenderer);
expect(canvasDiv1.querySelector("canvas")).toBeNull();
});
});

0 comments on commit 1c5f878

Please sign in to comment.