Move more tests from Jest to Vitest (#34181)

* Move more tests from Jest to Vitest

* Iterate
This commit is contained in:
Michael Telatynski
2026-07-08 12:15:28 +00:00
committed by GitHub
parent d5932851cb
commit 67a20c57a3
22 changed files with 262 additions and 195 deletions
@@ -5,33 +5,35 @@
* Please see LICENSE files in the repository root for full details. * Please see LICENSE files in the repository root for full details.
*/ */
// @vitest-environment happy-dom
import { vi, describe, it, expect, beforeEach, afterEach } from "vitest";
import { type MatrixClient, type Room } from "matrix-js-sdk/src/matrix"; import { type MatrixClient, type Room } from "matrix-js-sdk/src/matrix";
import { mocked } from "jest-mock"; import { createTestClient, flushPromises, mkRoom } from "test-utils";
import RoomListActions from "../../../src/actions/RoomListActions"; import RoomListActions from "./RoomListActions";
import { DefaultTagID } from "../../../src/stores/room-list-v3/skip-list/tag"; import { DefaultTagID } from "../stores/room-list-v3/skip-list/tag";
import Modal from "../../../src/Modal"; import Modal from "../Modal";
import * as Rooms from "../../../src/Rooms"; import * as Rooms from "../Rooms";
import { createTestClient, flushPromises, mkRoom } from "../../test-utils";
jest.mock("../../../src/Modal"); vi.mock("../Modal");
jest.mock("../../../src/Rooms"); vi.mock("../Rooms");
describe("RoomListActions", () => { describe("RoomListActions", () => {
const ROOM_ID = "!room:example.org"; const ROOM_ID = "!room:example.org";
let client: MatrixClient; let client: MatrixClient;
let room: Room; let room: Room;
const dispatch = jest.fn(); const dispatch = vi.fn();
beforeEach(() => { beforeEach(() => {
client = createTestClient(); client = createTestClient();
room = mkRoom(client, ROOM_ID); room = mkRoom(client, ROOM_ID);
mocked(Rooms.guessAndSetDMRoom).mockResolvedValue(undefined); vi.mocked(Rooms.guessAndSetDMRoom).mockResolvedValue(undefined);
}); });
afterEach(() => { afterEach(() => {
jest.clearAllMocks(); vi.clearAllMocks();
}); });
describe("tagRoom", () => { describe("tagRoom", () => {
@@ -81,7 +83,7 @@ describe("RoomListActions", () => {
it("opens an ErrorDialog and swallows the error if guessAndSetDMRoom rejects", async () => { it("opens an ErrorDialog and swallows the error if guessAndSetDMRoom rejects", async () => {
const error = new Error("DM tag error"); const error = new Error("DM tag error");
mocked(Rooms.guessAndSetDMRoom).mockRejectedValue(error); vi.mocked(Rooms.guessAndSetDMRoom).mockRejectedValue(error);
await invokeTagRoom(undefined, DefaultTagID.DM); await invokeTagRoom(undefined, DefaultTagID.DM);
@@ -140,7 +142,7 @@ describe("RoomListActions", () => {
it("shows an ErrorDialog but still dispatches success when deleteRoomTag fails", async () => { it("shows an ErrorDialog but still dispatches success when deleteRoomTag fails", async () => {
const error = new Error("delete failed"); const error = new Error("delete failed");
jest.spyOn(client, "deleteRoomTag").mockRejectedValue(error); vi.spyOn(client, "deleteRoomTag").mockRejectedValue(error);
await invokeTagRoom(DefaultTagID.Favourite, DefaultTagID.LowPriority); await invokeTagRoom(DefaultTagID.Favourite, DefaultTagID.LowPriority);
@@ -156,7 +158,7 @@ describe("RoomListActions", () => {
it("shows an ErrorDialog and dispatches failure when setRoomTag fails", async () => { it("shows an ErrorDialog and dispatches failure when setRoomTag fails", async () => {
const error = new Error("set failed"); const error = new Error("set failed");
jest.spyOn(client, "setRoomTag").mockRejectedValue(error); vi.spyOn(client, "setRoomTag").mockRejectedValue(error);
await invokeTagRoom(DefaultTagID.Favourite, DefaultTagID.LowPriority); await invokeTagRoom(DefaultTagID.Favourite, DefaultTagID.LowPriority);
@@ -104,21 +104,16 @@ describe("MessageComposerUrlPreview", () => {
(text) => text === "show-fake-preview", (text) => text === "show-fake-preview",
() => <strong>Fake preview</strong>, () => <strong>Fake preview</strong>,
); );
const { container, getByText, rerender } = wrapComponent( const { container, getByText, queryByText, rerender } = wrapComponent(
<MessageComposerUrlPreviewWrapper content="show-fake-preview" moduleApi={modApi} />, <MessageComposerUrlPreviewWrapper content="show-fake-preview" moduleApi={modApi} />,
); );
await waitFor( await waitFor(() => {
() => { expect(getByText("Fake preview")).toBeDefined();
expect(getByText("Fake preview")).toBeDefined(); });
},
{ timeout: DEBOUNCE_REQUEST_TIMEOUT_MS },
);
rerender(<MessageComposerUrlPreviewWrapper content="other-text" moduleApi={modApi} />); rerender(<MessageComposerUrlPreviewWrapper content="other-text" moduleApi={modApi} />);
await waitFor( await waitFor(() => {
() => { expect(queryByText("Fake preview")).toBeNull();
expect(container).toMatchInlineSnapshot(`<div />`); });
}, expect(container).toMatchInlineSnapshot(`<div />`);
{ timeout: DEBOUNCE_REQUEST_TIMEOUT_MS },
);
}); });
}); });
@@ -6,12 +6,14 @@ SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Com
Please see LICENSE files in the repository root for full details. Please see LICENSE files in the repository root for full details.
*/ */
import { type MatrixClient } from "matrix-js-sdk/src/matrix"; // @vitest-environment happy-dom
import { SDKContextClass } from "../../../src/contexts/SDKContextClass"; import { describe, it, expect, beforeAll, beforeEach } from "vitest";
import { UserProfilesStore } from "../../../src/stores/UserProfilesStore"; import { type MatrixClient } from "matrix-js-sdk/src/matrix";
import { createTestClient } from "../../test-utils"; import { createTestClient, TestSDKContext } from "test-utils";
import { TestSDKContext } from "../TestSDKContext.ts";
import { SDKContextClass } from "./SDKContextClass";
import { UserProfilesStore } from "../stores/UserProfilesStore";
describe("SDKContextClass", () => { describe("SDKContextClass", () => {
let sdkContext: TestSDKContext; let sdkContext: TestSDKContext;
@@ -6,10 +6,12 @@ SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Com
Please see LICENSE files in the repository root for full details. Please see LICENSE files in the repository root for full details.
*/ */
import React from "react"; // @vitest-environment happy-dom
import { render, screen } from "jest-matrix-react";
import { mocked } from "jest-mock"; import { vi, describe, it, expect, beforeAll, beforeEach, afterEach } from "vitest";
import { render } from "test-utils-rtl";
import { EventType, type MatrixClient, MatrixEvent, MsgType, Room, type RoomMember } from "matrix-js-sdk/src/matrix"; import { EventType, type MatrixClient, MatrixEvent, MsgType, Room, type RoomMember } from "matrix-js-sdk/src/matrix";
import { createTestClient, mkEvent, withClientContextRenderOptions } from "test-utils";
import { import {
JSONEventFactory, JSONEventFactory,
@@ -17,14 +19,12 @@ import {
pickFactory, pickFactory,
renderTile, renderTile,
RoomCreateEventFactory, RoomCreateEventFactory,
} from "../../../src/events/EventTileFactory"; } from "./EventTileFactory";
import SettingsStore from "../../../src/settings/SettingsStore"; import SettingsStore from "../settings/SettingsStore";
import { createTestClient, mkEvent } from "../../test-utils"; import { TimelineRenderingType } from "../contexts/RoomContext";
import { TimelineRenderingType } from "../../../src/contexts/RoomContext"; import { ModuleApi } from "../modules/Api";
import { ModuleApi } from "../../../src/modules/Api"; import DMRoomMap from "../utils/DMRoomMap";
import MatrixClientContext from "../../../src/contexts/MatrixClientContext"; import { MatrixClientPeg } from "../MatrixClientPeg";
import DMRoomMap from "../../../src/utils/DMRoomMap";
import { MatrixClientPeg } from "../../../src/MatrixClientPeg";
const roomId = "!room:example.com"; const roomId = "!room:example.com";
@@ -70,7 +70,7 @@ describe("pickFactory", () => {
client = createTestClient(); client = createTestClient();
room = new Room(roomId, client, client.getSafeUserId()); room = new Room(roomId, client, client.getSafeUserId());
mocked(client.getRoom).mockImplementation((getRoomId: string): Room | null => { vi.mocked(client.getRoom).mockImplementation((getRoomId?: string): Room | null => {
if (getRoomId === room.roomId) return room; if (getRoomId === room.roomId) return room;
return null; return null;
}); });
@@ -159,7 +159,7 @@ describe("pickFactory", () => {
describe("when not showing hidden events", () => { describe("when not showing hidden events", () => {
describe("without dynamic predecessor support", () => { describe("without dynamic predecessor support", () => {
beforeEach(() => { beforeEach(() => {
jest.spyOn(SettingsStore, "getValue").mockReset(); vi.spyOn(SettingsStore, "getValue").mockReset();
}); });
it("should return undefined for a room without predecessor", () => { it("should return undefined for a room without predecessor", () => {
@@ -195,7 +195,7 @@ describe("pickFactory", () => {
describe("with dynamic predecessor support", () => { describe("with dynamic predecessor support", () => {
beforeEach(() => { beforeEach(() => {
jest.spyOn(SettingsStore, "getValue") vi.spyOn(SettingsStore, "getValue")
.mockReset() .mockReset()
.mockImplementation((settingName) => settingName === "feature_dynamic_room_predecessors"); .mockImplementation((settingName) => settingName === "feature_dynamic_room_predecessors");
}); });
@@ -261,11 +261,11 @@ describe("renderTile", () => {
afterEach(() => { afterEach(() => {
ModuleApi.instance.customComponents.renderMessage = originalRenderMessage; ModuleApi.instance.customComponents.renderMessage = originalRenderMessage;
jest.restoreAllMocks(); vi.restoreAllMocks();
}); });
it("rendering a tile defers to the module API", () => { it("rendering a tile defers to the module API", () => {
ModuleApi.instance.customComponents.renderMessage = jest.fn(); ModuleApi.instance.customComponents.renderMessage = vi.fn();
const messageEvent = mkEvent({ const messageEvent = mkEvent({
event: true, event: true,
@@ -288,7 +288,7 @@ describe("renderTile", () => {
}); });
it("rendering a tile for a message of unknown type defers to the module API", () => { it("rendering a tile for a message of unknown type defers to the module API", () => {
ModuleApi.instance.customComponents.renderMessage = jest.fn(); ModuleApi.instance.customComponents.renderMessage = vi.fn();
const messageEvent = mkEvent({ const messageEvent = mkEvent({
event: true, event: true,
@@ -310,11 +310,11 @@ describe("renderTile", () => {
it("renders an incoming key verification request with the wrapped shared-components view", () => { it("renders an incoming key verification request with the wrapped shared-components view", () => {
const sender = "@alice:example.com"; const sender = "@alice:example.com";
const room = new Room(roomId, client, client.getSafeUserId()); const room = new Room(roomId, client, client.getSafeUserId());
jest.spyOn(room, "getMember").mockImplementation((userId: string) => { vi.spyOn(room, "getMember").mockImplementation((userId: string) => {
if (userId === sender) return { name: "Alice" } as RoomMember; if (userId === sender) return { name: "Alice" } as RoomMember;
return null; return null;
}); });
mocked(client.getRoom).mockReturnValue(room); vi.mocked(client.getRoom).mockReturnValue(room);
const verificationRequestEvent = makeVerificationRequestEvent({ const verificationRequestEvent = makeVerificationRequestEvent({
sender, sender,
@@ -327,21 +327,20 @@ describe("renderTile", () => {
client, client,
); );
if (!tile) throw new Error("Expected a key verification request tile"); if (!tile) throw new Error("Expected a key verification request tile");
const { getByText } = render(tile, withClientContextRenderOptions(client));
render(React.createElement(MatrixClientContext.Provider, { value: client }, tile)); expect(getByText("Alice wants to verify")).toBeVisible();
expect(getByText("Alice (@alice:example.com)")).toBeVisible();
expect(screen.getByText("Alice wants to verify")).toBeInTheDocument();
expect(screen.getByText("Alice (@alice:example.com)")).toBeInTheDocument();
}); });
it("renders an outgoing key verification request with the wrapped shared-components view", () => { it("renders an outgoing key verification request with the wrapped shared-components view", () => {
const recipient = "@alice:example.com"; const recipient = "@alice:example.com";
const room = new Room(roomId, client, client.getSafeUserId()); const room = new Room(roomId, client, client.getSafeUserId());
jest.spyOn(room, "getMember").mockImplementation((userId: string) => { vi.spyOn(room, "getMember").mockImplementation((userId: string) => {
if (userId === recipient) return { name: "Alice" } as RoomMember; if (userId === recipient) return { name: "Alice" } as RoomMember;
return null; return null;
}); });
mocked(client.getRoom).mockReturnValue(room); vi.mocked(client.getRoom).mockReturnValue(room);
const verificationRequestEvent = makeVerificationRequestEvent({ const verificationRequestEvent = makeVerificationRequestEvent({
sender: client.getUserId()!, sender: client.getUserId()!,
@@ -354,15 +353,14 @@ describe("renderTile", () => {
client, client,
); );
if (!tile) throw new Error("Expected a key verification request tile"); if (!tile) throw new Error("Expected a key verification request tile");
const { getByText } = render(tile, withClientContextRenderOptions(client));
render(React.createElement(MatrixClientContext.Provider, { value: client }, tile)); expect(getByText("You sent a verification request")).toBeInTheDocument();
expect(getByText("Alice (@alice:example.com)")).toBeInTheDocument();
expect(screen.getByText("You sent a verification request")).toBeInTheDocument();
expect(screen.getByText("Alice (@alice:example.com)")).toBeInTheDocument();
}); });
it("throws when a key verification request tile is rendered without a client context", () => { it("throws when a key verification request tile is rendered without a client context", () => {
jest.spyOn(console, "error").mockImplementation(() => {}); vi.spyOn(console, "error").mockImplementation(() => {});
const verificationRequestEvent = makeVerificationRequestEvent({ const verificationRequestEvent = makeVerificationRequestEvent({
sender: client.getUserId()!, sender: client.getUserId()!,
to: "@alice:example.com", to: "@alice:example.com",
@@ -393,11 +391,11 @@ describe("renderTile", () => {
}, },
}), }),
]); ]);
mocked(client.getRoom).mockReturnValue(room); vi.mocked(client.getRoom).mockReturnValue(room);
jest.spyOn(DMRoomMap, "shared").mockReturnValue({ vi.spyOn(DMRoomMap, "shared").mockReturnValue({
getUserIdForRoomId: jest.fn().mockReturnValue(null), getUserIdForRoomId: vi.fn().mockReturnValue(null),
} as unknown as DMRoomMap); } as unknown as DMRoomMap);
jest.spyOn(MatrixClientPeg, "safeGet").mockReturnValue(client); vi.spyOn(MatrixClientPeg, "safeGet").mockReturnValue(client);
const roomAvatarEvent = makeRoomAvatarEvent(); const roomAvatarEvent = makeRoomAvatarEvent();
roomAvatarEvent.sender = { name: "Alice" } as MatrixEvent["sender"]; roomAvatarEvent.sender = { name: "Alice" } as MatrixEvent["sender"];
@@ -407,10 +405,9 @@ describe("renderTile", () => {
client, client,
); );
if (!tile) throw new Error("Expected a room avatar event tile"); if (!tile) throw new Error("Expected a room avatar event tile");
const { getByText, getByRole } = render(tile, withClientContextRenderOptions(client));
render(React.createElement(MatrixClientContext.Provider, { value: client }, tile)); expect(getByText("Alice changed the room avatar to")).toBeInTheDocument();
expect(getByRole("button", { name: "Alice changed the avatar for General" })).toBeInTheDocument();
expect(screen.getByText("Alice changed the room avatar to")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Alice changed the avatar for General" })).toBeInTheDocument();
}); });
}); });
@@ -6,22 +6,25 @@ SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Com
Please see LICENSE files in the repository root for full details. Please see LICENSE files in the repository root for full details.
*/ */
import { EventType, MatrixEvent, MsgType } from "matrix-js-sdk/src/matrix"; // @vitest-environment happy-dom
import { getForwardableEvent } from "../../../../src/events"; import { vi, describe, it, expect } from "vitest";
import { EventType, MatrixEvent, MsgType } from "matrix-js-sdk/src/matrix";
import { import {
getMockClientWithEventEmitter, getMockClientWithEventEmitter,
makeBeaconEvent, makeBeaconEvent,
makeBeaconInfoEvent, makeBeaconInfoEvent,
makePollStartEvent, makePollStartEvent,
makeRoomWithBeacons, makeRoomWithBeacons,
} from "../../../test-utils"; } from "test-utils";
import { getForwardableEvent } from "./getForwardableEvent";
describe("getForwardableEvent()", () => { describe("getForwardableEvent()", () => {
const userId = "@alice:server.org"; const userId = "@alice:server.org";
const roomId = "!room:server.org"; const roomId = "!room:server.org";
const client = getMockClientWithEventEmitter({ const client = getMockClientWithEventEmitter({
getRoom: jest.fn(), getRoom: vi.fn(),
}); });
it("returns the event for a room message", () => { it("returns the event for a room message", () => {
@@ -6,22 +6,25 @@ SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Com
Please see LICENSE files in the repository root for full details. Please see LICENSE files in the repository root for full details.
*/ */
import { EventType, MatrixEvent, MsgType } from "matrix-js-sdk/src/matrix"; // @vitest-environment happy-dom
import { getShareableLocationEvent } from "../../../../src/events"; import { vi, describe, it, expect } from "vitest";
import { EventType, MatrixEvent, MsgType } from "matrix-js-sdk/src/matrix";
import { import {
getMockClientWithEventEmitter, getMockClientWithEventEmitter,
makeBeaconEvent, makeBeaconEvent,
makeBeaconInfoEvent, makeBeaconInfoEvent,
makeLocationEvent, makeLocationEvent,
makeRoomWithBeacons, makeRoomWithBeacons,
} from "../../../test-utils"; } from "test-utils";
import { getShareableLocationEvent } from "./getShareableLocationEvent";
describe("getShareableLocationEvent()", () => { describe("getShareableLocationEvent()", () => {
const userId = "@alice:server.org"; const userId = "@alice:server.org";
const roomId = "!room:server.org"; const roomId = "!room:server.org";
const client = getMockClientWithEventEmitter({ const client = getMockClientWithEventEmitter({
getRoom: jest.fn(), getRoom: vi.fn(),
}); });
it("returns null for a non-location event", () => { it("returns null for a non-location event", () => {
@@ -6,14 +6,17 @@ SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Com
Please see LICENSE files in the repository root for full details. Please see LICENSE files in the repository root for full details.
*/ */
import { renderHook } from "jest-matrix-react"; // @vitest-environment happy-dom
import { type MatrixClient, NotificationCountType, Room } from "matrix-js-sdk/src/matrix";
import { useRoomThreadNotifications } from "../../../../src/hooks/room/useRoomThreadNotifications"; import { describe, it, expect, beforeEach } from "vitest";
import { stubClient } from "../../../test-utils"; import { renderHook } from "test-utils-rtl";
import { MatrixClientPeg } from "../../../../src/MatrixClientPeg"; import { type MatrixClient, NotificationCountType, Room } from "matrix-js-sdk/src/matrix";
import { NotificationLevel } from "../../../../src/stores/notifications/NotificationLevel"; import { stubClient } from "test-utils";
import { populateThread } from "../../../test-utils/threads"; import { populateThread } from "test-utils/threads";
import { useRoomThreadNotifications } from "../../hooks/room/useRoomThreadNotifications";
import { MatrixClientPeg } from "../../MatrixClientPeg";
import { NotificationLevel } from "../../stores/notifications/NotificationLevel";
function render(room: Room) { function render(room: Room) {
return renderHook(() => useRoomThreadNotifications(room)); return renderHook(() => useRoomThreadNotifications(room));
@@ -6,13 +6,16 @@ SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Com
Please see LICENSE files in the repository root for full details. Please see LICENSE files in the repository root for full details.
*/ */
// @vitest-environment happy-dom
import { describe, it, expect } from "vitest";
import React from "react"; import React from "react";
import { Room } from "matrix-js-sdk/src/matrix"; import { Room } from "matrix-js-sdk/src/matrix";
import { act, render, screen } from "jest-matrix-react"; import { act, render, screen } from "test-utils-rtl";
import { mkEvent, stubClient } from "test-utils";
import { useTopic } from "../../src/hooks/room/useTopic"; import { useTopic } from "./useTopic";
import { mkEvent, stubClient } from "../test-utils"; import { MatrixClientPeg } from "../../MatrixClientPeg";
import { MatrixClientPeg } from "../../src/MatrixClientPeg";
describe("useTopic", () => { describe("useTopic", () => {
it("should display the room topic", () => { it("should display the room topic", () => {
@@ -5,14 +5,17 @@ SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Com
Please see LICENSE files in the repository root for full details. Please see LICENSE files in the repository root for full details.
*/ */
import { act, renderHook, waitFor } from "jest-matrix-react"; // @vitest-environment happy-dom
import { JoinRule, MatrixEvent, type MatrixClient, type Room } from "matrix-js-sdk/src/matrix";
import { useMediaVisible } from "../../../src/hooks/useMediaVisible"; import { vi, describe, it, expect, beforeEach, afterEach } from "vitest";
import { createTestClient, mkStubRoom, withClientContextRenderOptions } from "../../test-utils"; import { act, renderHook, waitFor } from "test-utils-rtl";
import { type MediaPreviewConfig, MediaPreviewValue } from "../../../src/@types/media_preview"; import { JoinRule, MatrixEvent, type MatrixClient, type Room } from "matrix-js-sdk/src/matrix";
import MediaPreviewConfigController from "../../../src/settings/controllers/MediaPreviewConfigController"; import { createTestClient, mkStubRoom, withClientContextRenderOptions } from "test-utils";
import SettingsStore from "../../../src/settings/SettingsStore";
import { useMediaVisible } from "./useMediaVisible";
import { type MediaPreviewConfig, MediaPreviewValue } from "../@types/media_preview";
import MediaPreviewConfigController from "../settings/controllers/MediaPreviewConfigController";
import SettingsStore from "../settings/SettingsStore";
const EVENT_ID = "$fibble:example.org"; const EVENT_ID = "$fibble:example.org";
const ROOM_ID = "!foobar:example.org"; const ROOM_ID = "!foobar:example.org";
@@ -43,9 +46,9 @@ describe("useMediaVisible", () => {
beforeEach(() => { beforeEach(() => {
matrixClient = createTestClient(); matrixClient = createTestClient();
room = mkStubRoom(ROOM_ID, undefined, matrixClient); room = mkStubRoom(ROOM_ID, undefined, matrixClient);
matrixClient.getRoom = jest.fn().mockReturnValue(room); matrixClient.getRoom = vi.fn().mockReturnValue(room);
const origFn = SettingsStore.getValue; const origFn = SettingsStore.getValue;
jest.spyOn(SettingsStore, "getValue").mockImplementation((setting, ...args) => { vi.spyOn(SettingsStore, "getValue").mockImplementation((setting, ...args) => {
if (setting === "mediaPreviewConfig") { if (setting === "mediaPreviewConfig") {
return mediaPreviewConfig; return mediaPreviewConfig;
} }
@@ -54,7 +57,7 @@ describe("useMediaVisible", () => {
}); });
afterEach(() => { afterEach(() => {
jest.restoreAllMocks(); vi.restoreAllMocks();
}); });
it("should display media by default", () => { it("should display media by default", () => {
@@ -86,7 +89,7 @@ describe("useMediaVisible", () => {
"should display media when media previews are Private and the join rule is %s", "should display media when media previews are Private and the join rule is %s",
(rule) => { (rule) => {
mediaPreviewConfig.media_previews = MediaPreviewValue.Private; mediaPreviewConfig.media_previews = MediaPreviewValue.Private;
room.currentState.getJoinRule = jest.fn().mockReturnValue(rule); room.currentState.getJoinRule = vi.fn().mockReturnValue(rule);
const [visible] = render().result.current; const [visible] = render().result.current;
expect(visible).toEqual(true); expect(visible).toEqual(true);
}, },
@@ -96,7 +99,7 @@ describe("useMediaVisible", () => {
"should hide media when media previews are Private and the join rule is %s", "should hide media when media previews are Private and the join rule is %s",
(rule) => { (rule) => {
mediaPreviewConfig.media_previews = MediaPreviewValue.Private; mediaPreviewConfig.media_previews = MediaPreviewValue.Private;
room.currentState.getJoinRule = jest.fn().mockReturnValue(rule); room.currentState.getJoinRule = vi.fn().mockReturnValue(rule);
const [visible] = render().result.current; const [visible] = render().result.current;
expect(visible).toEqual(false); expect(visible).toEqual(false);
}, },
@@ -6,18 +6,22 @@ SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Com
Please see LICENSE files in the repository root for full details. Please see LICENSE files in the repository root for full details.
*/ */
import { waitFor, renderHook } from "jest-matrix-react"; // @vitest-environment happy-dom
import { type IPushRules, type MatrixClient, PushRuleKind, RuleId } from "matrix-js-sdk/src/matrix";
import { useNotificationSettings } from "../../../src/hooks/useNotificationSettings"; import { vi, describe, it, expect, beforeEach } from "vitest";
import { MatrixClientPeg } from "../../../src/MatrixClientPeg"; import { waitFor, renderHook } from "test-utils-rtl";
import { type IPushRules, type MatrixClient, PushRuleKind, RuleId } from "matrix-js-sdk/src/matrix";
import { stubClient } from "test-utils";
import { useNotificationSettings } from "./useNotificationSettings";
import { MatrixClientPeg } from "../MatrixClientPeg";
import { import {
DefaultNotificationSettings, DefaultNotificationSettings,
type NotificationSettings, type NotificationSettings,
} from "../../../src/models/notificationsettings/NotificationSettings"; } from "../models/notificationsettings/NotificationSettings";
import { StandardActions } from "../../../src/notifications/StandardActions"; import { StandardActions } from "../notifications/StandardActions";
import { RoomNotifState } from "../../../src/RoomNotifs"; import { RoomNotifState } from "../RoomNotifs";
import { stubClient } from "../../test-utils"; import samplePushRules from "../../test/unit-tests/models/notificationsettings/pushrules_sample.json" with { type: "json" };
const expectedModel: NotificationSettings = { const expectedModel: NotificationSettings = {
globalMute: false, globalMute: false,
@@ -42,20 +46,16 @@ const expectedModel: NotificationSettings = {
}, },
keywords: ["justjann3", "justj4nn3", "justj4nne", "Janne", "J4nne", "Jann3", "jann3", "j4nne", "janne"], keywords: ["justjann3", "justj4nn3", "justj4nne", "Janne", "J4nne", "Jann3", "jann3", "j4nne", "janne"],
}; };
const pushRules = samplePushRules as IPushRules;
describe("useNotificationSettings", () => { describe("useNotificationSettings", () => {
let cli: MatrixClient; let cli: MatrixClient;
let pushRules: IPushRules;
beforeAll(async () => {
pushRules = (await import("../models/notificationsettings/pushrules_sample.json")) as IPushRules;
});
beforeEach(() => { beforeEach(() => {
stubClient(); stubClient();
cli = MatrixClientPeg.safeGet(); cli = MatrixClientPeg.safeGet();
cli.getPushRules = jest.fn(cli.getPushRules).mockResolvedValue(pushRules); cli.getPushRules = vi.fn(cli.getPushRules).mockResolvedValue(pushRules);
cli.supportsIntentionalMentions = jest.fn(cli.supportsIntentionalMentions).mockReturnValue(false); cli.supportsIntentionalMentions = vi.fn(cli.supportsIntentionalMentions).mockReturnValue(false);
}); });
it("correctly parses model", async () => { it("correctly parses model", async () => {
@@ -66,13 +66,13 @@ describe("useNotificationSettings", () => {
}); });
it("correctly generates change calls", async () => { it("correctly generates change calls", async () => {
const addPushRule = jest.fn(cli.addPushRule); const addPushRule = vi.fn(cli.addPushRule);
cli.addPushRule = addPushRule; cli.addPushRule = addPushRule;
const deletePushRule = jest.fn(cli.deletePushRule); const deletePushRule = vi.fn(cli.deletePushRule);
cli.deletePushRule = deletePushRule; cli.deletePushRule = deletePushRule;
const setPushRuleEnabled = jest.fn(cli.setPushRuleEnabled); const setPushRuleEnabled = vi.fn(cli.setPushRuleEnabled);
cli.setPushRuleEnabled = setPushRuleEnabled; cli.setPushRuleEnabled = setPushRuleEnabled;
const setPushRuleActions = jest.fn(cli.setPushRuleActions); const setPushRuleActions = vi.fn(cli.setPushRuleActions);
cli.setPushRuleActions = setPushRuleActions; cli.setPushRuleActions = setPushRuleActions;
const { result } = renderHook(() => useNotificationSettings(cli)); const { result } = renderHook(() => useNotificationSettings(cli));
@@ -6,12 +6,15 @@ SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Com
Please see LICENSE files in the repository root for full details. Please see LICENSE files in the repository root for full details.
*/ */
import { waitFor, renderHook, act } from "jest-matrix-react"; // @vitest-environment happy-dom
import { type EmptyObject, type MatrixClient } from "matrix-js-sdk/src/matrix";
import { useProfileInfo } from "../../../src/hooks/useProfileInfo"; import { describe, it, expect, beforeEach } from "vitest";
import { MatrixClientPeg } from "../../../src/MatrixClientPeg"; import { waitFor, renderHook, act } from "test-utils-rtl";
import { stubClient } from "../../test-utils/test-utils"; import { type EmptyObject, type MatrixClient } from "matrix-js-sdk/src/matrix";
import { stubClient } from "test-utils/test-utils";
import { useProfileInfo } from "./useProfileInfo";
import { MatrixClientPeg } from "../MatrixClientPeg";
function render() { function render() {
return renderHook(() => useProfileInfo()); return renderHook(() => useProfileInfo());
@@ -6,12 +6,15 @@ SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Com
Please see LICENSE files in the repository root for full details. Please see LICENSE files in the repository root for full details.
*/ */
import { waitFor, renderHook, act } from "jest-matrix-react"; // @vitest-environment happy-dom
import { type IRoomDirectoryOptions, type MatrixClient } from "matrix-js-sdk/src/matrix";
import { usePublicRoomDirectory } from "../../../src/hooks/usePublicRoomDirectory"; import { describe, it, expect, beforeEach } from "vitest";
import { MatrixClientPeg } from "../../../src/MatrixClientPeg"; import { waitFor, renderHook, act } from "test-utils-rtl";
import { stubClient } from "../../test-utils/test-utils"; import { type IRoomDirectoryOptions, type MatrixClient } from "matrix-js-sdk/src/matrix";
import { stubClient } from "test-utils/test-utils";
import { usePublicRoomDirectory } from "./usePublicRoomDirectory";
import { MatrixClientPeg } from "../MatrixClientPeg";
function render() { function render() {
return renderHook(() => usePublicRoomDirectory()); return renderHook(() => usePublicRoomDirectory());
@@ -5,10 +5,10 @@ SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Com
Please see LICENSE files in the repository root for full details. Please see LICENSE files in the repository root for full details.
*/ */
import { renderHook, waitFor } from "jest-matrix-react"; // @vitest-environment happy-dom
import React from "react";
import { PlatformCallType, useRoomCall } from "../../../src/hooks/room/useRoomCall"; import { vi, describe, it, expect, beforeEach, afterEach } from "vitest";
import { renderHook, waitFor } from "test-utils-rtl";
import { import {
getMockClientWithEventEmitter, getMockClientWithEventEmitter,
mkRoom, mkRoom,
@@ -17,13 +17,14 @@ import {
mockClientMethodsUser, mockClientMethodsUser,
MockEventEmitter, MockEventEmitter,
setupAsyncStoreWithClient, setupAsyncStoreWithClient,
} from "../../test-utils"; withContexts,
import { ScopedRoomContextProvider } from "../../../src/contexts/ScopedRoomContext"; } from "test-utils";
import RoomContext, { type RoomContextType } from "../../../src/contexts/RoomContext";
import { MatrixClientContextProvider } from "../../../src/components/structures/MatrixClientContextProvider"; import { PlatformCallType, useRoomCall } from "./room/useRoomCall";
import type LegacyCallHandler from "../../../src/LegacyCallHandler"; import RoomContext, { type RoomContextType } from "../contexts/RoomContext";
import { CallStore } from "../../../src/stores/CallStore"; import type LegacyCallHandler from "../LegacyCallHandler";
import { SDKContextClass } from "../../../src/contexts/SDKContextClass"; import { CallStore } from "../stores/CallStore";
import { SDKContextClass } from "../contexts/SDKContextClass";
describe("useRoomCall", () => { describe("useRoomCall", () => {
const client = getMockClientWithEventEmitter({ const client = getMockClientWithEventEmitter({
@@ -31,16 +32,16 @@ describe("useRoomCall", () => {
...mockClientMethodsServer(), ...mockClientMethodsServer(),
...mockClientMethodsRooms(), ...mockClientMethodsRooms(),
matrixRTC: new MockEventEmitter(), matrixRTC: new MockEventEmitter(),
_unstable_getRTCTransports: jest.fn().mockResolvedValue([]), _unstable_getRTCTransports: vi.fn().mockResolvedValue([]),
getCrypto: () => null, getCrypto: () => null,
}); });
const room = mkRoom(client, "!test-room"); const room = mkRoom(client, "!test-room");
// Create a stable room context for this test // Create a stable room context for this test
const mockRoomViewStore = { const mockRoomViewStore = {
isViewingCall: jest.fn().mockReturnValue(false), isViewingCall: vi.fn().mockReturnValue(false),
on: jest.fn(), on: vi.fn(),
off: jest.fn(), off: vi.fn(),
emit: jest.fn(), emit: vi.fn(),
}; };
const roomContext = { const roomContext = {
@@ -51,30 +52,24 @@ describe("useRoomCall", () => {
beforeEach(() => { beforeEach(() => {
const callHandler = { const callHandler = {
getCallForRoom: jest.fn().mockReturnValue(null), getCallForRoom: vi.fn().mockReturnValue(null),
isCallSidebarShown: jest.fn().mockReturnValue(true), isCallSidebarShown: vi.fn().mockReturnValue(true),
addListener: jest.fn(), addListener: vi.fn(),
removeListener: jest.fn(), removeListener: vi.fn(),
on: jest.fn(), on: vi.fn(),
off: jest.fn(), off: vi.fn(),
}; };
jest.spyOn(SDKContextClass.instance, "legacyCallHandler", "get").mockReturnValue( vi.spyOn(SDKContextClass.instance, "legacyCallHandler", "get").mockReturnValue(
callHandler as unknown as LegacyCallHandler, callHandler as unknown as LegacyCallHandler,
); );
}); });
afterEach(() => { afterEach(() => {
jest.restoreAllMocks(); vi.restoreAllMocks();
}); });
function render() { function render() {
return renderHook(() => useRoomCall(room), { return renderHook(() => useRoomCall(room), withContexts({ matrixClient: client, roomContext }));
wrapper: ({ children }) => (
<MatrixClientContextProvider client={client}>
<ScopedRoomContextProvider {...roomContext}>{children}</ScopedRoomContextProvider>
</MatrixClientContextProvider>
),
});
} }
describe("Element Call focus detection", () => { describe("Element Call focus detection", () => {
@@ -6,13 +6,16 @@ SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Com
Please see LICENSE files in the repository root for full details. Please see LICENSE files in the repository root for full details.
*/ */
import { waitFor, renderHook, act } from "jest-matrix-react"; // @vitest-environment happy-dom
import { describe, it, expect, beforeEach } from "vitest";
import { waitFor, renderHook, act } from "test-utils-rtl";
import { type MatrixClient, MatrixEvent, Room } from "matrix-js-sdk/src/matrix"; import { type MatrixClient, MatrixEvent, Room } from "matrix-js-sdk/src/matrix";
import { KnownMembership } from "matrix-js-sdk/src/types"; import { KnownMembership } from "matrix-js-sdk/src/types";
import { stubClient } from "test-utils";
import { MatrixClientPeg } from "../../../src/MatrixClientPeg"; import { MatrixClientPeg } from "../MatrixClientPeg";
import { stubClient } from "../../test-utils"; import { useMyRoomMembership, useRoomMemberCount, useRoomMembers } from "./useRoomMembers";
import { useMyRoomMembership, useRoomMemberCount, useRoomMembers } from "../../../src/hooks/useRoomMembers";
describe("useRoomMembers", () => { describe("useRoomMembers", () => {
function render(room: Room) { function render(room: Room) {
@@ -6,14 +6,17 @@ SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Com
Please see LICENSE files in the repository root for full details. Please see LICENSE files in the repository root for full details.
*/ */
import { renderHook } from "jest-matrix-react"; // @vitest-environment happy-dom
import { describe, it, expect, beforeEach } from "vitest";
import { renderHook } from "test-utils-rtl";
import { EventStatus, NotificationCountType, PendingEventOrdering, Room } from "matrix-js-sdk/src/matrix"; import { EventStatus, NotificationCountType, PendingEventOrdering, Room } from "matrix-js-sdk/src/matrix";
import { KnownMembership } from "matrix-js-sdk/src/types"; import { KnownMembership } from "matrix-js-sdk/src/types";
import { type MatrixClient } from "matrix-js-sdk/src/matrix";
import { mkEvent, muteRoom, stubClient } from "test-utils";
import type { MatrixClient } from "matrix-js-sdk/src/matrix"; import { useUnreadNotifications } from "./useUnreadNotifications";
import { useUnreadNotifications } from "../../../src/hooks/useUnreadNotifications"; import { NotificationLevel } from "../stores/notifications/NotificationLevel";
import { NotificationLevel } from "../../../src/stores/notifications/NotificationLevel";
import { mkEvent, muteRoom, stubClient } from "../../test-utils";
describe("useUnreadNotifications", () => { describe("useUnreadNotifications", () => {
let client: MatrixClient; let client: MatrixClient;
@@ -6,12 +6,15 @@ SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Com
Please see LICENSE files in the repository root for full details. Please see LICENSE files in the repository root for full details.
*/ */
import { waitFor, renderHook, act } from "jest-matrix-react"; // @vitest-environment happy-dom
import { type MatrixClient } from "matrix-js-sdk/src/matrix";
import { useUserDirectory } from "../../../src/hooks/useUserDirectory"; import { describe, it, expect, beforeEach } from "vitest";
import { MatrixClientPeg } from "../../../src/MatrixClientPeg"; import { waitFor, renderHook, act } from "test-utils-rtl";
import { stubClient } from "../../test-utils"; import { type MatrixClient } from "matrix-js-sdk/src/matrix";
import { stubClient } from "test-utils";
import { useUserDirectory } from "./useUserDirectory";
import { MatrixClientPeg } from "../MatrixClientPeg";
function render() { function render() {
return renderHook(() => useUserDirectory()); return renderHook(() => useUserDirectory());
@@ -5,32 +5,34 @@ SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Com
Please see LICENSE files in the repository root for full details. Please see LICENSE files in the repository root for full details.
*/ */
import React from "react"; // @vitest-environment happy-dom
import { renderHook, waitFor } from "jest-matrix-react";
import { ClientEvent } from "matrix-js-sdk/src/matrix";
import { useUserStatus } from "../../../src/hooks/useUserStatus"; import { vi, describe, it, expect, beforeEach, afterEach } from "vitest";
import { getMockClientWithEventEmitter, mockClientMethodsUser, mockClientMethodsServer } from "../../test-utils"; import { renderHook, waitFor } from "test-utils-rtl";
import { MatrixClientContextProvider } from "../../../src/components/structures/MatrixClientContextProvider"; import { ClientEvent } from "matrix-js-sdk/src/matrix";
import SettingsStore from "../../../src/settings/SettingsStore"; import {
import { userStatusTextWithinMaxLength } from "../../../src/utils/userStatus"; getMockClientWithEventEmitter,
mockClientMethodsUser,
mockClientMethodsServer,
withContexts,
} from "test-utils";
import { useUserStatus } from "./useUserStatus";
import SettingsStore from "../settings/SettingsStore";
import { userStatusTextWithinMaxLength } from "../utils/userStatus";
const userId = "@alice:example.com"; const userId = "@alice:example.com";
const client = getMockClientWithEventEmitter({ const client = getMockClientWithEventEmitter({
...mockClientMethodsUser(), ...mockClientMethodsUser(),
...mockClientMethodsServer(), ...mockClientMethodsServer(),
getCrypto: jest.fn().mockReturnValue(null), getCrypto: vi.fn().mockReturnValue(null),
doesServerSupportExtendedProfiles: jest.fn().mockResolvedValue(true), doesServerSupportExtendedProfiles: vi.fn().mockResolvedValue(true),
getExtendedProfileProperty: jest.fn().mockResolvedValue(undefined), getExtendedProfileProperty: vi.fn().mockResolvedValue(undefined),
}); });
function render(uid: string | undefined = userId) { function render(uid: string | undefined = userId) {
return renderHook(() => useUserStatus(uid), { return renderHook(() => useUserStatus(uid), withContexts({ matrixClient: client }));
wrapper: ({ children }) => (
<MatrixClientContextProvider client={client}>{children}</MatrixClientContextProvider>
),
});
} }
describe("userStatusTextWithinMaxLength", () => { describe("userStatusTextWithinMaxLength", () => {
@@ -49,7 +51,7 @@ describe("userStatusTextWithinMaxLength", () => {
describe("useUserStatus", () => { describe("useUserStatus", () => {
beforeEach(() => { beforeEach(() => {
jest.spyOn(SettingsStore, "getValue").mockImplementation((name): any => { vi.spyOn(SettingsStore, "getValue").mockImplementation((name): any => {
if (name === "feature_user_status") return true; if (name === "feature_user_status") return true;
}); });
client.doesServerSupportExtendedProfiles.mockResolvedValue(true); client.doesServerSupportExtendedProfiles.mockResolvedValue(true);
@@ -57,11 +59,11 @@ describe("useUserStatus", () => {
}); });
afterEach(() => { afterEach(() => {
jest.restoreAllMocks(); vi.restoreAllMocks();
}); });
it("returns undefined when feature is disabled", async () => { it("returns undefined when feature is disabled", async () => {
jest.spyOn(SettingsStore, "getValue").mockReturnValue(false); vi.spyOn(SettingsStore, "getValue").mockReturnValue(false);
const { result } = render(); const { result } = render();
expect(result.current).toBeUndefined(); expect(result.current).toBeUndefined();
}); });
+1
View File
@@ -21,6 +21,7 @@ export * from "./utilities";
export * from "./date"; export * from "./date";
export * from "./relations"; export * from "./relations";
export * from "./console"; export * from "./console";
export * from "../unit-tests/TestSDKContext.ts";
// wait for loading page // wait for loading page
export async function waitForLoadingSpinner(): Promise<void> { export async function waitForLoadingSpinner(): Promise<void> {
@@ -0,0 +1,16 @@
/*
Copyright 2024 New Vector Ltd.
Copyright 2022 The Matrix.org Foundation C.I.C.
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE files in the repository root for full details.
*/
import "@testing-library/jest-dom/vitest";
// eslint-disable-next-line no-restricted-imports
import { cleanup } from "@testing-library/react";
import { afterEach } from "vitest";
afterEach(cleanup);
export * from "./jest-matrix-react.tsx";
+27
View File
@@ -14,6 +14,8 @@ import { MatrixClientPeg as peg } from "../../src/MatrixClientPeg";
import MatrixClientContext from "../../src/contexts/MatrixClientContext"; import MatrixClientContext from "../../src/contexts/MatrixClientContext";
import { SDKContext } from "../../src/contexts/SDKContext"; import { SDKContext } from "../../src/contexts/SDKContext";
import { type SDKContextClass } from "../../src/contexts/SDKContextClass"; import { type SDKContextClass } from "../../src/contexts/SDKContextClass";
import { type RoomContextType } from "../../src/contexts/RoomContext.ts";
import { ScopedRoomContextProvider } from "../../src/contexts/ScopedRoomContext.tsx";
type WrapperProps<T> = { wrappedRef?: Ref<ComponentType<T>> } & T; type WrapperProps<T> = { wrappedRef?: Ref<ComponentType<T>> } & T;
@@ -73,3 +75,28 @@ export function clientAndSDKContextRenderOptions(client: MatrixClient, sdkContex
), ),
}; };
} }
export function withContexts({
sdkContext,
matrixClient,
roomContext,
}: {
sdkContext?: SDKContextClass;
matrixClient?: MatrixClient;
roomContext?: RoomContextType;
}): RenderOptions {
return {
wrapper: ({ children }) => {
const client = matrixClient || sdkContext?.client;
if (client) {
children = <MatrixClientContext.Provider value={client}>{children}</MatrixClientContext.Provider>;
}
if (sdkContext) {
children = <SDKContext.Provider value={sdkContext}>{children}</SDKContext.Provider>;
}
if (roomContext) {
children = <ScopedRoomContextProvider {...roomContext}>{children}</ScopedRoomContextProvider>;
}
return children;
},
};
}
@@ -18,7 +18,7 @@ import SettingsStore from "../../../src/settings/SettingsStore";
import { UIFeature } from "../../../src/settings/UIFeature"; import { UIFeature } from "../../../src/settings/UIFeature";
import { SDKContextClass } from "../../../src/contexts/SDKContextClass"; import { SDKContextClass } from "../../../src/contexts/SDKContextClass";
import { DateSeparatorViewModel } from "../../../src/viewmodels/room/timeline/DateSeparatorViewModel"; import { DateSeparatorViewModel } from "../../../src/viewmodels/room/timeline/DateSeparatorViewModel";
import { flushPromisesWithFakeTimers } from "../../test-utils"; import { flushPromisesWithFakeTimers } from "../../test-utils/utilities";
jest.mock("../../../src/settings/SettingsStore"); jest.mock("../../../src/settings/SettingsStore");
jest.mock("../../../src/contexts/SDKContextClass", () => ({ jest.mock("../../../src/contexts/SDKContextClass", () => ({
+1 -1
View File
@@ -11,7 +11,7 @@ import { resolve } from "node:path";
export default defineProject({ export default defineProject({
resolve: { resolve: {
alias: [ alias: [
{ find: "test-utils-rtl", replacement: resolve(__dirname, "./test/test-utils/jest-matrix-react") }, { find: "test-utils-rtl", replacement: resolve(__dirname, "./test/test-utils/vitest-matrix-react") },
{ find: "test-utils", replacement: resolve(__dirname, "./test/test-utils") }, { find: "test-utils", replacement: resolve(__dirname, "./test/test-utils") },
// Stub out workers as they do not play well under test // Stub out workers as they do not play well under test
{ {