Migrate stores Jest tests to Vitest (#34728)

* Migrate stores Jest tests to Vitest

* Fix bad rebase
This commit is contained in:
Michael Telatynski
2026-08-18 12:48:34 +00:00
committed by GitHub
parent a6ec53fcdf
commit a8d5ab4d2d
43 changed files with 998 additions and 864 deletions
@@ -6,7 +6,9 @@ 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.
*/
import ActiveWidgetStore from "../../../src/stores/ActiveWidgetStore";
import { describe, it, expect } from "vitest";
import ActiveWidgetStore from "./ActiveWidgetStore";
describe("ActiveWidgetStore", () => {
const store = ActiveWidgetStore.instance;
@@ -6,30 +6,32 @@ 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.
*/
import { mocked } from "jest-mock";
import { type MatrixClient, Room } from "matrix-js-sdk/src/matrix";
// @vitest-environment happy-dom
import { createTestClient, flushPromises, setupAsyncStoreWithClient } from "../../test-utils";
import SettingsStore from "../../../src/settings/SettingsStore";
import { BreadcrumbsStore } from "../../../src/stores/BreadcrumbsStore";
import { Action } from "../../../src/dispatcher/actions";
import defaultDispatcher from "../../../src/dispatcher/dispatcher";
import { describe, it, beforeEach, expect, vi } from "vitest";
import { type MatrixClient, Room } from "matrix-js-sdk/src/matrix";
import { createTestClient, flushPromises, setupAsyncStoreWithClient } from "test-utils";
import SettingsStore from "../settings/SettingsStore";
import { BreadcrumbsStore } from "./BreadcrumbsStore";
import { Action } from "../dispatcher/actions";
import defaultDispatcher from "../dispatcher/dispatcher";
describe("BreadcrumbsStore", () => {
let store: BreadcrumbsStore;
const client: MatrixClient = createTestClient();
beforeEach(() => {
jest.resetAllMocks();
vi.resetAllMocks();
store = BreadcrumbsStore.instance;
setupAsyncStoreWithClient(store, client);
jest.spyOn(SettingsStore, "setValue").mockImplementation(() => Promise.resolve());
jest.spyOn(SettingsStore, "getValue").mockReturnValue(false);
vi.spyOn(SettingsStore, "setValue").mockImplementation(() => Promise.resolve());
vi.spyOn(SettingsStore, "getValue").mockReturnValue(false);
});
describe("If the feature_dynamic_room_predecessors is not enabled", () => {
beforeEach(() => {
jest.spyOn(SettingsStore, "getValue").mockReturnValue(false);
vi.spyOn(SettingsStore, "getValue").mockReturnValue(false);
});
it("Appends a room when you join", async () => {
@@ -38,8 +40,8 @@ describe("BreadcrumbsStore", () => {
// Given a room
const room = fakeRoom();
mocked(client.getRoom).mockReturnValue(room);
mocked(client.getRoomUpgradeHistory).mockReturnValue([]);
vi.mocked(client.getRoom).mockReturnValue(room);
vi.mocked(client.getRoomUpgradeHistory).mockReturnValue([]);
// When we hear that we have joined it
await dispatchJoinRoom(room.roomId);
@@ -52,12 +54,12 @@ describe("BreadcrumbsStore", () => {
// Given an old room and a new room
const oldRoom = fakeRoom();
const newRoom = fakeRoom();
mocked(client.getRoom).mockImplementation((roomId) => {
vi.mocked(client.getRoom).mockImplementation((roomId) => {
if (roomId === oldRoom.roomId) return oldRoom;
return newRoom;
});
// Where the new one is a predecessor of the old one
mocked(client.getRoomUpgradeHistory).mockReturnValue([oldRoom, newRoom]);
vi.mocked(client.getRoomUpgradeHistory).mockReturnValue([oldRoom, newRoom]);
// When we hear that we joined the old room, then the new one
await dispatchJoinRoom(oldRoom.roomId);
@@ -70,8 +72,8 @@ describe("BreadcrumbsStore", () => {
it("Passes through the dynamic predecessor setting", async () => {
// Given a room
const room = fakeRoom();
mocked(client.getRoom).mockReturnValue(room);
mocked(client.getRoomUpgradeHistory).mockReturnValue([]);
vi.mocked(client.getRoom).mockReturnValue(room);
vi.mocked(client.getRoomUpgradeHistory).mockReturnValue([]);
// When we signal that we have joined
await dispatchJoinRoom(room.roomId);
@@ -84,7 +86,7 @@ describe("BreadcrumbsStore", () => {
describe("If the feature_dynamic_room_predecessors is enabled", () => {
beforeEach(() => {
// Turn on feature_dynamic_room_predecessors setting
jest.spyOn(SettingsStore, "getValue").mockImplementation(
vi.spyOn(SettingsStore, "getValue").mockImplementation(
(settingName) => settingName === "feature_dynamic_room_predecessors",
);
});
@@ -92,8 +94,8 @@ describe("BreadcrumbsStore", () => {
it("Passes through the dynamic predecessor setting", async () => {
// Given a room
const room = fakeRoom();
mocked(client.getRoom).mockReturnValue(room);
mocked(client.getRoomUpgradeHistory).mockReturnValue([]);
vi.mocked(client.getRoom).mockReturnValue(room);
vi.mocked(client.getRoomUpgradeHistory).mockReturnValue([]);
// When we signal that we have joined
await dispatchJoinRoom(room.roomId);
@@ -5,22 +5,24 @@
* Please see LICENSE files in the repository root for full details.
*/
import { type CallMembership, MatrixRTCSessionManagerEvents } from "matrix-js-sdk/src/matrixrtc";
import { type MatrixClient, type Room } from "matrix-js-sdk/src/matrix";
import { type MockedObject } from "jest-mock";
// @vitest-environment happy-dom
import { ElementCall } from "../../../src/models/Call";
import { CallStore } from "../../../src/stores/CallStore";
import { type CallMembership, MatrixRTCSessionManagerEvents } from "matrix-js-sdk/src/matrixrtc";
import { type Room } from "matrix-js-sdk/src/matrix";
import { vi, describe, it, expect, beforeEach, afterEach } from "vitest";
import {
setUpClientRoomAndStores,
cleanUpClientRoomAndStores,
setupAsyncStoreWithClient,
enableCalls,
} from "../../test-utils";
import SdkConfig from "../../../src/SdkConfig.ts";
} from "test-utils";
import { ElementCall } from "../models/Call";
import { CallStore } from "./CallStore";
import SdkConfig from "../SdkConfig";
describe("CallStore", () => {
let client: MockedObject<MatrixClient>;
let client: ReturnType<typeof setUpClientRoomAndStores>["client"];
let room: Room;
beforeEach(() => {
@@ -32,12 +34,12 @@ describe("CallStore", () => {
afterEach(() => {
cleanUpClientRoomAndStores(client, room);
jest.restoreAllMocks();
vi.restoreAllMocks();
});
it("constructs one call for one MatrixRTC session", () => {
setupAsyncStoreWithClient(CallStore.instance, client);
const getSpy = jest.spyOn(ElementCall, "get");
const getSpy = vi.spyOn(ElementCall, "get");
// Simulate another user starting a new MatrixRTC session
const session = client.matrixRTC.getRoomSession(room);
@@ -69,7 +71,7 @@ describe("CallStore", () => {
it("does not fall back to client well-known when enable_client_well_known_lookups is false", async () => {
const sdkConfigGet = SdkConfig.get;
jest.spyOn(SdkConfig, "get").mockImplementation((key?: any, altCaseName?: string): any => {
vi.spyOn(SdkConfig, "get").mockImplementation((key?: any, altCaseName?: string): any => {
if (key === "enable_client_well_known_lookups") return false;
return sdkConfigGet(key, altCaseName);
});
@@ -5,17 +5,19 @@ 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.
*/
import { mocked } from "jest-mock";
// @vitest-environment happy-dom
import { vi, describe, it, expect, beforeEach } from "vitest";
import { type MatrixClient } from "matrix-js-sdk/src/matrix";
import { waitFor } from "jest-matrix-react";
import { waitFor } from "test-utils-rtl";
import { sleep } from "matrix-js-sdk/src/utils";
import { createTestClient } from "test-utils";
import { createCrossSigning } from "../../../src/CreateCrossSigning";
import { InitialCryptoSetupStore } from "../../../src/stores/InitialCryptoSetupStore";
import { createTestClient } from "../../test-utils";
import { createCrossSigning } from "../CreateCrossSigning";
import { InitialCryptoSetupStore } from "./InitialCryptoSetupStore";
jest.mock("../../../src/CreateCrossSigning", () => ({
createCrossSigning: jest.fn(),
vi.mock("../CreateCrossSigning", () => ({
createCrossSigning: vi.fn(),
}));
describe("InitialCryptoSetupStore", () => {
@@ -29,7 +31,7 @@ describe("InitialCryptoSetupStore", () => {
testStore = new InitialCryptoSetupStore();
client = createTestClient();
mocked(createCrossSigning).mockImplementation(() => {
vi.mocked(createCrossSigning).mockImplementation(() => {
return new Promise<void>((resolve, reject) => {
createCrossSigningResolve = resolve;
createCrossSigningReject = reject;
@@ -38,16 +40,16 @@ describe("InitialCryptoSetupStore", () => {
});
it("should call createCrossSigning when startInitialCryptoSetup is called", async () => {
testStore.startInitialCryptoSetup(client, jest.fn());
testStore.startInitialCryptoSetup(client, vi.fn());
await waitFor(() => expect(createCrossSigning).toHaveBeenCalled());
});
it("emits an update event when createCrossSigning resolves", async () => {
const updateSpy = jest.fn();
const updateSpy = vi.fn();
testStore.on("update", updateSpy);
testStore.startInitialCryptoSetup(client, jest.fn());
testStore.startInitialCryptoSetup(client, vi.fn());
createCrossSigningResolve();
await waitFor(() => expect(updateSpy).toHaveBeenCalled());
@@ -55,10 +57,10 @@ describe("InitialCryptoSetupStore", () => {
});
it("emits an update event when createCrossSigning rejects", async () => {
const updateSpy = jest.fn();
const updateSpy = vi.fn();
testStore.on("update", updateSpy);
testStore.startInitialCryptoSetup(client, jest.fn());
testStore.startInitialCryptoSetup(client, vi.fn());
createCrossSigningReject(new Error("Test error"));
await waitFor(() => expect(updateSpy).toHaveBeenCalled());
@@ -66,7 +68,7 @@ describe("InitialCryptoSetupStore", () => {
});
it("should fail to retry once complete", async () => {
testStore.startInitialCryptoSetup(client, jest.fn());
testStore.startInitialCryptoSetup(client, vi.fn());
await waitFor(() => expect(createCrossSigning).toHaveBeenCalled());
createCrossSigningResolve();
@@ -75,7 +77,7 @@ describe("InitialCryptoSetupStore", () => {
});
it("should retry if initial attempt failed", async () => {
testStore.startInitialCryptoSetup(client, jest.fn());
testStore.startInitialCryptoSetup(client, vi.fn());
await waitFor(() => expect(createCrossSigning).toHaveBeenCalled());
createCrossSigningReject(new Error("Test error"));
@@ -6,26 +6,28 @@ 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.
*/
import { mocked } from "jest-mock";
// @vitest-environment happy-dom
import { vi, describe, it, expect, beforeEach, type Mock } from "vitest";
import { SyncState } from "matrix-js-sdk/src/matrix";
import { sleep } from "matrix-js-sdk/src/utils";
import { stubClient } from "test-utils";
import { MatrixClientPeg } from "../../../src/MatrixClientPeg";
import ToastStore from "../../../src/stores/ToastStore";
import { stubClient } from "../../test-utils";
import LifecycleStore from "../../../src/stores/LifecycleStore";
import { MatrixClientPeg } from "../MatrixClientPeg";
import ToastStore from "./ToastStore";
import LifecycleStore from "./LifecycleStore";
describe("LifecycleStore", () => {
stubClient();
const client = MatrixClientPeg.safeGet();
let addOrReplaceToast: jest.SpyInstance;
let addOrReplaceToast: Mock;
beforeEach(() => {
addOrReplaceToast = jest.spyOn(ToastStore.sharedInstance(), "addOrReplaceToast");
addOrReplaceToast = vi.spyOn(ToastStore.sharedInstance(), "addOrReplaceToast");
});
it("should do nothing if the matrix server version is supported", async () => {
mocked(client).isVersionSupported.mockResolvedValue(true);
vi.mocked(client).isVersionSupported.mockResolvedValue(true);
(LifecycleStore as any).onDispatch({
action: "MatrixActions.sync",
@@ -43,7 +45,7 @@ describe("LifecycleStore", () => {
});
it("should show a toast if the matrix server version is unsupported", async () => {
mocked(client).isVersionSupported.mockResolvedValue(false);
vi.mocked(client).isVersionSupported.mockResolvedValue(false);
(LifecycleStore as any).onDispatch({
action: "MatrixActions.sync",
@@ -61,8 +63,8 @@ describe("LifecycleStore", () => {
});
it("dismisses toast on accept button", async () => {
const dismissToast = jest.spyOn(ToastStore.sharedInstance(), "dismissToast");
mocked(client).isVersionSupported.mockResolvedValue(false);
const dismissToast = vi.spyOn(ToastStore.sharedInstance(), "dismissToast");
vi.mocked(client).isVersionSupported.mockResolvedValue(false);
(LifecycleStore as any).onDispatch({
action: "MatrixActions.sync",
@@ -6,15 +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.
*/
import { mocked } from "jest-mock";
// @vitest-environment happy-dom
import { EventType, type IContent, type MatrixClient, MatrixEvent, Room } from "matrix-js-sdk/src/matrix";
import { KnownMembership } from "matrix-js-sdk/src/types";
import { vi, describe, it, expect, beforeEach } from "vitest";
import { stubClient, TestSDKContext } from "test-utils";
import SdkConfig from "../../../src/SdkConfig";
import SettingsStore from "../../../src/settings/SettingsStore";
import { MemberListStore } from "../../../src/stores/MemberListStore";
import { stubClient } from "../../test-utils";
import { TestSDKContext } from "../TestSDKContext";
import SdkConfig from "../SdkConfig";
import SettingsStore from "../settings/SettingsStore";
import { MemberListStore } from "./MemberListStore";
describe("MemberListStore", () => {
const alice = "@alice:bar";
@@ -56,7 +57,7 @@ describe("MemberListStore", () => {
}),
]);
room.recalculate();
mocked(client.getRoom).mockImplementation((r: string): Room | null => {
vi.mocked(client.getRoom).mockImplementation((r: string | undefined): Room | null => {
if (r === roomId) {
return room;
}
@@ -143,9 +144,9 @@ describe("MemberListStore", () => {
describe("lazy loading", () => {
beforeEach(() => {
mocked(client.hasLazyLoadMembersEnabled).mockReturnValue(true);
room.loadMembersIfNeeded = jest.fn();
mocked(room.loadMembersIfNeeded).mockResolvedValue(true);
vi.mocked(client.hasLazyLoadMembersEnabled).mockReturnValue(true);
room.loadMembersIfNeeded = vi.fn();
vi.mocked(room.loadMembersIfNeeded).mockResolvedValue(true);
});
it("calls Room.loadMembersIfNeeded once when enabled", async () => {
@@ -160,14 +161,14 @@ describe("MemberListStore", () => {
describe("sliding sync", () => {
beforeEach(() => {
jest.spyOn(SettingsStore, "getValue").mockImplementation((settingName, roomId, value) => {
vi.spyOn(SettingsStore, "getValue").mockImplementation((settingName, roomId, value) => {
return settingName === "feature_simplified_sliding_sync"; // this is enabled, everything else is disabled.
});
client.members = jest.fn();
client.members = vi.fn();
});
it("calls /members when lazy loading", async () => {
mocked(client.members).mockResolvedValue({
vi.mocked(client.members).mockResolvedValue({
chunk: [
{
type: EventType.RoomMember,
@@ -189,7 +190,7 @@ describe("MemberListStore", () => {
});
it("does not use lazy loading on encrypted rooms", async () => {
jest.spyOn(client.getCrypto()!, "isEncryptionEnabledInRoom").mockResolvedValue(true);
vi.spyOn(client.getCrypto()!, "isEncryptionEnabledInRoom").mockResolvedValue(true);
const { joined } = await store.loadMemberList(roomId);
expect(joined).toEqual([room.getMember(alice)]);
@@ -5,28 +5,32 @@ 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.
*/
import { MultiRoomViewStore } from "../../../src/stores/MultiRoomViewStore";
import { RoomViewStore } from "../../../src/stores/RoomViewStore";
import { Action } from "../../../src/dispatcher/actions";
import type { MatrixDispatcher } from "../../../src/dispatcher/dispatcher";
import { TestSDKContext } from "../TestSDKContext";
// @vitest-environment happy-dom
jest.mock("../../../src/stores/RoomViewStore");
import { vi, describe, it, expect, beforeEach, type Mocked, type MockedClass } from "vitest";
import { TestSDKContext } from "test-utils";
import { MultiRoomViewStore } from "./MultiRoomViewStore";
import { RoomViewStore } from "./RoomViewStore";
import { Action } from "../dispatcher/actions";
import type { MatrixDispatcher } from "../dispatcher/dispatcher";
vi.mock("./RoomViewStore");
describe("MultiRoomViewStore", () => {
let multiRoomViewStore: MultiRoomViewStore;
let mockDispatcher: MatrixDispatcher;
let mockSdkContext: TestSDKContext;
let mockRoomViewStore: jest.Mocked<RoomViewStore>;
let mockRoomViewStore: Mocked<RoomViewStore>;
beforeEach(() => {
jest.clearAllMocks();
vi.clearAllMocks();
// Create mock dispatcher
mockDispatcher = {
dispatch: jest.fn(),
register: jest.fn(),
unregister: jest.fn(),
dispatch: vi.fn(),
register: vi.fn(),
unregister: vi.fn(),
} as unknown as MatrixDispatcher;
// Create mock SDK context
@@ -34,11 +38,13 @@ describe("MultiRoomViewStore", () => {
// Create mock RoomViewStore instance
mockRoomViewStore = {
viewRoom: jest.fn(),
dispose: jest.fn(),
viewRoom: vi.fn(),
dispose: vi.fn(),
} as any;
(RoomViewStore as jest.MockedClass<typeof RoomViewStore>).mockImplementation(() => mockRoomViewStore as any);
(RoomViewStore as MockedClass<typeof RoomViewStore>).mockImplementation(function () {
return mockRoomViewStore as any;
});
// Create the MultiRoomViewStore instance
multiRoomViewStore = new MultiRoomViewStore(mockDispatcher, mockSdkContext);
@@ -65,7 +71,7 @@ describe("MultiRoomViewStore", () => {
// First call creates the store
const firstResult = multiRoomViewStore.getRoomViewStoreForRoom(roomId);
jest.clearAllMocks();
vi.clearAllMocks();
// Should return the same store
const secondResult = multiRoomViewStore.getRoomViewStoreForRoom(roomId);
@@ -89,10 +95,10 @@ describe("MultiRoomViewStore", () => {
multiRoomViewStore.removeRoomViewStore(roomId);
// New store should be created now
jest.clearAllMocks();
(RoomViewStore as jest.MockedClass<typeof RoomViewStore>).mockImplementation(
() => mockRoomViewStore as any,
);
vi.clearAllMocks();
(RoomViewStore as MockedClass<typeof RoomViewStore>).mockImplementation(function () {
return mockRoomViewStore as any;
});
multiRoomViewStore.getRoomViewStoreForRoom(roomId);
expect(RoomViewStore).toHaveBeenCalledWith(mockDispatcher, mockSdkContext, roomId);
@@ -6,6 +6,8 @@ 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.
*/
// @vitest-environment happy-dom
import {
Room,
Beacon,
@@ -19,28 +21,28 @@ import {
} from "matrix-js-sdk/src/matrix";
import { KnownMembership } from "matrix-js-sdk/src/types";
import { logger } from "matrix-js-sdk/src/logger";
import { type Mocked } from "jest-mock-vitest-adapter";
import { OwnBeaconStore, OwnBeaconStoreEvent } from "../../../src/stores/OwnBeaconStore";
import { describe, it, expect, beforeEach, afterEach, afterAll, vi, type Mocked } from "vitest";
import {
advanceDateAndTime,
flushPromisesWithFakeTimers,
makeMembershipEvent,
resetAsyncStoreWithClient,
setupAsyncStoreWithClient,
} from "../../test-utils";
import { makeBeaconInfoEvent, mockGeolocation, watchPositionMockImplementation } from "../../test-utils/beacon";
import { getMockClientWithEventEmitter } from "../../test-utils/client";
import SettingsStore from "../../../src/settings/SettingsStore";
} from "test-utils";
import { makeBeaconInfoEvent, mockGeolocation, watchPositionMockImplementation } from "test-utils/beacon";
import { getMockClientWithEventEmitter } from "test-utils/client";
import { OwnBeaconStore, OwnBeaconStoreEvent } from "./OwnBeaconStore";
import SettingsStore from "../settings/SettingsStore";
// modern fake timers and lodash.debounce are a faff
// short circuit it
jest.mock("lodash", () => ({
...(jest.requireActual("lodash") as object),
debounce: jest.fn().mockImplementation((callback) => callback),
vi.mock("lodash", async () => ({
...(await vi.importActual("lodash")),
debounce: vi.fn().mockImplementation((callback) => callback),
}));
jest.useFakeTimers();
vi.useFakeTimers();
describe("OwnBeaconStore", () => {
let geolocation: Mocked<Geolocation>;
@@ -51,13 +53,13 @@ describe("OwnBeaconStore", () => {
const aliceId = "@alice:server.org";
const bobId = "@bob:server.org";
const mockClient = getMockClientWithEventEmitter({
getUserId: jest.fn().mockReturnValue(aliceId),
getSafeUserId: jest.fn().mockReturnValue(aliceId),
getVisibleRooms: jest.fn().mockReturnValue([]),
unstable_setLiveBeacon: jest.fn().mockResolvedValue({ event_id: "1" }),
sendEvent: jest.fn().mockResolvedValue({ event_id: "1" }),
unstable_createLiveBeacon: jest.fn().mockResolvedValue({ event_id: "1" }),
isGuest: jest.fn().mockReturnValue(false),
getUserId: vi.fn().mockReturnValue(aliceId),
getSafeUserId: vi.fn().mockReturnValue(aliceId),
getVisibleRooms: vi.fn().mockReturnValue([]),
unstable_setLiveBeacon: vi.fn().mockResolvedValue({ event_id: "1" }),
sendEvent: vi.fn().mockResolvedValue({ event_id: "1" }),
unstable_createLiveBeacon: vi.fn().mockResolvedValue({ event_id: "1" }),
isGuest: vi.fn().mockReturnValue(false),
});
const room1Id = "$room1:server.org";
const room2Id = "$room2:server.org";
@@ -70,7 +72,7 @@ describe("OwnBeaconStore", () => {
// with timeout of 3 hours
// event creation sets timestamp to Date.now()
jest.spyOn(global.Date, "now").mockReturnValue(now - HOUR_MS);
vi.spyOn(global.Date, "now").mockReturnValue(now - HOUR_MS);
const alicesRoom1BeaconInfo = makeBeaconInfoEvent(aliceId, room1Id, { isLive: true }, "$alice-room1-1");
const alicesRoom2BeaconInfo = makeBeaconInfoEvent(aliceId, room2Id, { isLive: true }, "$alice-room2-1");
const alicesOldRoomIdBeaconInfo = makeBeaconInfoEvent(aliceId, room1Id, { isLive: false }, "$alice-room1-2");
@@ -134,26 +136,26 @@ describe("OwnBeaconStore", () => {
mockClient.emit(BeaconEvent.New, beaconInfoEvent, beacon);
};
const localStorageGetSpy = jest.spyOn(localStorage.__proto__, "getItem").mockReturnValue(undefined);
const localStorageSetSpy = jest.spyOn(localStorage.__proto__, "setItem").mockImplementation(() => {});
const localStorageGetSpy = vi.spyOn(localStorage, "getItem").mockReturnValue(null);
const localStorageSetSpy = vi.spyOn(localStorage, "setItem").mockImplementation(() => {});
beforeEach(() => {
geolocation = mockGeolocation();
mockClient.getVisibleRooms.mockReturnValue([]);
mockClient.unstable_setLiveBeacon.mockClear().mockResolvedValue({ event_id: "1" });
mockClient.sendEvent.mockReset().mockResolvedValue({ event_id: "1" });
jest.spyOn(global.Date, "now").mockReturnValue(now);
jest.spyOn(OwnBeaconStore.instance, "emit").mockRestore();
jest.spyOn(logger, "error").mockRestore();
vi.spyOn(global.Date, "now").mockReturnValue(now);
vi.spyOn(OwnBeaconStore.instance, "emit").mockRestore();
vi.spyOn(logger, "error").mockRestore();
localStorageGetSpy.mockClear().mockReturnValue(undefined);
localStorageGetSpy.mockClear().mockReturnValue(null);
localStorageSetSpy.mockClear();
});
afterEach(async () => {
await resetAsyncStoreWithClient(OwnBeaconStore.instance);
jest.clearAllTimers();
vi.clearAllTimers();
});
afterAll(() => {
@@ -245,7 +247,7 @@ describe("OwnBeaconStore", () => {
describe("onNotReady()", () => {
it("removes listeners", async () => {
const store = await makeOwnBeaconStore();
const removeSpy = jest.spyOn(mockClient, "removeListener");
const removeSpy = vi.spyOn(mockClient, "removeListener");
// @ts-ignore
store.onNotReady();
@@ -260,7 +262,7 @@ describe("OwnBeaconStore", () => {
const [room1] = makeRoomsWithStateEvents([alicesRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
const beacon = room1.currentState.beacons.get(getBeaconInfoIdentifier(alicesRoom1BeaconInfo))!;
const destroySpy = jest.spyOn(beacon, "destroy");
const destroySpy = vi.spyOn(beacon, "destroy");
// @ts-ignore
store.onNotReady();
@@ -361,7 +363,7 @@ describe("OwnBeaconStore", () => {
makeRoomsWithStateEvents([]);
const store = await makeOwnBeaconStore();
const bobsLiveBeacon = new Beacon(bobsRoom1BeaconInfo);
const monitorSpy = jest.spyOn(bobsLiveBeacon, "monitorLiveness");
const monitorSpy = vi.spyOn(bobsLiveBeacon, "monitorLiveness");
mockClient.emit(BeaconEvent.New, bobsRoom1BeaconInfo, bobsLiveBeacon);
@@ -374,7 +376,7 @@ describe("OwnBeaconStore", () => {
makeRoomsWithStateEvents([]);
const store = await makeOwnBeaconStore();
const alicesLiveBeacon = new Beacon(alicesRoom1BeaconInfo);
const monitorSpy = jest.spyOn(alicesLiveBeacon, "monitorLiveness");
const monitorSpy = vi.spyOn(alicesLiveBeacon, "monitorLiveness");
mockClient.emit(BeaconEvent.New, alicesRoom1BeaconInfo, alicesLiveBeacon);
@@ -386,7 +388,7 @@ describe("OwnBeaconStore", () => {
it("emits a liveness change event when new beacons change live state", async () => {
makeRoomsWithStateEvents([]);
const store = await makeOwnBeaconStore();
const emitSpy = jest.spyOn(store, "emit");
const emitSpy = vi.spyOn(store, "emit");
const alicesLiveBeacon = new Beacon(alicesRoom1BeaconInfo);
mockClient.emit(BeaconEvent.New, alicesRoom1BeaconInfo, alicesLiveBeacon);
@@ -399,7 +401,7 @@ describe("OwnBeaconStore", () => {
const store = await makeOwnBeaconStore();
// already live
expect(store.hasLiveBeacons()).toBe(true);
const emitSpy = jest.spyOn(store, "emit");
const emitSpy = vi.spyOn(store, "emit");
const alicesLiveBeacon = new Beacon(alicesRoom1BeaconInfo);
mockClient.emit(BeaconEvent.New, alicesRoom1BeaconInfo, alicesLiveBeacon);
@@ -424,7 +426,7 @@ describe("OwnBeaconStore", () => {
it("ignores events for irrelevant beacons", async () => {
makeRoomsWithStateEvents([alicesRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
const emitSpy = jest.spyOn(store, "emit");
const emitSpy = vi.spyOn(store, "emit");
const oldLiveBeaconIds = store.getLiveBeaconIds();
const bobsLiveBeacon = new Beacon(bobsRoom1BeaconInfo);
@@ -441,7 +443,7 @@ describe("OwnBeaconStore", () => {
// live before
expect(store.hasLiveBeacons()).toBe(true);
const emitSpy = jest.spyOn(store, "emit");
const emitSpy = vi.spyOn(store, "emit");
await expireBeaconAndEmit(store, alicesRoom1BeaconInfo);
@@ -472,7 +474,7 @@ describe("OwnBeaconStore", () => {
// not live before
expect(store.hasLiveBeacons()).toBe(false);
const emitSpy = jest.spyOn(store, "emit");
const emitSpy = vi.spyOn(store, "emit");
updateBeaconLivenessAndEmit(store, alicesOldRoomIdBeaconInfo, true);
@@ -496,7 +498,7 @@ describe("OwnBeaconStore", () => {
// no beacons for room2
const [, room2] = makeRoomsWithStateEvents([alicesRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
const emitSpy = jest.spyOn(store, "emit");
const emitSpy = vi.spyOn(store, "emit");
const oldLiveBeaconIds = store.getLiveBeaconIds();
mockClient.emit(
@@ -519,7 +521,7 @@ describe("OwnBeaconStore", () => {
const [room1] = makeRoomsWithStateEvents([alicesRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
const emitSpy = jest.spyOn(store, "emit");
const emitSpy = vi.spyOn(store, "emit");
const oldLiveBeaconIds = store.getLiveBeaconIds();
mockClient.emit(RoomStateEvent.Members, membershipEvent, room1.currentState, member);
@@ -537,7 +539,7 @@ describe("OwnBeaconStore", () => {
const [room1] = makeRoomsWithStateEvents([alicesRoom1BeaconInfo, alicesRoom2BeaconInfo]);
const store = await makeOwnBeaconStore();
const emitSpy = jest.spyOn(store, "emit");
const emitSpy = vi.spyOn(store, "emit");
const oldLiveBeaconIds = store.getLiveBeaconIds();
mockClient.emit(RoomStateEvent.Members, membershipEvent, room1.currentState, member);
@@ -556,8 +558,8 @@ describe("OwnBeaconStore", () => {
const [room1] = makeRoomsWithStateEvents([alicesRoom1BeaconInfo, alicesRoom2BeaconInfo]);
const store = await makeOwnBeaconStore();
const room1BeaconInstance = store.beacons.get(getBeaconInfoIdentifier(alicesRoom1BeaconInfo))!;
const beaconDestroySpy = jest.spyOn(room1BeaconInstance, "destroy");
const emitSpy = jest.spyOn(store, "emit");
const beaconDestroySpy = vi.spyOn(room1BeaconInstance, "destroy");
const emitSpy = vi.spyOn(store, "emit");
mockClient.emit(RoomStateEvent.Members, membershipEvent, room1.currentState, member);
@@ -587,7 +589,7 @@ describe("OwnBeaconStore", () => {
it("ignores events for irrelevant beacons", async () => {
makeRoomsWithStateEvents([alicesRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
const emitSpy = jest.spyOn(store, "emit");
const emitSpy = vi.spyOn(store, "emit");
const oldLiveBeaconIds = store.getLiveBeaconIds();
const bobsLiveBeacon = new Beacon(bobsRoom1BeaconInfo);
@@ -604,7 +606,7 @@ describe("OwnBeaconStore", () => {
// live before
expect(store.hasLiveBeacons()).toBe(true);
const emitSpy = jest.spyOn(store, "emit");
const emitSpy = vi.spyOn(store, "emit");
const beacon = store.getBeaconById(getBeaconInfoIdentifier(alicesRoom1BeaconInfo))!;
@@ -652,10 +654,10 @@ describe("OwnBeaconStore", () => {
});
it("records error when stopping beacon event fails to send", async () => {
jest.spyOn(logger, "error").mockImplementation(() => {});
vi.spyOn(logger, "error").mockImplementation(() => {});
makeRoomsWithStateEvents([alicesRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
const emitSpy = jest.spyOn(store, "emit");
const emitSpy = vi.spyOn(store, "emit");
const error = new Error("oups");
mockClient.unstable_setLiveBeacon.mockRejectedValue(error);
@@ -670,10 +672,10 @@ describe("OwnBeaconStore", () => {
});
it("clears previous error and emits when stopping beacon works on retry", async () => {
jest.spyOn(logger, "error").mockImplementation(() => {});
vi.spyOn(logger, "error").mockImplementation(() => {});
makeRoomsWithStateEvents([alicesRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
const emitSpy = jest.spyOn(store, "emit");
const emitSpy = vi.spyOn(store, "emit");
const error = new Error("oups");
mockClient.unstable_setLiveBeacon.mockRejectedValueOnce(error);
@@ -694,10 +696,10 @@ describe("OwnBeaconStore", () => {
});
it("does not emit BeaconUpdateError when stopping succeeds and beacon did not have errors", async () => {
jest.spyOn(logger, "error").mockImplementation(() => {});
vi.spyOn(logger, "error").mockImplementation(() => {});
makeRoomsWithStateEvents([alicesRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
const emitSpy = jest.spyOn(store, "emit");
const emitSpy = vi.spyOn(store, "emit");
// error cleared
expect(store.beaconUpdateErrors.get(getBeaconInfoIdentifier(alicesRoom1BeaconInfo))).toBeFalsy();
@@ -790,10 +792,9 @@ describe("OwnBeaconStore", () => {
});
it("kills live beacon when geolocation is unavailable", async () => {
const errorLogSpy = jest.spyOn(logger, "error").mockImplementation(() => {});
const errorLogSpy = vi.spyOn(logger, "error").mockImplementation(() => {});
// remove the mock we set
// @ts-ignore
navigator.geolocation = undefined;
vi.spyOn(navigator, "geolocation", "get").mockReturnValue(undefined as unknown as Geolocation);
makeRoomsWithStateEvents([alicesRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
@@ -811,7 +812,7 @@ describe("OwnBeaconStore", () => {
// return only a permission denied error
geolocation.watchPosition.mockImplementation(watchPositionMockImplementation([0], [1]));
const errorLogSpy = jest.spyOn(logger, "error").mockImplementation(() => {});
const errorLogSpy = vi.spyOn(logger, "error").mockImplementation(() => {});
makeRoomsWithStateEvents([alicesRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
@@ -839,9 +840,8 @@ describe("OwnBeaconStore", () => {
});
it("kills live beacons when geolocation is unavailable", async () => {
jest.spyOn(logger, "error").mockImplementation(() => {});
// @ts-ignore
navigator.geolocation = undefined;
vi.spyOn(logger, "error").mockImplementation(() => {});
vi.spyOn(navigator, "geolocation", "get").mockReturnValue(undefined as unknown as Geolocation);
makeRoomsWithStateEvents([]);
const store = await makeOwnBeaconStore();
// wait for store to settle
@@ -882,7 +882,7 @@ describe("OwnBeaconStore", () => {
);
// eat expected console error logs
jest.spyOn(logger, "error").mockImplementation(() => {});
vi.spyOn(logger, "error").mockImplementation(() => {});
});
// we need to advance time and then flush promises
@@ -893,7 +893,7 @@ describe("OwnBeaconStore", () => {
// until given ms is 'elapsed'
const advanceAndFlushPromises = async (timeMs: number) => {
while (timeMs > 0) {
jest.advanceTimersByTime(1000);
vi.advanceTimersByTime(1000);
await flushPromisesWithFakeTimers();
timeMs -= 1000;
}
@@ -929,7 +929,7 @@ describe("OwnBeaconStore", () => {
makeRoomsWithStateEvents([alicesRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
const emitSpy = jest.spyOn(store, "emit");
const emitSpy = vi.spyOn(store, "emit");
// wait for store to settle
await flushPromisesWithFakeTimers();
@@ -950,7 +950,7 @@ describe("OwnBeaconStore", () => {
mockClient.sendEvent.mockRejectedValue(new Error("oups"));
makeRoomsWithStateEvents([alicesRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
const emitSpy = jest.spyOn(store, "emit");
const emitSpy = vi.spyOn(store, "emit");
// wait for store to settle
await flushPromisesWithFakeTimers();
@@ -1001,7 +1001,7 @@ describe("OwnBeaconStore", () => {
mockClient.sendEvent.mockRejectedValue(new Error("oups"));
makeRoomsWithStateEvents([alicesRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
const emitSpy = jest.spyOn(store, "emit");
const emitSpy = vi.spyOn(store, "emit");
// wait for store to settle
await flushPromisesWithFakeTimers();
@@ -1049,13 +1049,13 @@ describe("OwnBeaconStore", () => {
// wait for store to settle
await flushPromisesWithFakeTimers();
jest.advanceTimersByTime(5000);
vi.advanceTimersByTime(5000);
expect(mockClient.sendEvent).toHaveBeenCalledTimes(3);
});
it("stops live beacons when geolocation permissions are revoked", async () => {
jest.spyOn(logger, "error").mockImplementation(() => {});
vi.spyOn(logger, "error").mockImplementation(() => {});
// return two good positions, then a permission denied error
geolocation.watchPosition.mockImplementation(watchPositionMockImplementation([0, 1000, 3000], [0, 0, 1]));
@@ -1065,7 +1065,7 @@ describe("OwnBeaconStore", () => {
// wait for store to settle
await flushPromisesWithFakeTimers();
jest.advanceTimersByTime(5000);
vi.advanceTimersByTime(5000);
// first two events were sent successfully
expect(mockClient.sendEvent).toHaveBeenCalledTimes(2);
@@ -1076,7 +1076,7 @@ describe("OwnBeaconStore", () => {
});
it("keeps sharing positions when geolocation has a non fatal error", async () => {
const errorLogSpy = jest.spyOn(logger, "error").mockImplementation(() => {});
const errorLogSpy = vi.spyOn(logger, "error").mockImplementation(() => {});
// return good position, timeout error, good position
geolocation.watchPosition.mockImplementation(watchPositionMockImplementation([0, 1000, 3000], [0, 3, 0]));
@@ -1086,7 +1086,7 @@ describe("OwnBeaconStore", () => {
// wait for store to settle
await flushPromisesWithFakeTimers();
jest.advanceTimersByTime(5000);
vi.advanceTimersByTime(5000);
// two good locations were sent
expect(mockClient.sendEvent).toHaveBeenCalledTimes(2);
@@ -1137,7 +1137,7 @@ describe("OwnBeaconStore", () => {
describe("createLiveBeacon", () => {
const newEventId = "new-beacon-event-id";
const loggerErrorSpy = jest.spyOn(logger, "error").mockImplementation(() => {});
const loggerErrorSpy = vi.spyOn(logger, "error").mockImplementation(() => {});
beforeEach(() => {
localStorageGetSpy.mockReturnValue(JSON.stringify([alicesRoom1BeaconInfo.getId()]));
@@ -1206,7 +1206,7 @@ describe("OwnBeaconStore", () => {
describe("If the feature_dynamic_room_predecessors is not enabled", () => {
beforeEach(() => {
jest.spyOn(SettingsStore, "getValue").mockReturnValue(false);
vi.spyOn(SettingsStore, "getValue").mockReturnValue(false);
});
it("Passes through the dynamic predecessor setting", async () => {
@@ -1220,7 +1220,7 @@ describe("OwnBeaconStore", () => {
describe("If the feature_dynamic_room_predecessors is enabled", () => {
beforeEach(() => {
// Turn on feature_dynamic_room_predecessors setting
jest.spyOn(SettingsStore, "getValue").mockImplementation(
vi.spyOn(SettingsStore, "getValue").mockImplementation(
(settingName) => settingName === "feature_dynamic_room_predecessors",
);
});
@@ -6,22 +6,24 @@ 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.
*/
import { ClientEvent, type MatrixClient, MatrixError } from "matrix-js-sdk/src/matrix";
import { type MockedObject, mocked } from "jest-mock";
// @vitest-environment happy-dom
import { stubClient } from "../../test-utils";
import { OwnProfileStore } from "../../../src/stores/OwnProfileStore";
import { UPDATE_EVENT } from "../../../src/stores/AsyncStore";
import SettingsStore from "../../../src/settings/SettingsStore";
import { vi, describe, it, expect, beforeEach, afterEach, type MockedObject, type Mock } from "vitest";
import { ClientEvent, type MatrixClient, MatrixError } from "matrix-js-sdk/src/matrix";
import { stubClient } from "test-utils";
import { OwnProfileStore } from "./OwnProfileStore";
import { UPDATE_EVENT } from "./AsyncStore";
import SettingsStore from "../settings/SettingsStore";
describe("OwnProfileStore", () => {
let client: MockedObject<MatrixClient>;
let ownProfileStore: OwnProfileStore;
let onUpdate: ReturnType<typeof jest.fn>;
let onUpdate: Mock<() => void>;
beforeEach(() => {
client = mocked(stubClient());
onUpdate = jest.fn();
client = vi.mocked(stubClient());
onUpdate = vi.fn<() => void>();
ownProfileStore = new OwnProfileStore();
ownProfileStore.addListener(UPDATE_EVENT, onUpdate);
});
@@ -84,14 +86,14 @@ describe("OwnProfileStore", () => {
});
it("should be undefined if the feature is disabled", async () => {
jest.spyOn(SettingsStore, "getValue").mockReturnValue(false);
vi.spyOn(SettingsStore, "getValue").mockReturnValue(false);
await ownProfileStore.start();
expect(ownProfileStore.userStatus).toBeUndefined();
});
it("should be undefined if no status is set", async () => {
jest.spyOn(SettingsStore, "getValue").mockReturnValue(true);
vi.spyOn(SettingsStore, "getValue").mockReturnValue(true);
client.getExtendedProfileProperty.mockResolvedValue(undefined);
await ownProfileStore.start();
@@ -99,7 +101,7 @@ describe("OwnProfileStore", () => {
});
it("should fetch and expose the user status on start", async () => {
jest.spyOn(SettingsStore, "getValue").mockReturnValue(true);
vi.spyOn(SettingsStore, "getValue").mockReturnValue(true);
client.getExtendedProfileProperty.mockResolvedValue({ emoji: "🏝️", text: "On a tropical holiday" });
await ownProfileStore.start();
@@ -111,7 +113,7 @@ describe("OwnProfileStore", () => {
});
it("should reflect our own on-a-call status if no other status is set", async () => {
jest.spyOn(SettingsStore, "getValue").mockReturnValue(true);
vi.spyOn(SettingsStore, "getValue").mockReturnValue(true);
client.getExtendedProfileProperty.mockImplementation(async (_userId, key) =>
key === "org.matrix.msc4426.call" ? { call_joined_ts: 12345 } : undefined,
);
@@ -125,7 +127,7 @@ describe("OwnProfileStore", () => {
});
it("should update the user status when a UserProfileUpdate event is received for the current user", async () => {
jest.spyOn(SettingsStore, "getValue").mockReturnValue(true);
vi.spyOn(SettingsStore, "getValue").mockReturnValue(true);
client.getExtendedProfileProperty.mockResolvedValue({ emoji: "🏝️", text: "On a tropical holiday" });
await ownProfileStore.start();
@@ -137,7 +139,7 @@ describe("OwnProfileStore", () => {
});
it("should not update the user status when a UserProfileUpdate event is received for another user", async () => {
jest.spyOn(SettingsStore, "getValue").mockReturnValue(true);
vi.spyOn(SettingsStore, "getValue").mockReturnValue(true);
client.getExtendedProfileProperty.mockResolvedValue({ emoji: "🏝️", text: "On a tropical holiday" });
await ownProfileStore.start();
@@ -6,15 +6,15 @@
* Please see LICENSE files in the repository root for full details.
*/
import { mocked } from "jest-mock";
import { vi, describe, it, expect, beforeEach } from "vitest";
import SettingsStore, { type CallbackFn } from "../../../src/settings/SettingsStore";
import { type Feature, ReleaseAnnouncementStore } from "../../../src/stores/ReleaseAnnouncementStore";
import { type SettingLevel } from "../../../src/settings/SettingLevel";
import ToastStore from "../../../src/stores/ToastStore";
import SettingsStore, { type CallbackFn } from "../settings/SettingsStore";
import { type Feature, ReleaseAnnouncementStore } from "./ReleaseAnnouncementStore";
import { type SettingLevel } from "../settings/SettingLevel";
import ToastStore from "./ToastStore";
jest.mock("../../../src/settings/SettingsStore");
jest.mock("../../../src/stores/ToastStore");
vi.mock("../settings/SettingsStore");
vi.mock("./ToastStore");
describe("ReleaseAnnouncementStore", () => {
let releaseAnnouncementStore: ReleaseAnnouncementStore;
@@ -30,10 +30,10 @@ describe("ReleaseAnnouncementStore", () => {
};
const watchCallbacks: Array<CallbackFn<any>> = [];
mocked(SettingsStore.getValue).mockImplementation((setting: string) => {
vi.mocked(SettingsStore.getValue).mockImplementation((setting: string) => {
return settings[setting];
});
mocked(SettingsStore.setValue).mockImplementation(
vi.mocked(SettingsStore.setValue).mockImplementation(
(settingName: string, roomId: string | null, level: SettingLevel, value: any): Promise<void> => {
settings[settingName] = value;
// we don't care about the parameters, just call the callbacks
@@ -42,16 +42,18 @@ describe("ReleaseAnnouncementStore", () => {
return Promise.resolve();
},
);
mocked(SettingsStore.isLevelSupported).mockReturnValue(true);
mocked(SettingsStore.canSetValue).mockReturnValue(true);
mocked(SettingsStore.watchSetting).mockImplementation((settingName: string, roomId: null, callback: any) => {
watchCallbacks.push(callback);
return "watcherId";
});
vi.mocked(SettingsStore.isLevelSupported).mockReturnValue(true);
vi.mocked(SettingsStore.canSetValue).mockReturnValue(true);
vi.mocked(SettingsStore.watchSetting).mockImplementation(
(settingName: string, roomId: string | null, callback: any) => {
watchCallbacks.push(callback);
return "watcherId";
},
);
mocked(ToastStore.sharedInstance).mockReturnValue({
on: jest.fn(),
getToasts: jest.fn().mockReturnValue([]),
vi.mocked(ToastStore.sharedInstance).mockReturnValue({
on: vi.fn(),
getToasts: vi.fn().mockReturnValue([]),
} as any);
releaseAnnouncementStore = new ReleaseAnnouncementStore();
@@ -118,7 +120,7 @@ describe("ReleaseAnnouncementStore", () => {
});
it("should return null when there are toasts on screen", async () => {
mocked(ToastStore.sharedInstance().getToasts).mockReturnValue([{} as any]);
vi.mocked(ToastStore.sharedInstance().getToasts).mockReturnValue([{} as any]);
expect(releaseAnnouncementStore.getReleaseAnnouncement()).toBeNull();
});
@@ -6,7 +6,8 @@ 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.
*/
import { mocked } from "jest-mock-vitest-adapter";
// @vitest-environment happy-dom
import { KnownMembership, MatrixError, Room } from "matrix-js-sdk/src/matrix";
import { sleep } from "matrix-js-sdk/src/utils";
import {
@@ -14,9 +15,8 @@ import {
type ViewRoomOpts,
} from "@matrix-org/react-sdk-module-api/lib/lifecycles/RoomViewLifecycle";
import EventEmitter from "node:events";
import { RoomViewStore } from "../../../src/stores/RoomViewStore";
import { Action } from "../../../src/dispatcher/actions";
import type * as NodeEvents from "node:events";
import { vi, describe, it, expect, beforeEach, afterEach, type MockedClass } from "vitest";
import {
flushPromises,
getMockClientWithEventEmitter,
@@ -26,79 +26,84 @@ import {
setupAsyncStoreWithClient,
untilDispatch,
untilEmission,
} from "../../test-utils";
import SettingsStore from "../../../src/settings/SettingsStore";
import { SlidingSyncManager } from "../../../src/SlidingSyncManager";
import { PosthogAnalytics } from "../../../src/PosthogAnalytics";
import { TimelineRenderingType } from "../../../src/contexts/RoomContext";
import { MatrixDispatcher } from "../../../src/dispatcher/dispatcher";
import { UPDATE_EVENT } from "../../../src/stores/AsyncStore";
import { type ActiveRoomChangedPayload } from "../../../src/dispatcher/payloads/ActiveRoomChangedPayload";
import SpaceStore from "../../../src/stores/spaces/SpaceStore";
import { TestSDKContext } from "../TestSDKContext";
import { type ViewRoomPayload } from "../../../src/dispatcher/payloads/ViewRoomPayload";
import Modal from "../../../src/Modal";
import ErrorDialog from "../../../src/components/views/dialogs/ErrorDialog";
import { type CancelAskToJoinPayload } from "../../../src/dispatcher/payloads/CancelAskToJoinPayload";
import { type JoinRoomErrorPayload } from "../../../src/dispatcher/payloads/JoinRoomErrorPayload";
import { type SubmitAskToJoinPayload } from "../../../src/dispatcher/payloads/SubmitAskToJoinPayload";
import { ModuleRunner } from "../../../src/modules/ModuleRunner";
import { type IApp } from "../../../src/utils/WidgetUtils-types";
import { CallStore } from "../../../src/stores/CallStore";
import { MatrixClientPeg } from "../../../src/MatrixClientPeg";
import MediaDeviceHandler, { MediaDeviceKindEnum } from "../../../src/MediaDeviceHandler";
import { storeRoomAliasInCache } from "../../../src/RoomAliasCache.ts";
import { type Call, ConnectionState } from "../../../src/models/Call.ts";
import ActiveWidgetStore from "../../../src/stores/ActiveWidgetStore";
import { ModuleApi } from "../../../src/modules/Api";
import { type JoinRoomPayload } from "../../../src/dispatcher/payloads/JoinRoomPayload.ts";
TestSDKContext,
} from "test-utils";
jest.mock("../../../src/Modal");
import { RoomViewStore } from "./RoomViewStore";
import { Action } from "../dispatcher/actions";
import SettingsStore from "../settings/SettingsStore";
import { SlidingSyncManager } from "../SlidingSyncManager";
import { PosthogAnalytics } from "../PosthogAnalytics";
import { TimelineRenderingType } from "../contexts/RoomContext";
import { MatrixDispatcher } from "../dispatcher/dispatcher";
import { UPDATE_EVENT } from "./AsyncStore";
import { type ActiveRoomChangedPayload } from "../dispatcher/payloads/ActiveRoomChangedPayload";
import SpaceStore from "./spaces/SpaceStore";
import { type ViewRoomPayload } from "../dispatcher/payloads/ViewRoomPayload";
import Modal from "../Modal";
import ErrorDialog from "../components/views/dialogs/ErrorDialog";
import { type CancelAskToJoinPayload } from "../dispatcher/payloads/CancelAskToJoinPayload";
import { type JoinRoomErrorPayload } from "../dispatcher/payloads/JoinRoomErrorPayload";
import { type SubmitAskToJoinPayload } from "../dispatcher/payloads/SubmitAskToJoinPayload";
import { ModuleRunner } from "../modules/ModuleRunner";
import { type IApp } from "../utils/WidgetUtils-types";
import { CallStore } from "./CallStore";
import { MatrixClientPeg } from "../MatrixClientPeg";
import MediaDeviceHandler, { MediaDeviceKindEnum } from "../MediaDeviceHandler";
import { storeRoomAliasInCache } from "../RoomAliasCache.ts";
import { type Call, ConnectionState } from "../models/Call.ts";
import ActiveWidgetStore from "./ActiveWidgetStore";
import { ModuleApi } from "../modules/Api";
import { type JoinRoomPayload } from "../dispatcher/payloads/JoinRoomPayload.ts";
vi.mock("../Modal");
// mock out the injected classes
jest.mock("../../../src/PosthogAnalytics");
const MockPosthogAnalytics = <jest.Mock<PosthogAnalytics>>(<unknown>PosthogAnalytics);
jest.mock("../../../src/SlidingSyncManager");
const MockSlidingSyncManager = <jest.Mock<SlidingSyncManager>>(<unknown>SlidingSyncManager);
jest.mock("../../../src/stores/spaces/SpaceStore");
const MockSpaceStore = <jest.Mock<SpaceStore>>(<unknown>SpaceStore);
vi.mock("../PosthogAnalytics");
const MockPosthogAnalytics = PosthogAnalytics as unknown as MockedClass<typeof PosthogAnalytics>;
vi.mock("../SlidingSyncManager");
const MockSlidingSyncManager = SlidingSyncManager as unknown as MockedClass<typeof SlidingSyncManager>;
vi.mock("./spaces/SpaceStore");
const MockSpaceStore = SpaceStore as unknown as MockedClass<typeof SpaceStore>;
// mock VoiceRecording because it contains all the audio APIs
jest.mock("../../../src/audio/VoiceRecording", () => ({
VoiceRecording: jest.fn().mockReturnValue({
disableMaxLength: jest.fn(),
vi.mock("../audio/VoiceRecording", () => ({
VoiceRecording: vi.fn().mockReturnValue({
disableMaxLength: vi.fn(),
liveData: {
onUpdate: jest.fn(),
onUpdate: vi.fn(),
},
off: jest.fn(),
on: jest.fn(),
start: jest.fn(),
stop: jest.fn(),
destroy: jest.fn(),
off: vi.fn(),
on: vi.fn(),
start: vi.fn(),
stop: vi.fn(),
destroy: vi.fn(),
contentType: "audio/ogg",
}),
}));
jest.spyOn(MediaDeviceHandler, "getDevices").mockResolvedValue({
vi.spyOn(MediaDeviceHandler, "getDevices").mockResolvedValue({
[MediaDeviceKindEnum.AudioInput]: [],
[MediaDeviceKindEnum.VideoInput]: [],
[MediaDeviceKindEnum.AudioOutput]: [],
});
jest.mock("../../../src/utils/DMRoomMap", () => {
vi.mock("../utils/DMRoomMap", () => {
const mock = {
getUserIdForRoomId: jest.fn(),
getDMRoomsForUserId: jest.fn(),
getUserIdForRoomId: vi.fn(),
getDMRoomsForUserId: vi.fn(),
};
return {
shared: jest.fn().mockReturnValue(mock),
sharedInstance: mock,
default: {
shared: vi.fn().mockReturnValue(mock),
sharedInstance: mock,
},
};
});
jest.mock("../../../src/stores/WidgetStore", () => {
const EventEmitter = jest.requireActual("events");
vi.mock("./WidgetStore", async () => {
const { EventEmitter } = await vi.importActual<typeof NodeEvents>("node:events");
const apps: IApp[] = [];
const instance = new (class extends EventEmitter {
getApps() {
@@ -108,9 +113,9 @@ jest.mock("../../../src/stores/WidgetStore", () => {
apps.push(app);
}
})();
return { instance };
return { default: { instance } };
});
jest.mock("../../../src/stores/widgets/WidgetLayoutStore");
vi.mock("./widgets/WidgetLayoutStore");
describe("RoomViewStore", function () {
const userId = "@alice:server";
@@ -119,30 +124,30 @@ describe("RoomViewStore", function () {
// we need to change the alias to ensure cache misses as the cache exists
// through all tests.
let alias = "#somealias2:aser.ver";
const getRooms = jest.fn();
const getRooms = vi.fn();
const mockClient = getMockClientWithEventEmitter({
joinRoom: jest.fn(),
getRoom: jest.fn(),
getRoomIdForAlias: jest.fn(),
joinRoom: vi.fn(),
getRoom: vi.fn(),
getRoomIdForAlias: vi.fn(),
getRooms,
isGuest: jest.fn(),
getUserId: jest.fn().mockReturnValue(userId),
getSafeUserId: jest.fn().mockReturnValue(userId),
getDeviceId: jest.fn().mockReturnValue("ABC123"),
getDomain: jest.fn().mockReturnValue("server"),
sendStateEvent: jest.fn().mockResolvedValue({}),
supportsThreads: jest.fn(),
isInitialSyncComplete: jest.fn().mockResolvedValue(false),
relations: jest.fn(),
knockRoom: jest.fn(),
leave: jest.fn(),
setRoomAccountData: jest.fn(),
getAccountData: jest.fn(),
waitForClientWellKnown: jest.fn().mockResolvedValue(undefined),
getClientWellKnown: jest.fn().mockReturnValue({}),
isGuest: vi.fn(),
getUserId: vi.fn().mockReturnValue(userId),
getSafeUserId: vi.fn().mockReturnValue(userId),
getDeviceId: vi.fn().mockReturnValue("ABC123"),
getDomain: vi.fn().mockReturnValue("server"),
sendStateEvent: vi.fn().mockResolvedValue({}),
supportsThreads: vi.fn(),
isInitialSyncComplete: vi.fn().mockResolvedValue(false),
relations: vi.fn(),
knockRoom: vi.fn(),
leave: vi.fn(),
setRoomAccountData: vi.fn(),
getAccountData: vi.fn(),
waitForClientWellKnown: vi.fn().mockResolvedValue(undefined),
getClientWellKnown: vi.fn().mockReturnValue({}),
cachedRtcTransports: {
get: jest.fn().mockReturnValue([]),
wait: jest.fn().mockResolvedValue([]),
get: vi.fn().mockReturnValue([]),
wait: vi.fn().mockResolvedValue([]),
},
matrixRTC: new (class extends EventEmitter {
getRoomSession() {
@@ -182,7 +187,7 @@ describe("RoomViewStore", function () {
let stores: TestSDKContext;
beforeEach(function () {
jest.clearAllMocks();
vi.clearAllMocks();
mockClient.credentials = { userId: userId };
mockClient.joinRoom.mockResolvedValue(room);
mockClient.getRoom.mockImplementation((roomId?: string): Room | null => {
@@ -199,10 +204,14 @@ describe("RoomViewStore", function () {
stores = new TestSDKContext();
stores._client = mockClient;
stores._SlidingSyncManager = slidingSyncManager;
stores._PosthogAnalytics = new MockPosthogAnalytics();
// @ts-expect-error
MockPosthogAnalytics.instance = stores._PosthogAnalytics;
stores._SpaceStore = new MockSpaceStore();
stores._PosthogAnalytics = new MockPosthogAnalytics(
undefined as unknown as ConstructorParameters<typeof PosthogAnalytics>[0],
);
vi.spyOn(MockPosthogAnalytics, "instance", "get").mockReturnValue(stores._PosthogAnalytics);
stores._SpaceStore = new MockSpaceStore(
undefined as unknown as ConstructorParameters<typeof SpaceStore>[0],
undefined as unknown as ConstructorParameters<typeof SpaceStore>[1],
);
// Add activeSpace property to the mock
Object.defineProperty(stores._SpaceStore, "activeSpace", {
value: null,
@@ -257,7 +266,7 @@ describe("RoomViewStore", function () {
});
it("invokes room activity listeners when the viewed room changes", async () => {
const callback = jest.fn();
const callback = vi.fn();
roomViewStore.addRoomListener(roomId, callback);
dis.dispatch({ action: Action.ViewRoom, room_id: roomId });
(await untilDispatch(Action.ActiveRoomChanged, dis)) as ActiveRoomChangedPayload;
@@ -361,7 +370,7 @@ describe("RoomViewStore", function () {
it("does not change room when replying to event in a room displayed in module", async () => {
// Spy on dispatch to check later if ViewRoom was dispatched
jest.spyOn(dis, "dispatch");
vi.spyOn(dis, "dispatch");
// Set up current room
dis.dispatch({ action: Action.ViewRoom, room_id: roomId });
@@ -402,7 +411,7 @@ describe("RoomViewStore", function () {
it("when viewing a call without a broadcast, it should not raise an error", async () => {
const call = { presented: false } as Call;
const getCallSpy = jest.spyOn(CallStore.instance, "getCall").mockReturnValue(call);
const getCallSpy = vi.spyOn(CallStore.instance, "getCall").mockReturnValue(call);
await setupAsyncStoreWithClient(CallStore.instance, MatrixClientPeg.safeGet());
dis.dispatch<ViewRoomPayload>({
@@ -419,8 +428,8 @@ describe("RoomViewStore", function () {
it("implicitly views an active call", async () => {
const call = { presented: false } as Call;
jest.spyOn(CallStore.instance, "getCall").mockReturnValue(call);
jest.spyOn(CallStore.instance, "getActiveCall").mockImplementation((rId) => (rId === roomId ? call : null));
vi.spyOn(CallStore.instance, "getCall").mockReturnValue(call);
vi.spyOn(CallStore.instance, "getActiveCall").mockImplementation((rId) => (rId === roomId ? call : null));
await setupAsyncStoreWithClient(CallStore.instance, MatrixClientPeg.safeGet());
// View the room without explicitly setting view_call to true
@@ -439,10 +448,10 @@ describe("RoomViewStore", function () {
presented: false,
connectionState: ConnectionState.Disconnected,
widget: { id: "!widget:example.org" },
start: jest.fn(),
start: vi.fn(),
} as unknown as Call;
jest.spyOn(CallStore.instance, "getCall").mockReturnValue(call);
const persistenceSpy = jest.spyOn(ActiveWidgetStore.instance, "setWidgetPersistence");
vi.spyOn(CallStore.instance, "getCall").mockReturnValue(call);
const persistenceSpy = vi.spyOn(ActiveWidgetStore.instance, "setWidgetPersistence");
await setupAsyncStoreWithClient(CallStore.instance, MatrixClientPeg.safeGet());
dis.dispatch<ViewRoomPayload>({
@@ -467,10 +476,10 @@ describe("RoomViewStore", function () {
presented: false,
connectionState: ConnectionState.Disconnected,
widget: { id: "!widget:example.org" },
start: jest.fn(),
start: vi.fn(),
} as unknown as Call;
jest.spyOn(CallStore.instance, "getCall").mockReturnValue(call);
const persistenceSpy = jest.spyOn(ActiveWidgetStore.instance, "setWidgetPersistence");
vi.spyOn(CallStore.instance, "getCall").mockReturnValue(call);
const persistenceSpy = vi.spyOn(ActiveWidgetStore.instance, "setWidgetPersistence");
await setupAsyncStoreWithClient(CallStore.instance, MatrixClientPeg.safeGet());
dis.dispatch<ViewRoomPayload>({
@@ -497,7 +506,7 @@ describe("RoomViewStore", function () {
roomViewStore.showJoinRoomError(error, roomId);
// Check the modal props
expect(mocked(Modal).createDialog.mock.calls[0][1]).toMatchSnapshot();
expect(vi.mocked(Modal).createDialog.mock.calls[0][1]).toMatchSnapshot();
});
// The server bob is on will affect the message we send.
it.each(["server", "another-server"])(
@@ -520,7 +529,7 @@ describe("RoomViewStore", function () {
roomViewStore.showJoinRoomError(error, roomId);
// Check the modal props
expect(mocked(Modal).createDialog.mock.calls[0][1]).toMatchSnapshot();
expect(vi.mocked(Modal).createDialog.mock.calls[0][1]).toMatchSnapshot();
},
);
@@ -537,7 +546,7 @@ describe("RoomViewStore", function () {
roomViewStore.showJoinRoomError(error, roomId);
// Check the modal props
expect(mocked(Modal).createDialog.mock.calls[0][1]).toMatchSnapshot();
expect(vi.mocked(Modal).createDialog.mock.calls[0][1]).toMatchSnapshot();
});
it("clears the unread flag when viewing a room", async () => {
@@ -553,13 +562,22 @@ describe("RoomViewStore", function () {
describe("Sliding Sync", function () {
beforeEach(() => {
jest.spyOn(SettingsStore, "getValue").mockImplementation((settingName, roomId, value) => {
vi.spyOn(SettingsStore, "getValue").mockImplementation((settingName, roomId, value) => {
return settingName === "feature_simplified_sliding_sync"; // this is enabled, everything else is disabled.
});
});
afterEach(() => {
// Restore immediately: this mock makes RoomViewStore.viewRoom() take the "simplified sliding sync"
// branch, which re-dispatches Action.ViewRoom asynchronously. If left in place after this describe
// block, it leaks into later tests (vi.clearAllMocks() clears call history but not implementations)
// and can cause a dangling re-dispatch that fires during a later test and crashes on
// MatrixClientPeg.safeGet() once that room is no longer set up.
vi.mocked(SettingsStore.getValue).mockRestore();
});
it("subscribes to the room", async () => {
const setRoomVisible = jest.spyOn(slidingSyncManager, "setRoomVisible").mockReturnValue(Promise.resolve());
const setRoomVisible = vi.spyOn(slidingSyncManager, "setRoomVisible").mockReturnValue(Promise.resolve());
const subscribedRoomId = "!sub1:localhost";
dis.dispatch({ action: Action.ViewRoom, room_id: subscribedRoomId });
await untilDispatch(Action.ActiveRoomChanged, dis);
@@ -571,7 +589,7 @@ describe("RoomViewStore", function () {
// although that was before the complexity was removed with similified mode. I've removed the complexity but kept the
// test anyway.
it("doesn't get stuck in a loop if you view rooms quickly", async () => {
const setRoomVisible = jest.spyOn(slidingSyncManager, "setRoomVisible").mockReturnValue(Promise.resolve());
const setRoomVisible = vi.spyOn(slidingSyncManager, "setRoomVisible").mockReturnValue(Promise.resolve());
const subscribedRoomId = "!sub1:localhost";
const subscribedRoomId2 = "!sub2:localhost";
dis.dispatch({ action: Action.ViewRoom, room_id: subscribedRoomId }, true);
@@ -594,8 +612,8 @@ describe("RoomViewStore", function () {
it("dispatches Action.JoinRoomError and Action.AskToJoin when the join fails with 403", async () => {
const err = new MatrixError({}, 403);
jest.spyOn(dis, "dispatch");
jest.spyOn(mockClient, "joinRoom").mockRejectedValueOnce(err);
vi.spyOn(dis, "dispatch");
vi.spyOn(mockClient, "joinRoom").mockRejectedValueOnce(err);
const roomId = "!hello:world";
@@ -607,19 +625,19 @@ describe("RoomViewStore", function () {
});
await untilDispatch(Action.PromptAskToJoin, dis);
expect(mocked(dis.dispatch).mock.calls[0][0]).toEqual({
expect(vi.mocked(dis.dispatch).mock.calls[0][0]).toEqual({
action: Action.JoinRoom,
canAskToJoin: true,
metricsTrigger: "RoomPreview",
roomId,
});
expect(mocked(dis.dispatch).mock.calls[1][0]).toEqual({
expect(vi.mocked(dis.dispatch).mock.calls[1][0]).toEqual({
action: Action.JoinRoomError,
roomId,
err,
canAskToJoin: true,
});
expect(mocked(dis.dispatch).mock.calls[2][0]).toEqual({ action: Action.PromptAskToJoin });
expect(vi.mocked(dis.dispatch).mock.calls[2][0]).toEqual({ action: Action.PromptAskToJoin });
});
it("sets 'acceptSharedHistory'", async () => {
@@ -632,7 +650,7 @@ describe("RoomViewStore", function () {
describe("Action.JoinRoomError", () => {
const err = new MatrixError();
beforeEach(() => jest.spyOn(roomViewStore, "showJoinRoomError"));
beforeEach(() => vi.spyOn(roomViewStore, "showJoinRoomError"));
it("calls showJoinRoomError()", async () => {
dis.dispatch<JoinRoomErrorPayload>({ action: Action.JoinRoomError, roomId, err });
@@ -663,7 +681,7 @@ describe("RoomViewStore", function () {
beforeEach(async () => await dispatchPromptAskToJoin());
it("calls knockRoom() and sets promptAskToJoin state to false", async () => {
jest.spyOn(mockClient, "knockRoom").mockResolvedValue({ room_id: roomId });
vi.spyOn(mockClient, "knockRoom").mockResolvedValue({ room_id: roomId });
await dispatchSubmitAskToJoin(roomId, reason);
expect(mockClient.knockRoom).toHaveBeenCalledWith(roomId, { reason, viaServers: [] });
@@ -672,7 +690,7 @@ describe("RoomViewStore", function () {
it("calls knockRoom(), sets promptAskToJoin state to false and shows an error dialog", async () => {
const error = new MatrixError(undefined, 403);
jest.spyOn(mockClient, "knockRoom").mockRejectedValue(error);
vi.spyOn(mockClient, "knockRoom").mockRejectedValue(error);
await dispatchSubmitAskToJoin(roomId, reason);
expect(mockClient.knockRoom).toHaveBeenCalledWith(roomId, { reason, viaServers: [] });
@@ -685,7 +703,7 @@ describe("RoomViewStore", function () {
it("shows an error dialog with a generic error message", async () => {
const error = new MatrixError();
jest.spyOn(mockClient, "knockRoom").mockRejectedValue(error);
vi.spyOn(mockClient, "knockRoom").mockRejectedValue(error);
await dispatchSubmitAskToJoin(roomId);
expect(Modal.createDialog).toHaveBeenCalledWith(ErrorDialog, {
@@ -697,12 +715,12 @@ describe("RoomViewStore", function () {
describe("Action.CancelAskToJoin", () => {
beforeEach(async () => {
jest.spyOn(mockClient, "knockRoom").mockResolvedValue({ room_id: roomId });
vi.spyOn(mockClient, "knockRoom").mockResolvedValue({ room_id: roomId });
await dispatchSubmitAskToJoin(roomId);
});
it("calls leave()", async () => {
jest.spyOn(mockClient, "leave").mockResolvedValue({});
vi.spyOn(mockClient, "leave").mockResolvedValue({});
await dispatchCancelAskToJoin(roomId);
expect(mockClient.leave).toHaveBeenCalledWith(roomId);
@@ -710,7 +728,7 @@ describe("RoomViewStore", function () {
it("calls leave() and shows an error dialog", async () => {
const error = new MatrixError();
jest.spyOn(mockClient, "leave").mockRejectedValue(error);
vi.spyOn(mockClient, "leave").mockRejectedValue(error);
await dispatchCancelAskToJoin(roomId);
expect(mockClient.leave).toHaveBeenCalledWith(roomId);
@@ -737,7 +755,7 @@ describe("RoomViewStore", function () {
onClick: () => {},
},
];
jest.spyOn(ModuleRunner.instance, "invoke").mockImplementation((lifecycleEvent, opts) => {
vi.spyOn(ModuleRunner.instance, "invoke").mockImplementation((lifecycleEvent, opts) => {
if (lifecycleEvent === RoomViewLifecycle.ViewRoom) {
opts.buttons = buttons;
}
@@ -6,17 +6,19 @@ 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.
*/
import { mocked, type Mocked } from "jest-mock";
// @vitest-environment happy-dom
import { vi, describe, it, expect, beforeEach, type Mocked } from "vitest";
import { type MatrixClient, Device } from "matrix-js-sdk/src/matrix";
import { type SecretStorageKeyDescriptionAesV1, type ServerSideSecretStorage } from "matrix-js-sdk/src/secret-storage";
import { type CryptoApi, DeviceVerificationStatus } from "matrix-js-sdk/src/crypto-api";
import { emitPromise, stubClient } from "test-utils";
import { accessSecretStorage } from "../../../src/SecurityManager";
import { SetupEncryptionStore } from "../../../src/stores/SetupEncryptionStore";
import { emitPromise, stubClient } from "../../test-utils";
import { accessSecretStorage } from "../SecurityManager";
import { SetupEncryptionStore } from "./SetupEncryptionStore";
jest.mock("../../../src/SecurityManager", () => ({
accessSecretStorage: jest.fn(),
vi.mock("../SecurityManager", () => ({
accessSecretStorage: vi.fn(),
}));
describe("SetupEncryptionStore", () => {
@@ -26,21 +28,21 @@ describe("SetupEncryptionStore", () => {
let setupEncryptionStore: SetupEncryptionStore;
beforeEach(() => {
client = mocked(stubClient());
client = vi.mocked(stubClient());
mockCrypto = {
bootstrapCrossSigning: jest.fn(),
getCrossSigningKeyId: jest.fn(),
getVerificationRequestsToDeviceInProgress: jest.fn().mockReturnValue([]),
getUserDeviceInfo: jest.fn(),
getDeviceVerificationStatus: jest.fn(),
isDehydrationSupported: jest.fn().mockResolvedValue(false),
startDehydration: jest.fn(),
getKeyBackupInfo: jest.fn().mockResolvedValue(null),
bootstrapCrossSigning: vi.fn(),
getCrossSigningKeyId: vi.fn(),
getVerificationRequestsToDeviceInProgress: vi.fn().mockReturnValue([]),
getUserDeviceInfo: vi.fn(),
getDeviceVerificationStatus: vi.fn(),
isDehydrationSupported: vi.fn().mockResolvedValue(false),
startDehydration: vi.fn(),
getKeyBackupInfo: vi.fn().mockResolvedValue(null),
} as unknown as Mocked<CryptoApi>;
client.getCrypto.mockReturnValue(mockCrypto);
mockSecretStorage = {
isStored: jest.fn(),
isStored: vi.fn(),
} as unknown as Mocked<ServerSideSecretStorage>;
Object.defineProperty(client, "secretStorage", { value: mockSecretStorage });
@@ -128,7 +130,7 @@ describe("SetupEncryptionStore", () => {
mockCrypto.getDeviceVerificationStatus.mockResolvedValue(
new DeviceVerificationStatus({ signedByOwner: true }),
);
mocked(accessSecretStorage).mockImplementation(async (func?: () => Promise<void>) => {
vi.mocked(accessSecretStorage).mockImplementation(async (func?: () => Promise<void>) => {
await func!();
});
@@ -149,7 +151,7 @@ describe("SetupEncryptionStore", () => {
await setupEncryptionStore.usePassPhrase();
await dehydrationPromise;
await expect(dehydrationPromise).resolves.toBeUndefined();
});
});
});
@@ -6,8 +6,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.
*/
import GenericToast from "../../../src/components/views/toasts/GenericToast";
import ToastStore, { type IToast } from "../../../src/stores/ToastStore";
import { vi, describe, it, expect } from "vitest";
import GenericToast from "../components/views/toasts/GenericToast";
import ToastStore, { type IToast } from "./ToastStore";
describe("ToastStore", () => {
const makeToast = (priority: number, key?: string): IToast<typeof GenericToast> => ({
@@ -28,7 +30,7 @@ describe("ToastStore", () => {
it("adds a toast to an empty store", () => {
const toast = makeToast(1);
const store = new ToastStore();
const emitSpy = jest.spyOn(store, "emit");
const emitSpy = vi.spyOn(store, "emit");
store.addOrReplaceToast(toast);
expect(emitSpy).toHaveBeenCalledWith("update");
expect(store.getToasts()).toEqual([toast]);
@@ -67,7 +69,7 @@ describe("ToastStore", () => {
describe("dismissToast()", () => {
it("does nothing when there are no toasts", () => {
const store = new ToastStore();
const emitSpy = jest.spyOn(store, "emit");
const emitSpy = vi.spyOn(store, "emit");
store.dismissToast("whatever");
@@ -80,7 +82,7 @@ describe("ToastStore", () => {
const toastB = makeToast(3, "b");
store.addOrReplaceToast(toastA);
store.addOrReplaceToast(toastB);
const emitSpy = jest.spyOn(store, "emit");
const emitSpy = vi.spyOn(store, "emit");
store.dismissToast(toastA.key);
@@ -6,17 +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.
*/
// @vitest-environment happy-dom
import { vi, describe, it, expect, beforeEach } from "vitest";
import { type MatrixClient } from "matrix-js-sdk/src/matrix";
import { TestSDKContext } from "test-utils";
import TypingStore from "../../../src/stores/TypingStore";
import { LOCAL_ROOM_ID_PREFIX } from "../../../src/models/LocalRoom";
import SettingsStore from "../../../src/settings/SettingsStore";
import { TestSDKContext } from "../TestSDKContext";
import TypingStore from "./TypingStore";
import { LOCAL_ROOM_ID_PREFIX } from "../models/LocalRoom";
import SettingsStore from "../settings/SettingsStore";
jest.mock("../../../src/settings/SettingsStore", () => ({
getValue: jest.fn(),
monitorSetting: jest.fn(),
watchSetting: jest.fn(),
vi.mock("../settings/SettingsStore", () => ({
default: {
getValue: vi.fn(),
monitorSetting: vi.fn(),
watchSetting: vi.fn(),
},
}));
describe("TypingStore", () => {
@@ -27,12 +32,12 @@ describe("TypingStore", () => {
beforeEach(() => {
mockClient = {
sendTyping: jest.fn(),
sendTyping: vi.fn(),
} as unknown as MatrixClient;
const context = new TestSDKContext();
context._client = mockClient;
typingStore = new TypingStore(context);
jest.spyOn(SettingsStore, "getValue").mockImplementation((name: string) => {
vi.spyOn(SettingsStore, "getValue").mockImplementation((name: string) => {
return name === "sendTypingNotifications";
});
});
@@ -5,9 +5,13 @@
* Please see LICENSE files in the repository root for full details.
*/
import UIStore, { UI_EVENTS } from "../../../src/stores/UIStore";
// @vitest-environment happy-dom
jest.useFakeTimers();
import { vi, describe, it, expect } from "vitest";
import UIStore, { UI_EVENTS } from "./UIStore";
vi.useFakeTimers();
describe("UIStore", () => {
class MockResizeObserver {
@@ -30,9 +34,9 @@ describe("UIStore", () => {
MockResizeObserver.callback([entry], MockResizeObserver.instance);
};
public observe = jest.fn();
public unobserve = jest.fn();
public disconnect = jest.fn();
public observe = vi.fn();
public unobserve = vi.fn();
public disconnect = vi.fn();
}
globalThis.ResizeObserver = MockResizeObserver;
@@ -41,12 +45,12 @@ describe("UIStore", () => {
window.innerWidth = 500;
const store = UIStore.instance;
const onDecrease = jest.fn();
const onDecrease = vi.fn();
store.on(UI_EVENTS.WidthDecreased, onDecrease);
MockResizeObserver.changeWidth(200);
expect(onDecrease).toHaveBeenCalledWith(200);
const onIncrease = jest.fn();
const onIncrease = vi.fn();
store.on(UI_EVENTS.WidthIncreased, onIncrease);
MockResizeObserver.changeWidth(700);
expect(onIncrease).toHaveBeenCalledWith(700);
@@ -67,7 +71,7 @@ describe("UIStore", () => {
expect(store.isWindowBeingResized).toBe(true);
// After a second, isWindowBeingResized should again become false
jest.runAllTimers();
vi.runAllTimers();
expect(store.isWindowBeingResized).toBe(false);
});
});
@@ -6,7 +6,9 @@ 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.
*/
import { mocked, type Mocked } from "jest-mock";
// @vitest-environment happy-dom
import { vi, describe, it, expect, beforeEach, type Mocked } from "vitest";
import {
type IMatrixProfile,
type MatrixClient,
@@ -15,9 +17,9 @@ import {
Room,
RoomMemberEvent,
} from "matrix-js-sdk/src/matrix";
import { filterConsole, mkRoomMember, mkRoomMemberJoinEvent, stubClient } from "test-utils";
import { UserProfilesStore } from "../../../src/stores/UserProfilesStore";
import { filterConsole, mkRoomMember, mkRoomMemberJoinEvent, stubClient } from "../../test-utils";
import { UserProfilesStore } from "./UserProfilesStore";
describe("UserProfilesStore", () => {
const userIdDoesNotExist = "@unknown:example.com";
@@ -41,7 +43,7 @@ describe("UserProfilesStore", () => {
);
beforeEach(() => {
mockClient = mocked(stubClient());
mockClient = vi.mocked(stubClient());
room = new Room("!room:example.com", mockClient, mockClient.getSafeUserId());
room.currentState.setStateEvents([
mkRoomMemberJoinEvent(user2Id, room.roomId),
@@ -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.
*/
import { type MatrixClient } from "matrix-js-sdk/src/matrix";
// @vitest-environment happy-dom
import { VoiceRecordingStore } from "../../../src/stores/VoiceRecordingStore";
import { MatrixClientPeg } from "../../../src/MatrixClientPeg";
import { flushPromises } from "../../test-utils";
import { VoiceMessageRecording } from "../../../src/audio/VoiceMessageRecording";
import { vi, describe, it, expect } from "vitest";
import { type MatrixClient } from "matrix-js-sdk/src/matrix";
import { flushPromises } from "test-utils";
import { VoiceRecordingStore } from "./VoiceRecordingStore";
import { MatrixClientPeg } from "../MatrixClientPeg";
import { VoiceMessageRecording } from "../audio/VoiceMessageRecording";
const stubClient = {} as unknown as MatrixClient;
jest.spyOn(MatrixClientPeg, "get").mockReturnValue(stubClient);
vi.spyOn(MatrixClientPeg, "get").mockReturnValue(stubClient);
describe("VoiceRecordingStore", () => {
const room1Id = "!room1:server.org";
const room2Id = "!room2:server.org";
const room3Id = "!room3:server.org";
const room1Recording = { destroy: jest.fn() } as unknown as VoiceMessageRecording;
const room2Recording = { destroy: jest.fn() } as unknown as VoiceMessageRecording;
const room1Recording = { destroy: vi.fn() } as unknown as VoiceMessageRecording;
const room2Recording = { destroy: vi.fn() } as unknown as VoiceMessageRecording;
const state: Record<string, VoiceMessageRecording | undefined> = {
[room1Id]: room1Recording,
@@ -1,6 +1,6 @@
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`RoomViewStore should display an error message when the room is unreachable via the roomId 1`] = `
exports[`RoomViewStore > should display an error message when the room is unreachable via the roomId 1`] = `
{
"description": <div>
You attempted to join using a room ID without providing a list of servers to join through. Room IDs are internal identifiers and cannot be used to join a room without additional information.
@@ -12,21 +12,21 @@ exports[`RoomViewStore should display an error message when the room is unreacha
}
`;
exports[`RoomViewStore should display an invite-specific error message when the room is unreachable 1`] = `
exports[`RoomViewStore > should display an invite-specific error message when the room is unreachable 1`] = `
{
"description": "The person who invited you has already left.",
"title": "Failed to join",
}
`;
exports[`RoomViewStore should display an invite-specific error message when the room is unreachable 2`] = `
exports[`RoomViewStore > should display an invite-specific error message when the room is unreachable 2`] = `
{
"description": "The person who invited you has already left, or their server is offline.",
"title": "Failed to join",
}
`;
exports[`RoomViewStore should display the generic error message when the roomId doesnt match 1`] = `
exports[`RoomViewStore > should display the generic error message when the roomId doesnt match 1`] = `
{
"description": "MatrixError: [404] my 404 error",
"title": "Failed to join",
@@ -6,7 +6,9 @@ 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.
*/
import { type Mocked, mocked } from "jest-mock";
// @vitest-environment happy-dom
import { vi, describe, it, expect, beforeEach, type Mocked } from "vitest";
import {
EventStatus,
EventTimeline,
@@ -20,11 +22,11 @@ import {
RelationType,
Room,
} from "matrix-js-sdk/src/matrix";
import { mkEvent, mkMessage, mkReaction, setupAsyncStoreWithClient, stubClient } from "test-utils";
import { mkThread } from "test-utils/threads";
import { MessagePreviewStore } from "../../../../src/stores/message-preview";
import { mkEvent, mkMessage, mkReaction, setupAsyncStoreWithClient, stubClient } from "../../../test-utils";
import { DefaultTagID } from "../../../../src/stores/room-list-v3/skip-list/tag";
import { mkThread } from "../../../test-utils/threads";
import { MessagePreviewStore } from ".";
import { DefaultTagID } from "../room-list-v3/skip-list/tag";
describe("MessagePreviewStore", () => {
let client: Mocked<MatrixClient>;
@@ -73,14 +75,14 @@ describe("MessagePreviewStore", () => {
}
beforeEach(async () => {
client = mocked(stubClient());
client = vi.mocked(stubClient());
room = new Room("!roomId:server", client, client.getSafeUserId(), {
pendingEventOrdering: PendingEventOrdering.Detached,
});
nonRenderedRoom = new Room("!roomId2:server", client, client.getSafeUserId(), {
pendingEventOrdering: PendingEventOrdering.Detached,
});
mocked(client.getRoom).mockReturnValue(room);
vi.mocked(client.getRoom).mockReturnValue(room);
store = MessagePreviewStore.testInstance();
await store.start();
@@ -252,7 +254,7 @@ describe("MessagePreviewStore", () => {
});
it("should generate correct preview for message events in DMs", async () => {
room.getLiveTimeline().getState(EventTimeline.FORWARDS)!.getJoinedMemberCount = jest.fn().mockReturnValue(2);
room.getLiveTimeline().getState(EventTimeline.FORWARDS)!.getJoinedMemberCount = vi.fn().mockReturnValue(2);
await expect(store.getPreviewForRoom(room, DefaultTagID.DM)).resolves.toBeNull();
@@ -5,13 +5,15 @@
* Please see LICENSE files in the repository root for full details.
*/
import { Room } from "matrix-js-sdk/src/matrix";
import { mocked } from "jest-mock";
// @vitest-environment happy-dom
import { LegacyCallAnswerEventPreview } from "../../../../../src/stores/message-preview/previews/LegacyCallAnswerEventPreview";
import { DefaultTagID } from "../../../../../src/stores/room-list-v3/skip-list/tag";
import { mkEvent, stubClient } from "../../../../test-utils";
import { MatrixClientPeg } from "../../../../../src/MatrixClientPeg";
import { describe, it, expect, beforeAll, beforeEach, afterEach, vi } from "vitest";
import { Room } from "matrix-js-sdk/src/matrix";
import { mkEvent, stubClient } from "test-utils";
import { LegacyCallAnswerEventPreview } from "./LegacyCallAnswerEventPreview";
import { DefaultTagID } from "../../room-list-v3/skip-list/tag";
import { MatrixClientPeg } from "../../../MatrixClientPeg";
describe("LegacyCallAnswerEventPreview", () => {
const preview = new LegacyCallAnswerEventPreview();
@@ -55,12 +57,12 @@ describe("LegacyCallAnswerEventPreview", () => {
const cli = MatrixClientPeg.safeGet();
// Make a 1:1 room so shouldPrefixMessagesIn returns false
const room = new Room(roomId, cli, cli.getSafeUserId());
jest.spyOn(room.currentState, "getJoinedMemberCount").mockReturnValue(2);
mocked(cli.getRoom).mockReturnValue(room);
vi.spyOn(room.currentState, "getJoinedMemberCount").mockReturnValue(2);
vi.mocked(cli.getRoom).mockReturnValue(room);
});
afterEach(() => {
mocked(MatrixClientPeg.safeGet().getRoom).mockReturnValue(null);
vi.mocked(MatrixClientPeg.safeGet().getRoom).mockReturnValue(null);
});
it("returns 'Call in progress' regardless of sender", () => {
@@ -5,13 +5,15 @@
* Please see LICENSE files in the repository root for full details.
*/
import { Room } from "matrix-js-sdk/src/matrix";
import { mocked } from "jest-mock";
// @vitest-environment happy-dom
import { LegacyCallHangupEvent } from "../../../../../src/stores/message-preview/previews/LegacyCallHangupEvent";
import { DefaultTagID } from "../../../../../src/stores/room-list-v3/skip-list/tag";
import { mkEvent, stubClient } from "../../../../test-utils";
import { MatrixClientPeg } from "../../../../../src/MatrixClientPeg";
import { describe, it, expect, beforeAll, beforeEach, afterEach, vi } from "vitest";
import { Room } from "matrix-js-sdk/src/matrix";
import { mkEvent, stubClient } from "test-utils";
import { LegacyCallHangupEvent } from "./LegacyCallHangupEvent";
import { DefaultTagID } from "../../room-list-v3/skip-list/tag";
import { MatrixClientPeg } from "../../../MatrixClientPeg";
describe("LegacyCallHangupEvent", () => {
const preview = new LegacyCallHangupEvent();
@@ -53,12 +55,12 @@ describe("LegacyCallHangupEvent", () => {
const cli = MatrixClientPeg.safeGet();
// Make a 1:1 room so shouldPrefixMessagesIn returns false
const room = new Room(roomId, cli, cli.getSafeUserId());
jest.spyOn(room.currentState, "getJoinedMemberCount").mockReturnValue(2);
mocked(cli.getRoom).mockReturnValue(room);
vi.spyOn(room.currentState, "getJoinedMemberCount").mockReturnValue(2);
vi.mocked(cli.getRoom).mockReturnValue(room);
});
afterEach(() => {
mocked(MatrixClientPeg.safeGet().getRoom).mockReturnValue(null);
vi.mocked(MatrixClientPeg.safeGet().getRoom).mockReturnValue(null);
});
it("returns 'Call ended' regardless of sender", () => {
@@ -5,13 +5,15 @@
* Please see LICENSE files in the repository root for full details.
*/
import { Room } from "matrix-js-sdk/src/matrix";
import { mocked } from "jest-mock";
// @vitest-environment happy-dom
import { LegacyCallInviteEventPreview } from "../../../../../src/stores/message-preview/previews/LegacyCallInviteEventPreview";
import { DefaultTagID } from "../../../../../src/stores/room-list-v3/skip-list/tag";
import { mkEvent, stubClient } from "../../../../test-utils";
import { MatrixClientPeg } from "../../../../../src/MatrixClientPeg";
import { describe, it, expect, beforeAll, beforeEach, afterEach, vi } from "vitest";
import { Room } from "matrix-js-sdk/src/matrix";
import { mkEvent, stubClient } from "test-utils";
import { LegacyCallInviteEventPreview } from "./LegacyCallInviteEventPreview";
import { DefaultTagID } from "../../room-list-v3/skip-list/tag";
import { MatrixClientPeg } from "../../../MatrixClientPeg";
describe("LegacyCallInviteEventPreview", () => {
const preview = new LegacyCallInviteEventPreview();
@@ -53,12 +55,12 @@ describe("LegacyCallInviteEventPreview", () => {
const cli = MatrixClientPeg.safeGet();
// Make a 1:1 room so shouldPrefixMessagesIn returns false
const room = new Room(roomId, cli, cli.getSafeUserId());
jest.spyOn(room.currentState, "getJoinedMemberCount").mockReturnValue(2);
mocked(cli.getRoom).mockReturnValue(room);
vi.spyOn(room.currentState, "getJoinedMemberCount").mockReturnValue(2);
vi.mocked(cli.getRoom).mockReturnValue(room);
});
afterEach(() => {
mocked(MatrixClientPeg.safeGet().getRoom).mockReturnValue(null);
vi.mocked(MatrixClientPeg.safeGet().getRoom).mockReturnValue(null);
});
it("returns 'Waiting for answer' when the event is from self", () => {
@@ -6,11 +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.
*/
// @vitest-environment happy-dom
import { describe, it, expect, beforeAll } from "vitest";
import { RelationType } from "matrix-js-sdk/src/matrix";
import { mkEvent, stubClient } from "test-utils";
// Import directly from the file to avoid circular dependencies with MessagePreviewStore
import { MessageEventPreview } from "../../../../../src/stores/message-preview/previews/MessageEventPreview";
import { mkEvent, stubClient } from "../../../../test-utils";
import { MessageEventPreview } from "./MessageEventPreview";
describe("MessageEventPreview", () => {
const preview = new MessageEventPreview();
@@ -6,18 +6,21 @@ 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.
*/
// @vitest-environment happy-dom
import { describe, it, expect, vi } from "vitest";
import { type MatrixClient } from "matrix-js-sdk/src/matrix";
import { makePollStartEvent } from "test-utils";
// Import directly from the file to avoid circular dependencies with MessagePreviewStore
import { PollStartEventPreview } from "../../../../../src/stores/message-preview/previews/PollStartEventPreview";
import { MatrixClientPeg } from "../../../../../src/MatrixClientPeg";
import { makePollStartEvent } from "../../../../test-utils";
import { PollStartEventPreview } from "./PollStartEventPreview";
import { MatrixClientPeg } from "../../../MatrixClientPeg";
jest.spyOn(MatrixClientPeg, "get").mockReturnValue({
vi.spyOn(MatrixClientPeg, "get").mockReturnValue({
getUserId: () => "@me:example.com",
getSafeUserId: () => "@me:example.com",
} as unknown as MatrixClient);
jest.spyOn(MatrixClientPeg, "safeGet").mockReturnValue({
vi.spyOn(MatrixClientPeg, "safeGet").mockReturnValue({
getUserId: () => "@me:example.com",
getSafeUserId: () => "@me:example.com",
} as unknown as MatrixClient);
@@ -6,13 +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.
*/
import { RelationType, Room, RoomMember } from "matrix-js-sdk/src/matrix";
import { mocked } from "jest-mock";
// @vitest-environment happy-dom
import { mkEvent, stubClient } from "../../../../test-utils";
import { ReactionEventPreview } from "../../../../../src/stores/message-preview/previews/ReactionEventPreview";
import { MessagePreviewStore } from "../../../../../src/stores/message-preview";
import { MatrixClientPeg } from "../../../../../src/MatrixClientPeg";
import { describe, it, expect, beforeAll, vi } from "vitest";
import { RelationType, Room, RoomMember } from "matrix-js-sdk/src/matrix";
import { mkEvent, stubClient } from "test-utils";
import { ReactionEventPreview } from "./ReactionEventPreview";
import { MessagePreviewStore } from "..";
import { MatrixClientPeg } from "../../../MatrixClientPeg";
describe("ReactionEventPreview", () => {
const preview = new ReactionEventPreview(MessagePreviewStore.instance);
@@ -55,7 +57,7 @@ describe("ReactionEventPreview", () => {
it("should use 'You' for your own reactions", () => {
const cli = MatrixClientPeg.safeGet();
const room = new Room(roomId, cli, userId);
mocked(cli.getRoom).mockReturnValue(room);
vi.mocked(cli.getRoom).mockReturnValue(room);
const message = mkEvent({
event: true,
@@ -92,7 +94,7 @@ describe("ReactionEventPreview", () => {
it("should use display name for your others' reactions", () => {
const cli = MatrixClientPeg.safeGet();
const room = new Room(roomId, cli, userId);
mocked(cli.getRoom).mockReturnValue(room);
vi.mocked(cli.getRoom).mockReturnValue(room);
const message = mkEvent({
event: true,
@@ -5,13 +5,15 @@
* Please see LICENSE files in the repository root for full details.
*/
import { Room } from "matrix-js-sdk/src/matrix";
import { mocked } from "jest-mock";
// @vitest-environment happy-dom
import { StickerEventPreview } from "../../../../../src/stores/message-preview/previews/StickerEventPreview";
import { DefaultTagID } from "../../../../../src/stores/room-list-v3/skip-list/tag";
import { mkEvent, stubClient } from "../../../../test-utils";
import { MatrixClientPeg } from "../../../../../src/MatrixClientPeg";
import { describe, it, expect, beforeAll, beforeEach, afterEach, vi } from "vitest";
import { Room } from "matrix-js-sdk/src/matrix";
import { mkEvent, stubClient } from "test-utils";
import { StickerEventPreview } from "./StickerEventPreview";
import { DefaultTagID } from "../../room-list-v3/skip-list/tag";
import { MatrixClientPeg } from "../../../MatrixClientPeg";
describe("StickerEventPreview", () => {
const preview = new StickerEventPreview();
@@ -77,12 +79,12 @@ describe("StickerEventPreview", () => {
const cli = MatrixClientPeg.safeGet();
// Make a 1:1 room so shouldPrefixMessagesIn returns false
const room = new Room(roomId, cli, cli.getSafeUserId());
jest.spyOn(room.currentState, "getJoinedMemberCount").mockReturnValue(2);
mocked(cli.getRoom).mockReturnValue(room);
vi.spyOn(room.currentState, "getJoinedMemberCount").mockReturnValue(2);
vi.mocked(cli.getRoom).mockReturnValue(room);
});
afterEach(() => {
mocked(MatrixClientPeg.safeGet().getRoom).mockReturnValue(null);
vi.mocked(MatrixClientPeg.safeGet().getRoom).mockReturnValue(null);
});
it("returns just the sticker name regardless of sender", () => {
@@ -6,16 +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.
*/
import { mocked } from "jest-mock";
import { ClientEvent, type MatrixClient, Room, SyncState } from "matrix-js-sdk/src/matrix";
// @vitest-environment happy-dom
import { createTestClient, setupAsyncStoreWithClient } from "../../test-utils";
import {
RoomNotificationStateStore,
UPDATE_STATUS_INDICATOR,
} from "../../../src/stores/notifications/RoomNotificationStateStore";
import SettingsStore from "../../../src/settings/SettingsStore";
import { MatrixDispatcher } from "../../../src/dispatcher/dispatcher";
import { vi, describe, it, expect, beforeEach } from "vitest";
import { ClientEvent, type MatrixClient, Room, SyncState } from "matrix-js-sdk/src/matrix";
import { createTestClient, setupAsyncStoreWithClient } from "test-utils";
import { RoomNotificationStateStore, UPDATE_STATUS_INDICATOR } from "./RoomNotificationStateStore";
import SettingsStore from "../../settings/SettingsStore";
import { MatrixDispatcher } from "../../dispatcher/dispatcher";
describe("RoomNotificationStateStore", function () {
let store: RoomNotificationStateStore;
@@ -25,9 +24,9 @@ describe("RoomNotificationStateStore", function () {
beforeEach(() => {
client = createTestClient();
dis = new MatrixDispatcher();
jest.resetAllMocks();
vi.resetAllMocks();
store = RoomNotificationStateStore.testInstance(dis);
store.emit = jest.fn();
store.emit = vi.fn();
setupAsyncStoreWithClient(store, client);
});
@@ -36,7 +35,7 @@ describe("RoomNotificationStateStore", function () {
const room = fakeRoom(0);
// When we sync and the room is visible
mocked(client.getVisibleRooms).mockReturnValue([room]);
vi.mocked(client.getVisibleRooms).mockReturnValue([room]);
client.emit(ClientEvent.Sync, SyncState.Syncing, SyncState.Syncing);
// Then we emit an event from the store
@@ -48,7 +47,7 @@ describe("RoomNotificationStateStore", function () {
const room = fakeRoom(2);
// When we sync and the room is visible
mocked(client.getVisibleRooms).mockReturnValue([room]);
vi.mocked(client.getVisibleRooms).mockReturnValue([room]);
client.emit(ClientEvent.Sync, SyncState.Syncing, SyncState.Syncing);
// Then we emit an event from the store
@@ -58,15 +57,15 @@ describe("RoomNotificationStateStore", function () {
it("Emits an event when a feature flag changes notification state", async () => {
// Given we have synced already
let room = fakeRoom(0);
mocked(store.emit).mockReset();
mocked(client.getVisibleRooms).mockReturnValue([room]);
vi.mocked(store.emit).mockReset();
vi.mocked(client.getVisibleRooms).mockReturnValue([room]);
client.emit(ClientEvent.Sync, SyncState.Syncing, SyncState.Syncing);
expect(store.emit).not.toHaveBeenCalled();
// When we update the feature flag and it makes us have a notification
room = fakeRoom(2);
mocked(client.getVisibleRooms).mockReturnValue([room]);
jest.spyOn(SettingsStore, "getValue").mockReturnValue(true);
vi.mocked(client.getVisibleRooms).mockReturnValue([room]);
vi.spyOn(SettingsStore, "getValue").mockReturnValue(true);
store.emitUpdateIfStateChanged(SyncState.Syncing, false);
// Then we get notified
@@ -76,12 +75,12 @@ describe("RoomNotificationStateStore", function () {
describe("If the feature_dynamic_room_predecessors is not enabled", () => {
beforeEach(() => {
// Turn off feature_dynamic_room_predecessors setting
jest.spyOn(SettingsStore, "getValue").mockReturnValue(false);
vi.spyOn(SettingsStore, "getValue").mockReturnValue(false);
});
it("Passes the dynamic predecessor flag to getVisibleRooms", async () => {
// When we sync
mocked(client.getVisibleRooms).mockReturnValue([]);
vi.mocked(client.getVisibleRooms).mockReturnValue([]);
client.emit(ClientEvent.Sync, SyncState.Syncing, SyncState.Syncing);
// Then we check visible rooms, using the dynamic predecessor flag
@@ -93,14 +92,14 @@ describe("RoomNotificationStateStore", function () {
describe("If the feature_dynamic_room_predecessors is enabled", () => {
beforeEach(() => {
// Turn on feature_dynamic_room_predecessors setting
jest.spyOn(SettingsStore, "getValue").mockImplementation(
vi.spyOn(SettingsStore, "getValue").mockImplementation(
(settingName) => settingName === "feature_dynamic_room_predecessors",
);
});
it("Passes the dynamic predecessor flag to getVisibleRooms", async () => {
// When we sync
mocked(client.getVisibleRooms).mockReturnValue([]);
vi.mocked(client.getVisibleRooms).mockReturnValue([]);
client.emit(ClientEvent.Sync, SyncState.Syncing, SyncState.Syncing);
// Then we check visible rooms, using the dynamic predecessor flag
@@ -114,10 +113,10 @@ describe("RoomNotificationStateStore", function () {
function fakeRoom(numUnreads: number): Room {
roomIdx++;
const ret = new Room(`room${roomIdx}`, client, "@user:example.com");
ret.getPendingEvents = jest.fn().mockReturnValue([]);
ret.isSpaceRoom = jest.fn().mockReturnValue(false);
ret.getUnreadNotificationCount = jest.fn().mockReturnValue(numUnreads);
ret.getRoomUnreadNotificationCount = jest.fn().mockReturnValue(numUnreads);
ret.getPendingEvents = vi.fn().mockReturnValue([]);
ret.isSpaceRoom = vi.fn().mockReturnValue(false);
ret.getUnreadNotificationCount = vi.fn().mockReturnValue(numUnreads);
ret.getRoomUnreadNotificationCount = vi.fn().mockReturnValue(numUnreads);
return ret;
}
});
@@ -6,31 +6,33 @@ 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.
*/
import { mocked, type MockedObject } from "jest-mock";
// @vitest-environment happy-dom
import { vi, describe, it, expect, beforeEach, type MockedObject } from "vitest";
import { type MatrixClient, RoomMember } from "matrix-js-sdk/src/matrix";
import { stubClient } from "test-utils";
import { stubClient } from "../../../test-utils";
import { MatrixClientPeg } from "../../../../src/MatrixClientPeg";
import DMRoomMap from "../../../../src/utils/DMRoomMap";
import { Action } from "../../../../src/dispatcher/actions";
import defaultDispatcher from "../../../../src/dispatcher/dispatcher";
import { type ActiveRoomChangedPayload } from "../../../../src/dispatcher/payloads/ActiveRoomChangedPayload";
import RightPanelStore from "../../../../src/stores/right-panel/RightPanelStore";
import { RightPanelPhases } from "../../../../src/stores/right-panel/RightPanelStorePhases";
import SettingsStore from "../../../../src/settings/SettingsStore";
import { pendingVerificationRequestForUser } from "../../../../src/verification.ts";
import { MatrixClientPeg } from "../../MatrixClientPeg";
import DMRoomMap from "../../utils/DMRoomMap";
import { Action } from "../../dispatcher/actions";
import defaultDispatcher from "../../dispatcher/dispatcher";
import { type ActiveRoomChangedPayload } from "../../dispatcher/payloads/ActiveRoomChangedPayload";
import RightPanelStore from "./RightPanelStore";
import { RightPanelPhases } from "./RightPanelStorePhases";
import SettingsStore from "../../settings/SettingsStore";
import { pendingVerificationRequestForUser } from "../../verification.ts";
jest.mock("../../../../src/verification");
vi.mock("../../verification");
describe("RightPanelStore", () => {
// Mock out the settings store so the right panel store can't persist values between tests
jest.spyOn(SettingsStore, "setValue").mockImplementation(async () => {});
vi.spyOn(SettingsStore, "setValue").mockImplementation(async () => {});
const store = RightPanelStore.instance;
let cli: MockedObject<MatrixClient>;
beforeEach(() => {
stubClient();
cli = mocked(MatrixClientPeg.safeGet());
cli = vi.mocked(MatrixClientPeg.safeGet());
DMRoomMap.makeShared(cli);
// Make sure we start with a clean store
@@ -227,7 +229,7 @@ describe("RightPanelStore", () => {
it("should redirect to verification if set to phase MemberInfo for a user with a pending verification", async () => {
const member = new RoomMember("!1:example.org", "@alice:example.org");
const verificationRequest = { mockVerificationRequest: true } as any;
mocked(pendingVerificationRequestForUser).mockReturnValue(verificationRequest);
vi.mocked(pendingVerificationRequestForUser).mockReturnValue(verificationRequest);
await viewRoom("!1:example.org");
store.setCard(
{
@@ -6,21 +6,21 @@ 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.
*/
import { type MockedObject } from "jest-mock";
import { vi, describe, it, expect, beforeEach, type MockedObject } from "vitest";
import { EventType, MatrixEvent } from "matrix-js-sdk/src/matrix";
import { Action } from "../../../../../src/dispatcher/actions";
import { onView3pidInvite } from "../../../../../src/stores/right-panel/action-handlers";
import type RightPanelStore from "../../../../../src/stores/right-panel/RightPanelStore";
import { RightPanelPhases } from "../../../../../src/stores/right-panel/RightPanelStorePhases";
import { Action } from "../../../dispatcher/actions";
import { onView3pidInvite } from "./View3pidInvite";
import type RightPanelStore from "../RightPanelStore";
import { RightPanelPhases } from "../RightPanelStorePhases";
describe("onView3pidInvite()", () => {
let rightPanelStore!: MockedObject<RightPanelStore>;
beforeEach(() => {
rightPanelStore = {
pushCard: jest.fn(),
showOrHidePhase: jest.fn(),
pushCard: vi.fn(),
showOrHidePhase: vi.fn(),
} as unknown as MockedObject<RightPanelStore>;
});
@@ -5,70 +5,72 @@ 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.
*/
// @vitest-environment happy-dom
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { EventType, KnownMembership, MatrixEvent, Room } from "matrix-js-sdk/src/matrix";
import { logger } from "matrix-js-sdk/src/logger";
import { mocked } from "jest-mock";
import { mkEvent, mkMessage, mkSpace, mkStubRoom, stubClient, upsertRoomStateEvents } from "test-utils";
import type { MatrixClient } from "matrix-js-sdk/src/matrix";
import type { RoomNotificationState } from "../../../../src/stores/notifications/RoomNotificationState";
import type { RoomNotificationState } from "../notifications/RoomNotificationState";
import {
LISTS_UPDATE_EVENT,
ROOM_TAGGED_EVENT,
SECTION_CREATED_EVENT,
RoomListStoreV3Class,
type Section,
} from "../../../../src/stores/room-list-v3/RoomListStoreV3";
import * as sectionModule from "../../../../src/stores/room-list-v3/section";
import { AsyncStoreWithClient } from "../../../../src/stores/AsyncStoreWithClient";
import { RecencySorter } from "../../../../src/stores/room-list-v3/skip-list/sorters/RecencySorter";
import { mkEvent, mkMessage, mkSpace, mkStubRoom, stubClient, upsertRoomStateEvents } from "../../../test-utils";
import { getMockedRooms } from "./skip-list/getMockedRooms";
import { AlphabeticSorter } from "../../../../src/stores/room-list-v3/skip-list/sorters/AlphabeticSorter";
import dispatcher from "../../../../src/dispatcher/dispatcher";
import { MetaSpace, UPDATE_SELECTED_SPACE } from "../../../../src/stores/spaces";
import { DefaultTagID } from "../../../../src/stores/room-list-v3/skip-list/tag";
import { FilterEnum } from "../../../../src/stores/room-list-v3/skip-list/filters";
import { RoomNotificationStateStore } from "../../../../src/stores/notifications/RoomNotificationStateStore";
import DMRoomMap from "../../../../src/utils/DMRoomMap";
import { SortingAlgorithm } from "../../../../src/stores/room-list-v3/skip-list/sorters";
import SettingsStore from "../../../../src/settings/SettingsStore";
import * as utils from "../../../../src/utils/notifications";
import * as utilsRLS from "../../../../src/stores/room-list-v3/utils.ts";
import { Action } from "../../../../src/dispatcher/actions";
import { SettingLevel } from "../../../../src/settings/SettingLevel.ts";
import { CHATS_TAG } from "../../../../src/stores/room-list-v3/section";
import { SDKContextClass } from "../../../../src/contexts/SDKContextClass.ts";
} from "./RoomListStoreV3";
import * as sectionModule from "./section";
import { AsyncStoreWithClient } from "../AsyncStoreWithClient";
import { RecencySorter } from "./skip-list/sorters/RecencySorter";
import { getMockedRooms } from "./skip-list/__mocks__";
import { AlphabeticSorter } from "./skip-list/sorters/AlphabeticSorter";
import dispatcher from "../../dispatcher/dispatcher";
import { MetaSpace, UPDATE_SELECTED_SPACE } from "../spaces";
import { DefaultTagID } from "./skip-list/tag";
import { FilterEnum } from "./skip-list/filters";
import { RoomNotificationStateStore } from "../notifications/RoomNotificationStateStore";
import DMRoomMap from "../../utils/DMRoomMap";
import { SortingAlgorithm } from "./skip-list/sorters";
import SettingsStore from "../../settings/SettingsStore";
import * as utils from "../../utils/notifications";
import * as utilsRLS from "./utils.ts";
import { Action } from "../../dispatcher/actions";
import { SettingLevel } from "../../settings/SettingLevel.ts";
import { CHATS_TAG } from "./section";
import { SDKContextClass } from "../../contexts/SDKContextClass.ts";
describe("RoomListStoreV3", () => {
async function getRoomListStore() {
const client = stubClient();
const rooms = getMockedRooms(client);
client.getVisibleRooms = jest.fn().mockReturnValue(rooms);
jest.spyOn(AsyncStoreWithClient.prototype, "matrixClient", "get").mockReturnValue(client);
client.getVisibleRooms = vi.fn().mockReturnValue(rooms);
vi.spyOn(AsyncStoreWithClient.prototype, "matrixClient", "get").mockReturnValue(client);
const store = new RoomListStoreV3Class(dispatcher);
await store.start();
return { client, rooms, store, dispatcher };
}
beforeEach(() => {
jest.spyOn(global, "requestAnimationFrame").mockImplementation((cb: FrameRequestCallback) => {
vi.spyOn(global, "requestAnimationFrame").mockImplementation((cb: FrameRequestCallback) => {
cb(0);
return 0;
});
jest.spyOn(SDKContextClass.instance.spaceStore, "isRoomInSpace").mockImplementation(
vi.spyOn(SDKContextClass.instance.spaceStore, "isRoomInSpace").mockImplementation(
(space) => space === MetaSpace.Home,
);
jest.spyOn(SDKContextClass.instance.spaceStore, "activeSpace", "get").mockImplementation(() => MetaSpace.Home);
jest.spyOn(SDKContextClass.instance.spaceStore, "storeReadyPromise", "get").mockImplementation(() =>
vi.spyOn(SDKContextClass.instance.spaceStore, "activeSpace", "get").mockImplementation(() => MetaSpace.Home);
vi.spyOn(SDKContextClass.instance.spaceStore, "storeReadyPromise", "get").mockImplementation(() =>
Promise.resolve(),
);
jest.spyOn(RoomNotificationStateStore.instance, "getRoomState").mockImplementation((room) => {
vi.spyOn(RoomNotificationStateStore.instance, "getRoomState").mockImplementation((room) => {
const state = {
isUnread: false,
} as unknown as RoomNotificationState;
return state;
});
jest.spyOn(DMRoomMap, "shared").mockImplementation((() => {
vi.spyOn(DMRoomMap, "shared").mockImplementation((() => {
return {
getUserIdForRoomId: (id) => "",
};
@@ -76,7 +78,7 @@ describe("RoomListStoreV3", () => {
});
afterEach(() => {
jest.restoreAllMocks();
vi.restoreAllMocks();
});
it("Provides an unsorted list of rooms", async () => {
@@ -108,7 +110,7 @@ describe("RoomListStoreV3", () => {
});
it("Uses preferred sorter on startup", async () => {
jest.spyOn(SettingsStore, "getValue").mockImplementation(() => {
vi.spyOn(SettingsStore, "getValue").mockImplementation(() => {
return SortingAlgorithm.Alphabetic;
});
const { store } = await getRoomListStore();
@@ -122,7 +124,7 @@ describe("RoomListStoreV3", () => {
// Let's pretend like a new timeline event came on the room in 37th index.
const room = rooms[37];
const event = mkMessage({ room: room.roomId, user: "@foo3:matrix.org", ts: 1000, event: true });
jest.spyOn(room.getLiveTimeline(), "getEvents").mockReturnValue([event]);
vi.spyOn(room.getLiveTimeline(), "getEvents").mockReturnValue([event]);
const payload = {
action: "MatrixActions.Room.timeline",
@@ -132,7 +134,7 @@ describe("RoomListStoreV3", () => {
room,
};
const fn = jest.fn();
const fn = vi.fn();
store.on(LISTS_UPDATE_EVENT, fn);
dispatcher.dispatch(payload, true);
@@ -152,7 +154,7 @@ describe("RoomListStoreV3", () => {
action: Action.AfterForgetRoom,
room: room,
};
const fn = jest.fn();
const fn = vi.fn();
store.on(LISTS_UPDATE_EVENT, fn);
dispatcher.dispatch(payload, true);
@@ -176,7 +178,7 @@ describe("RoomListStoreV3", () => {
room,
};
const fn = jest.fn();
const fn = vi.fn();
store.on(LISTS_UPDATE_EVENT, fn);
dispatcher.dispatch(payload, true);
@@ -201,7 +203,7 @@ describe("RoomListStoreV3", () => {
room,
};
const fn = jest.fn();
const fn = vi.fn();
store.on(LISTS_UPDATE_EVENT, fn);
dispatcher.dispatch(payload, true);
@@ -215,7 +217,7 @@ describe("RoomListStoreV3", () => {
const oldRoom = rooms[32];
// Create a new room with a predecessor event that points to oldRoom
const newRoom = new Room("!foonew:matrix.org", client, client.getSafeUserId(), {});
mocked(client.getRoomUpgradeHistory).mockImplementation((roomId) =>
vi.mocked(client.getRoomUpgradeHistory).mockImplementation((roomId) =>
roomId === newRoom.roomId ? [oldRoom, newRoom] : [],
);
const createWithPredecessor = new MatrixEvent({
@@ -230,7 +232,7 @@ describe("RoomListStoreV3", () => {
});
upsertRoomStateEvents(newRoom, [createWithPredecessor]);
const fn = jest.fn();
const fn = vi.fn();
store.on(LISTS_UPDATE_EVENT, fn);
dispatcher.dispatch(
{
@@ -264,7 +266,7 @@ describe("RoomListStoreV3", () => {
});
upsertRoomStateEvents(newRoom, [createWithPredecessor]);
const fn = jest.fn();
const fn = vi.fn();
store.on(LISTS_UPDATE_EVENT, fn);
dispatcher.dispatch(
{
@@ -300,7 +302,7 @@ describe("RoomListStoreV3", () => {
type: EventType.Direct,
});
const fn = jest.fn();
const fn = vi.fn();
store.on(LISTS_UPDATE_EVENT, fn);
// Do the actual dispatch
@@ -335,7 +337,7 @@ describe("RoomListStoreV3", () => {
it("Room is re-inserted on tag change", async () => {
const { store, rooms, dispatcher } = await getRoomListStore();
const fn = jest.fn();
const fn = vi.fn();
store.on(LISTS_UPDATE_EVENT, fn);
dispatcher.dispatch(
{
@@ -349,7 +351,7 @@ describe("RoomListStoreV3", () => {
it("emits ROOM_TAGGED_EVENT on a local user tag action", async () => {
const { store, dispatcher } = await getRoomListStore();
const fn = jest.fn();
const fn = vi.fn();
store.on(ROOM_TAGGED_EVENT, fn);
dispatcher.dispatch(
{
@@ -362,9 +364,9 @@ describe("RoomListStoreV3", () => {
it("Room is re-inserted on decryption", async () => {
const { store, rooms, client, dispatcher } = await getRoomListStore();
jest.spyOn(client, "getRoom").mockImplementation(() => rooms[10]);
vi.spyOn(client, "getRoom").mockImplementation(() => rooms[10]);
const fn = jest.fn();
const fn = vi.fn();
store.on(LISTS_UPDATE_EVENT, fn);
dispatcher.dispatch(
{
@@ -378,10 +380,10 @@ describe("RoomListStoreV3", () => {
it("Logs a warning if room couldn't be found from room-id on decryption action", async () => {
const { store, client, dispatcher } = await getRoomListStore();
jest.spyOn(client, "getRoom").mockImplementation(() => null);
const warnSpy = jest.spyOn(logger, "warn");
vi.spyOn(client, "getRoom").mockImplementation(() => null);
const warnSpy = vi.spyOn(logger, "warn");
const fn = jest.fn();
const fn = vi.fn();
store.on(LISTS_UPDATE_EVENT, fn);
// Dispatch a decrypted action but the room does not exist.
@@ -423,7 +425,7 @@ describe("RoomListStoreV3", () => {
it("Room is re-inserted on read receipt from our user", async () => {
const { store, rooms, client, dispatcher } = await getRoomListStore();
const event = getReadReceiptEvent(client.getSafeUserId());
const fn = jest.fn();
const fn = vi.fn();
store.on(LISTS_UPDATE_EVENT, fn);
dispatcher.dispatch(
{
@@ -439,7 +441,7 @@ describe("RoomListStoreV3", () => {
it("Read receipt from other users do not cause room to be re-inserted", async () => {
const { store, rooms, dispatcher } = await getRoomListStore();
const event = getReadReceiptEvent("@foobar:matrix.org");
const fn = jest.fn();
const fn = vi.fn();
store.on(LISTS_UPDATE_EVENT, fn);
dispatcher.dispatch(
{
@@ -466,12 +468,12 @@ describe("RoomListStoreV3", () => {
}
function setupMocks(spaceRoom: Room, roomIds: string[]) {
jest.spyOn(SDKContextClass.instance.spaceStore, "isRoomInSpace").mockImplementation((space, id) => {
vi.spyOn(SDKContextClass.instance.spaceStore, "isRoomInSpace").mockImplementation((space, id) => {
if (space === MetaSpace.Home && !roomIds.includes(id)) return true;
if (space === spaceRoom.roomId && roomIds.includes(id)) return true;
return false;
});
jest.spyOn(SDKContextClass.instance.spaceStore, "activeSpace", "get").mockImplementation(
vi.spyOn(SDKContextClass.instance.spaceStore, "activeSpace", "get").mockImplementation(
() => spaceRoom.roomId,
);
}
@@ -479,15 +481,15 @@ describe("RoomListStoreV3", () => {
function getClientAndRooms() {
const client = stubClient();
const rooms = getMockedRooms(client);
client.getVisibleRooms = jest.fn().mockReturnValue(rooms);
jest.spyOn(AsyncStoreWithClient.prototype, "matrixClient", "get").mockReturnValue(client);
client.getVisibleRooms = vi.fn().mockReturnValue(rooms);
vi.spyOn(AsyncStoreWithClient.prototype, "matrixClient", "get").mockReturnValue(client);
return { client, rooms };
}
describe("Spaces", () => {
it("Newly created space is not added by the store", async () => {
const { client, rooms } = getClientAndRooms();
const infoSpy = jest.spyOn(logger, "info");
const infoSpy = vi.spyOn(logger, "info");
const store = new RoomListStoreV3Class(dispatcher);
await store.start();
@@ -517,7 +519,7 @@ describe("RoomListStoreV3", () => {
const { spaceRoom, roomIds } = createSpace(rooms, [6, 8, 13, 27, 75], client);
// Mock the space store
jest.spyOn(SDKContextClass.instance.spaceStore, "isRoomInSpace").mockImplementation((space, id) => {
vi.spyOn(SDKContextClass.instance.spaceStore, "isRoomInSpace").mockImplementation((space, id) => {
if (space === MetaSpace.Home && !roomIds.includes(id)) return true;
if (space === spaceRoom.roomId && roomIds.includes(id)) return true;
return false;
@@ -525,7 +527,7 @@ describe("RoomListStoreV3", () => {
const store = new RoomListStoreV3Class(dispatcher);
await store.start();
const fn = jest.fn();
const fn = vi.fn();
store.on(LISTS_UPDATE_EVENT, fn);
// The rooms which belong to the space should not be shown
@@ -538,7 +540,7 @@ describe("RoomListStoreV3", () => {
}
// Lets switch to the space
jest.spyOn(SDKContextClass.instance.spaceStore, "activeSpace", "get").mockImplementation(
vi.spyOn(SDKContextClass.instance.spaceStore, "activeSpace", "get").mockImplementation(
() => spaceRoom.roomId,
);
SDKContextClass.instance.spaceStore.emit(UPDATE_SELECTED_SPACE);
@@ -593,7 +595,7 @@ describe("RoomListStoreV3", () => {
await store.start();
// Let's say 27 got unfavourited
const fn = jest.fn();
const fn = vi.fn();
store.on(LISTS_UPDATE_EVENT, fn);
rooms[27].tags = {};
dispatcher.dispatch(
@@ -621,7 +623,7 @@ describe("RoomListStoreV3", () => {
const { spaceRoom, roomIds } = createSpace(rooms, [6, 8, 13, 27, 75], client);
// Let's say 8, 27 are unread
jest.spyOn(RoomNotificationStateStore.instance, "getRoomState").mockImplementation((room) => {
vi.spyOn(RoomNotificationStateStore.instance, "getRoomState").mockImplementation((room) => {
const state = {
hasUnreadCount: [rooms[8], rooms[27]].includes(room),
} as unknown as RoomNotificationState;
@@ -658,7 +660,7 @@ describe("RoomListStoreV3", () => {
expect(result).toHaveLength(0);
// Mock so that room at index 8 is marked as unread
jest.spyOn(utils, "getMarkedUnreadState").mockImplementation((room) => room.roomId === rooms[8].roomId);
vi.spyOn(utils, "getMarkedUnreadState").mockImplementation((room) => room.roomId === rooms[8].roomId);
dispatcher.dispatch(
{
action: "MatrixActions.Room.accountData",
@@ -681,7 +683,7 @@ describe("RoomListStoreV3", () => {
// Let's say 8, 27 are dms
const ids = [8, 27].map((i) => rooms[i].roomId);
jest.spyOn(DMRoomMap, "shared").mockImplementation((() => {
vi.spyOn(DMRoomMap, "shared").mockImplementation((() => {
return {
getUserIdForRoomId: (id) => (ids.includes(id) ? "@myuser:matrix.org" : ""),
};
@@ -716,7 +718,7 @@ describe("RoomListStoreV3", () => {
// Let's add 5 rooms that we are invited to
const invitedRooms = getMockedRooms(client, 5);
for (const room of invitedRooms) {
room.getMyMembership = jest.fn().mockReturnValue(KnownMembership.Invite);
room.getMyMembership = vi.fn().mockReturnValue(KnownMembership.Invite);
}
rooms.push(...invitedRooms);
@@ -742,7 +744,7 @@ describe("RoomListStoreV3", () => {
const { spaceRoom, roomIds } = createSpace(rooms, [6, 8, 13, 27, 75], client);
// Let's say 8, 27 have mentions
jest.spyOn(RoomNotificationStateStore.instance, "getRoomState").mockImplementation((room) => {
vi.spyOn(RoomNotificationStateStore.instance, "getRoomState").mockImplementation((room) => {
const state = {
isMention: [rooms[8], rooms[27]].includes(room),
} as unknown as RoomNotificationState;
@@ -796,7 +798,7 @@ describe("RoomListStoreV3", () => {
rooms[8].tags[DefaultTagID.Favourite] = {};
// Let's say 8, 27 are unread
jest.spyOn(RoomNotificationStateStore.instance, "getRoomState").mockImplementation((room) => {
vi.spyOn(RoomNotificationStateStore.instance, "getRoomState").mockImplementation((room) => {
const state = {
hasUnreadCount: [rooms[8], rooms[27]].includes(room),
} as unknown as RoomNotificationState;
@@ -820,7 +822,7 @@ describe("RoomListStoreV3", () => {
const { store, client, dispatcher } = await getRoomListStore();
const room = new Room("!fooknock:matrix.org", client, client.getSafeUserId(), {});
room.getMyMembership = jest.fn().mockReturnValue(KnownMembership.Knock);
room.getMyMembership = vi.fn().mockReturnValue(KnownMembership.Knock);
dispatcher.dispatch(
{
action: "MatrixActions.Room.myMembership",
@@ -833,7 +835,7 @@ describe("RoomListStoreV3", () => {
store.getSortedRoomsInActiveSpace([FilterEnum.InvitesFilter]).sections.flatMap((s) => s.rooms),
).not.toContain(room);
room.getMyMembership = jest.fn().mockReturnValue(KnownMembership.Invite);
room.getMyMembership = vi.fn().mockReturnValue(KnownMembership.Invite);
dispatcher.dispatch(
{
action: "MatrixActions.Room.myMembership",
@@ -899,7 +901,7 @@ describe("RoomListStoreV3", () => {
// Rooms 8 and 27 are DMs (no explicit tags + present in the DM map)
const ids = [8, 27].map((i) => rooms[i].roomId);
jest.spyOn(DMRoomMap, "shared").mockImplementation((() => {
vi.spyOn(DMRoomMap, "shared").mockImplementation((() => {
return {
getUserIdForRoomId: (id: string) => (ids.includes(id) ? "@myuser:matrix.org" : ""),
};
@@ -930,7 +932,7 @@ describe("RoomListStoreV3", () => {
// Room 8 (in the space) and room 50 (in Home only) are both DMs
const ids = [rooms[8].roomId, rooms[50].roomId];
jest.spyOn(DMRoomMap, "shared").mockImplementation((() => {
vi.spyOn(DMRoomMap, "shared").mockImplementation((() => {
return {
getUserIdForRoomId: (id: string) => (ids.includes(id) ? "@myuser:matrix.org" : ""),
};
@@ -950,7 +952,7 @@ describe("RoomListStoreV3", () => {
describe("Sections", () => {
function enableSections(): void {
jest.spyOn(SettingsStore, "getValue").mockImplementation((setting: string) => {
vi.spyOn(SettingsStore, "getValue").mockImplementation((setting: string) => {
if (setting === "RoomList.showSections") return true;
if (setting === "RoomList.OrderedCustomSections") return [];
if (setting === "RoomList.CustomSectionData") return {};
@@ -965,8 +967,8 @@ describe("RoomListStoreV3", () => {
function getClientAndRooms() {
const client = stubClient();
const rooms = getMockedRooms(client);
client.getVisibleRooms = jest.fn().mockReturnValue(rooms);
jest.spyOn(AsyncStoreWithClient.prototype, "matrixClient", "get").mockReturnValue(client);
client.getVisibleRooms = vi.fn().mockReturnValue(rooms);
vi.spyOn(AsyncStoreWithClient.prototype, "matrixClient", "get").mockReturnValue(client);
return { client, rooms };
}
@@ -986,7 +988,7 @@ describe("RoomListStoreV3", () => {
describe("RoomList.showSections disabled", () => {
function disableSections(): void {
jest.spyOn(SettingsStore, "getValue").mockImplementation((setting: string) => {
vi.spyOn(SettingsStore, "getValue").mockImplementation((setting: string) => {
if (setting === "RoomList.showSections") return false;
if (setting === "RoomList.OrderedCustomSections") return [];
if (setting === "RoomList.CustomSectionData") return {};
@@ -1017,7 +1019,7 @@ describe("RoomListStoreV3", () => {
getClientAndRooms();
let settingsWatcher: () => void = () => {};
jest.spyOn(SettingsStore, "watchSetting").mockImplementation((settingName, _roomId, callback) => {
vi.spyOn(SettingsStore, "watchSetting").mockImplementation((settingName, _roomId, callback) => {
if (settingName === "RoomList.showSections") settingsWatcher = callback as () => void;
return "watcher-id";
});
@@ -1025,7 +1027,7 @@ describe("RoomListStoreV3", () => {
const store = new RoomListStoreV3Class(dispatcher);
await store.start();
const listsUpdateListener = jest.fn();
const listsUpdateListener = vi.fn();
store.on(LISTS_UPDATE_EVENT, listsUpdateListener);
settingsWatcher();
@@ -1108,7 +1110,7 @@ describe("RoomListStoreV3", () => {
[3, 7].forEach((i) => {
rooms[i].tags[DefaultTagID.Favourite] = {};
});
jest.spyOn(RoomNotificationStateStore.instance, "getRoomState").mockImplementation((room) => {
vi.spyOn(RoomNotificationStateStore.instance, "getRoomState").mockImplementation((room) => {
const state = {
hasUnreadCount: room === rooms[7],
} as unknown as RoomNotificationState;
@@ -1132,7 +1134,7 @@ describe("RoomListStoreV3", () => {
// Mark room 3 as favourite; it's the only unread room
rooms[3].tags[DefaultTagID.Favourite] = {};
jest.spyOn(RoomNotificationStateStore.instance, "getRoomState").mockImplementation((room) => {
vi.spyOn(RoomNotificationStateStore.instance, "getRoomState").mockImplementation((room) => {
const state = {
hasUnreadCount: room === rooms[3],
} as unknown as RoomNotificationState;
@@ -1174,11 +1176,11 @@ describe("RoomListStoreV3", () => {
const spaceRoomId = "!space1:matrix.org";
const inSpaceIds = [3, 10, 20].map((i) => rooms[i].roomId);
jest.spyOn(SDKContextClass.instance.spaceStore, "isRoomInSpace").mockImplementation((space, id) => {
vi.spyOn(SDKContextClass.instance.spaceStore, "isRoomInSpace").mockImplementation((space, id) => {
if (space === spaceRoomId && inSpaceIds.includes(id)) return true;
return false;
});
jest.spyOn(SDKContextClass.instance.spaceStore, "activeSpace", "get").mockImplementation(() => spaceRoomId);
vi.spyOn(SDKContextClass.instance.spaceStore, "activeSpace", "get").mockImplementation(() => spaceRoomId);
const store = new RoomListStoreV3Class(dispatcher);
await store.start();
@@ -1205,12 +1207,12 @@ describe("RoomListStoreV3", () => {
it("emits SECTION_CREATED_EVENT and LISTS_UPDATE_EVENT when section is created", async () => {
enableSections();
getClientAndRooms();
jest.spyOn(sectionModule, "createSection").mockResolvedValue("element.io.section.test-tag");
vi.spyOn(sectionModule, "createSection").mockResolvedValue("element.io.section.test-tag");
const store = new RoomListStoreV3Class(dispatcher);
await store.start();
const sectionCreatedListener = jest.fn();
const sectionCreatedListener = vi.fn();
store.on(SECTION_CREATED_EVENT, sectionCreatedListener);
const tag = await store.createSection();
@@ -1222,12 +1224,12 @@ describe("RoomListStoreV3", () => {
it("does not emit when section creation is cancelled", async () => {
enableSections();
getClientAndRooms();
jest.spyOn(sectionModule, "createSection").mockResolvedValue(undefined);
vi.spyOn(sectionModule, "createSection").mockResolvedValue(undefined);
const store = new RoomListStoreV3Class(dispatcher);
await store.start();
const sectionCreatedListener = jest.fn();
const sectionCreatedListener = vi.fn();
store.on(SECTION_CREATED_EVENT, sectionCreatedListener);
await store.createSection();
@@ -1240,7 +1242,7 @@ describe("RoomListStoreV3", () => {
it("delegates to the section module", async () => {
enableSections();
getClientAndRooms();
const editSectionSpy = jest.spyOn(sectionModule, "editSection").mockResolvedValue(undefined);
const editSectionSpy = vi.spyOn(sectionModule, "editSection").mockResolvedValue(undefined);
const store = new RoomListStoreV3Class(dispatcher);
await store.start();
@@ -1254,12 +1256,12 @@ describe("RoomListStoreV3", () => {
it("delegates to the section module and emits LISTS_UPDATE_EVENT", async () => {
enableSections();
getClientAndRooms();
jest.spyOn(sectionModule, "deleteSection").mockResolvedValue(undefined);
vi.spyOn(sectionModule, "deleteSection").mockResolvedValue(undefined);
const store = new RoomListStoreV3Class(dispatcher);
await store.start();
const listsUpdateListener = jest.fn();
const listsUpdateListener = vi.fn();
store.on(LISTS_UPDATE_EVENT, listsUpdateListener);
await store.removeSection("element.io.section.test-tag", false);
@@ -1273,14 +1275,14 @@ describe("RoomListStoreV3", () => {
const { rooms } = getClientAndRooms();
let settingsWatcher: (settingName: string) => void = () => {};
jest.spyOn(SettingsStore, "watchSetting").mockImplementation((settingName, _roomId, callback) => {
vi.spyOn(SettingsStore, "watchSetting").mockImplementation((settingName, _roomId, callback) => {
if (settingName === "RoomList.OrderedCustomSections") settingsWatcher = callback as () => void;
return "watcher-id";
});
const customTag = "element.io.section.custom";
jest.spyOn(SettingsStore, "getValue").mockImplementation((setting: string) => {
vi.spyOn(SettingsStore, "getValue").mockImplementation((setting: string) => {
if (setting === "RoomList.showSections") return true;
if (setting === "RoomList.OrderedCustomSections") return [];
if (setting === "RoomList.CustomSectionData") return {};
@@ -1295,7 +1297,7 @@ describe("RoomListStoreV3", () => {
// Mark a room with the custom tag and update the settings
rooms[0].tags = { [customTag]: { order: 0 } };
jest.spyOn(SettingsStore, "getValue").mockImplementation((setting: string) => {
vi.spyOn(SettingsStore, "getValue").mockImplementation((setting: string) => {
if (setting === "RoomList.showSections") return true;
if (setting === "RoomList.OrderedCustomSections") return [customTag];
if (setting === "RoomList.CustomSectionData")
@@ -1321,15 +1323,15 @@ describe("RoomListStoreV3", () => {
// Let's say that rooms 34, 84, 64, 14, 57 are muted
const mutedIndices = [34, 84, 64, 14, 57];
const mutedRooms = mutedIndices.map((i) => rooms[i]);
jest.spyOn(RoomNotificationStateStore.instance, "getRoomState").mockImplementation((room) => {
vi.spyOn(RoomNotificationStateStore.instance, "getRoomState").mockImplementation((room) => {
const state = {
muted: mutedRooms.includes(room),
} as unknown as RoomNotificationState;
return state;
});
client.getVisibleRooms = jest.fn().mockReturnValue(rooms);
jest.spyOn(AsyncStoreWithClient.prototype, "matrixClient", "get").mockReturnValue(client);
client.getVisibleRooms = vi.fn().mockReturnValue(rooms);
vi.spyOn(AsyncStoreWithClient.prototype, "matrixClient", "get").mockReturnValue(client);
const store = new RoomListStoreV3Class(dispatcher);
await store.start();
return { client, rooms, mutedIndices, mutedRooms, store, dispatcher };
@@ -1350,7 +1352,7 @@ describe("RoomListStoreV3", () => {
let ts = 1000;
for (const room of [rooms[14], rooms[34]]) {
const event = mkMessage({ room: room.roomId, user: `@foo3:matrix.org`, ts: 1000, event: true });
jest.spyOn(room.getLiveTimeline(), "getEvents").mockReturnValue([event]);
vi.spyOn(room.getLiveTimeline(), "getEvents").mockReturnValue([event]);
const payload = {
action: "MatrixActions.Room.timeline",
@@ -1375,8 +1377,8 @@ describe("RoomListStoreV3", () => {
// Let's say that muted room 64 becomes un-muted.
const unmutedRoom = rooms[64];
jest.spyOn(utilsRLS, "getChangedOverrideRoomMutePushRules").mockImplementation(() => [unmutedRoom.roomId]);
client.getRoom = jest.fn().mockReturnValue(unmutedRoom);
vi.spyOn(utilsRLS, "getChangedOverrideRoomMutePushRules").mockImplementation(() => [unmutedRoom.roomId]);
client.getRoom = vi.fn().mockReturnValue(unmutedRoom);
const payload = {
action: "MatrixActions.accountData",
event_type: EventType.PushRules,
@@ -1407,15 +1409,15 @@ describe("RoomListStoreV3", () => {
// Let's say that rooms 14, 57, 65, 78, 82, 5, 36 are muted
const mutedIndices = [14, 57, 65, 78, 82, 5, 36];
const mutedRooms = mutedIndices.map((i) => rooms[i]);
jest.spyOn(RoomNotificationStateStore.instance, "getRoomState").mockImplementation((room) => {
vi.spyOn(RoomNotificationStateStore.instance, "getRoomState").mockImplementation((room) => {
const state = {
muted: mutedRooms.includes(room),
} as unknown as RoomNotificationState;
return state;
});
client.getVisibleRooms = jest.fn().mockReturnValue(rooms);
jest.spyOn(AsyncStoreWithClient.prototype, "matrixClient", "get").mockReturnValue(client);
client.getVisibleRooms = vi.fn().mockReturnValue(rooms);
vi.spyOn(AsyncStoreWithClient.prototype, "matrixClient", "get").mockReturnValue(client);
const store = new RoomListStoreV3Class(dispatcher);
await store.start();
@@ -5,17 +5,19 @@
* Please see LICENSE files in the repository root for full details.
*/
import { mocked } from "jest-mock";
// @vitest-environment happy-dom
import { describe, it, expect, beforeEach, vi } from "vitest";
import { type MatrixClient } from "matrix-js-sdk/src/matrix";
import { createTestClient, mkRoom, mkSpace } from "test-utils";
import { RoomListCustomisations } from "../../../../src/customisations/RoomList";
import { isRoomVisible } from "../../../../src/stores/room-list-v3/isRoomVisible";
import { createTestClient, mkRoom, mkSpace } from "../../../test-utils";
import { LOCAL_ROOM_ID_PREFIX, LocalRoom } from "../../../../src/models/LocalRoom";
import { RoomListCustomisations } from "../../customisations/RoomList";
import { isRoomVisible } from "./isRoomVisible";
import { LOCAL_ROOM_ID_PREFIX, LocalRoom } from "../../models/LocalRoom";
jest.mock("../../../../src/customisations/RoomList", () => ({
vi.mock("../../customisations/RoomList", () => ({
RoomListCustomisations: {
isRoomVisible: jest.fn(),
isRoomVisible: vi.fn(),
},
}));
@@ -43,14 +45,14 @@ describe("isRoomVisible", () => {
});
it("should return false if visibility customisation returns false", () => {
mocked(RoomListCustomisations.isRoomVisible!).mockReturnValue(false);
vi.mocked(RoomListCustomisations.isRoomVisible!).mockReturnValue(false);
const room = mkRoom(matrixClient, "test-room");
expect(isRoomVisible(room)).toBe(false);
expect(RoomListCustomisations.isRoomVisible!).toHaveBeenCalledWith(room);
});
it("should return true if visibility customisation returns true", () => {
mocked(RoomListCustomisations.isRoomVisible!).mockReturnValue(true);
vi.mocked(RoomListCustomisations.isRoomVisible!).mockReturnValue(true);
const room = mkRoom(matrixClient, "test-room");
expect(isRoomVisible(room)).toBe(true);
expect(RoomListCustomisations.isRoomVisible).toHaveBeenCalledWith(room);
@@ -5,10 +5,13 @@
* Please see LICENSE files in the repository root for full details.
*/
// @vitest-environment happy-dom
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { type Room } from "matrix-js-sdk/src/matrix";
import Modal from "../../../../src/Modal";
import SettingsStore from "../../../../src/settings/SettingsStore";
import Modal from "../../Modal";
import SettingsStore from "../../settings/SettingsStore";
import {
createSection,
editSection,
@@ -22,17 +25,17 @@ import {
CUSTOM_SECTION_TAG_PREFIX,
isSectionTag,
reorderSection,
} from "../../../../src/stores/room-list-v3/section";
import { SettingLevel } from "../../../../src/settings/SettingLevel";
import { CreateSectionDialog } from "../../../../src/components/views/dialogs/CreateSectionDialog";
import { RemoveSectionDialog } from "../../../../src/components/views/dialogs/RemoveSectionDialog";
import { DefaultTagID } from "../../../../src/stores/room-list-v3/skip-list/tag";
import { MetaSpace } from "../../../../src/stores/spaces";
import { SDKContextClass } from "../../../../src/contexts/SDKContextClass.ts";
} from "./section";
import { SettingLevel } from "../../settings/SettingLevel";
import { CreateSectionDialog } from "../../components/views/dialogs/CreateSectionDialog";
import { RemoveSectionDialog } from "../../components/views/dialogs/RemoveSectionDialog";
import { DefaultTagID } from "./skip-list/tag";
import { MetaSpace } from "../spaces";
import { SDKContextClass } from "../../contexts/SDKContextClass.ts";
describe("section", () => {
afterEach(() => {
jest.restoreAllMocks();
vi.restoreAllMocks();
});
describe("getCustomSectionData", () => {
@@ -42,17 +45,17 @@ describe("section", () => {
beforeEach(() => {
// Default: no known spaces
jest.spyOn(SDKContextClass.instance.spaceStore, "enabledMetaSpaces", "get").mockReturnValue([]);
jest.spyOn(SDKContextClass.instance.spaceStore, "spacePanelSpaces", "get").mockReturnValue([]);
vi.spyOn(SDKContextClass.instance.spaceStore, "enabledMetaSpaces", "get").mockReturnValue([]);
vi.spyOn(SDKContextClass.instance.spaceStore, "spacePanelSpaces", "get").mockReturnValue([]);
});
it.each([null, false, 42, "string", []] as const)("returns an empty object when the raw value is %p", (raw) => {
jest.spyOn(SettingsStore, "getValue").mockReturnValue(raw as any);
vi.spyOn(SettingsStore, "getValue").mockReturnValue(raw as any);
expect(getCustomSectionData()).toEqual({});
});
it("returns valid entries and drops invalid ones, defaulting spaceId to MetaSpace.Home", () => {
jest.spyOn(SettingsStore, "getValue").mockReturnValue({
vi.spyOn(SettingsStore, "getValue").mockReturnValue({
[validTag]: validEntry,
[invalidTag]: { tag: "element.io.section.mismatch", name: "Bad" },
});
@@ -60,7 +63,7 @@ describe("section", () => {
});
it("drops entries that fail the isValidCustomSection check", () => {
jest.spyOn(SettingsStore, "getValue").mockReturnValue({
vi.spyOn(SettingsStore, "getValue").mockReturnValue({
"element.io.section.null-val": null,
"element.io.section.str-val": "not-an-object",
"element.io.section.bad-tag": { tag: "not-a-custom-tag", name: "Bad" },
@@ -70,12 +73,12 @@ describe("section", () => {
});
it("defaults spaceId to MetaSpace.Home when spaceId is missing", () => {
jest.spyOn(SettingsStore, "getValue").mockReturnValue({ [validTag]: validEntry });
vi.spyOn(SettingsStore, "getValue").mockReturnValue({ [validTag]: validEntry });
expect(getCustomSectionData()[validTag].spaceId).toBe(MetaSpace.Home);
});
it("defaults spaceId to MetaSpace.Home when the stored space does not exist", () => {
jest.spyOn(SettingsStore, "getValue").mockReturnValue({
vi.spyOn(SettingsStore, "getValue").mockReturnValue({
[validTag]: { ...validEntry, spaceId: "!gone:server" },
});
// spacePanelSpaces is empty (default mock), so !gone:server is unknown
@@ -83,10 +86,8 @@ describe("section", () => {
});
it("keeps spaceId when the meta-space is enabled", () => {
jest.spyOn(SDKContextClass.instance.spaceStore, "enabledMetaSpaces", "get").mockReturnValue([
MetaSpace.Home,
]);
jest.spyOn(SettingsStore, "getValue").mockReturnValue({
vi.spyOn(SDKContextClass.instance.spaceStore, "enabledMetaSpaces", "get").mockReturnValue([MetaSpace.Home]);
vi.spyOn(SettingsStore, "getValue").mockReturnValue({
[validTag]: { ...validEntry, spaceId: MetaSpace.Home },
});
expect(getCustomSectionData()[validTag].spaceId).toBe(MetaSpace.Home);
@@ -94,10 +95,10 @@ describe("section", () => {
it("keeps spaceId when the real space room exists", () => {
const spaceId = "!space:server";
jest.spyOn(SDKContextClass.instance.spaceStore, "spacePanelSpaces", "get").mockReturnValue([
vi.spyOn(SDKContextClass.instance.spaceStore, "spacePanelSpaces", "get").mockReturnValue([
{ roomId: spaceId } as Room,
]);
jest.spyOn(SettingsStore, "getValue").mockReturnValue({
vi.spyOn(SettingsStore, "getValue").mockReturnValue({
[validTag]: { ...validEntry, spaceId },
});
expect(getCustomSectionData()[validTag].spaceId).toBe(spaceId);
@@ -108,12 +109,12 @@ describe("section", () => {
const tag = "element.io.section.abc";
beforeEach(() => {
jest.spyOn(SDKContextClass.instance.spaceStore, "enabledMetaSpaces", "get").mockReturnValue([]);
jest.spyOn(SDKContextClass.instance.spaceStore, "spacePanelSpaces", "get").mockReturnValue([]);
vi.spyOn(SDKContextClass.instance.spaceStore, "enabledMetaSpaces", "get").mockReturnValue([]);
vi.spyOn(SDKContextClass.instance.spaceStore, "spacePanelSpaces", "get").mockReturnValue([]);
});
it("returns an empty array when the raw value is not an array", () => {
jest.spyOn(SettingsStore, "getValue").mockImplementation((setting) => {
vi.spyOn(SettingsStore, "getValue").mockImplementation((setting) => {
if (setting === "RoomList.OrderedCustomSections") return "not-an-array";
return null;
});
@@ -124,7 +125,7 @@ describe("section", () => {
it("removes unknown sections and saves the cleaned list", () => {
const knownTag = "element.io.section.known";
jest.spyOn(SettingsStore, "getValue").mockImplementation((setting) => {
vi.spyOn(SettingsStore, "getValue").mockImplementation((setting) => {
if (setting === "RoomList.CustomSectionData") return { [knownTag]: { tag: knownTag, name: "Known" } };
if (setting === "RoomList.OrderedCustomSections") return [knownTag, tag];
return null;
@@ -144,7 +145,7 @@ describe("section", () => {
{ value: { [spaceId]: { "other.tag": false } }, result: true },
{ value: { [spaceId]: { [tag]: false } }, result: false },
])("returns the persisted state=$result when value=$value", ({ value, result }) => {
jest.spyOn(SettingsStore, "getValue").mockReturnValue(value);
vi.spyOn(SettingsStore, "getValue").mockReturnValue(value);
expect(isSectionExpanded(spaceId, tag)).toBe(result);
});
});
@@ -154,8 +155,8 @@ describe("section", () => {
const tag = "element.io.section.abc";
it("persists the state at the device level", async () => {
jest.spyOn(SettingsStore, "getValue").mockReturnValue({});
const setValueSpy = jest.spyOn(SettingsStore, "setValue").mockResolvedValue(undefined);
vi.spyOn(SettingsStore, "getValue").mockReturnValue({});
const setValueSpy = vi.spyOn(SettingsStore, "setValue").mockResolvedValue(undefined);
await setSectionExpanded(spaceId, tag, false);
@@ -165,11 +166,11 @@ describe("section", () => {
});
it("merges with existing state for other spaces and tags", async () => {
jest.spyOn(SettingsStore, "getValue").mockReturnValue({
vi.spyOn(SettingsStore, "getValue").mockReturnValue({
"!other:server": { "other.tag": false },
[spaceId]: { "existing.tag": true },
});
const setValueSpy = jest.spyOn(SettingsStore, "setValue").mockResolvedValue(undefined);
const setValueSpy = vi.spyOn(SettingsStore, "setValue").mockResolvedValue(undefined);
await setSectionExpanded(spaceId, tag, false);
@@ -180,8 +181,8 @@ describe("section", () => {
});
it("overwrites the previous state for the same space and tag", async () => {
jest.spyOn(SettingsStore, "getValue").mockReturnValue({ [spaceId]: { [tag]: false } });
const setValueSpy = jest.spyOn(SettingsStore, "setValue").mockResolvedValue(undefined);
vi.spyOn(SettingsStore, "getValue").mockReturnValue({ [spaceId]: { [tag]: false } });
const setValueSpy = vi.spyOn(SettingsStore, "setValue").mockResolvedValue(undefined);
await setSectionExpanded(spaceId, tag, true);
@@ -193,10 +194,10 @@ describe("section", () => {
describe("createSection", () => {
beforeEach(() => {
jest.spyOn(SettingsStore, "getValue").mockReturnValue(null);
jest.spyOn(SettingsStore, "setValue").mockResolvedValue(undefined);
jest.spyOn(SDKContextClass.instance.spaceStore, "enabledMetaSpaces", "get").mockReturnValue([]);
jest.spyOn(SDKContextClass.instance.spaceStore, "spacePanelSpaces", "get").mockReturnValue([]);
vi.spyOn(SettingsStore, "getValue").mockReturnValue(null);
vi.spyOn(SettingsStore, "setValue").mockResolvedValue(undefined);
vi.spyOn(SDKContextClass.instance.spaceStore, "enabledMetaSpaces", "get").mockReturnValue([]);
vi.spyOn(SDKContextClass.instance.spaceStore, "spacePanelSpaces", "get").mockReturnValue([]);
});
it.each([
@@ -204,9 +205,9 @@ describe("section", () => {
[true, "", undefined],
[true, "My Section", expect.stringMatching(/^element\.io\.section\./)],
])("returns %s when shouldCreate=%s and name='%s'", async (shouldCreate, name, expected) => {
jest.spyOn(Modal, "createDialog").mockReturnValue({
vi.spyOn(Modal, "createDialog").mockReturnValue({
finished: Promise.resolve([shouldCreate, name]),
close: jest.fn(),
close: vi.fn(),
} as any);
const result = await createSection(MetaSpace.Home);
@@ -214,9 +215,9 @@ describe("section", () => {
});
it("returns the new tag when section is created", async () => {
jest.spyOn(Modal, "createDialog").mockReturnValue({
vi.spyOn(Modal, "createDialog").mockReturnValue({
finished: Promise.resolve([true, "My Section"]),
close: jest.fn(),
close: vi.fn(),
} as any);
const result = await createSection(MetaSpace.Home);
@@ -224,9 +225,9 @@ describe("section", () => {
});
it("opens the CreateSectionDialog", async () => {
const createDialogSpy = jest.spyOn(Modal, "createDialog").mockReturnValue({
const createDialogSpy = vi.spyOn(Modal, "createDialog").mockReturnValue({
finished: Promise.resolve([false, ""]),
close: jest.fn(),
close: vi.fn(),
} as any);
await createSection(MetaSpace.Home);
@@ -235,17 +236,17 @@ describe("section", () => {
it("saves section data and ordered sections at ACCOUNT level when confirmed", async () => {
const existingTag = "element.io.section.existing";
jest.spyOn(SettingsStore, "getValue").mockImplementation((setting) => {
vi.spyOn(SettingsStore, "getValue").mockImplementation((setting) => {
if (setting === "RoomList.OrderedCustomSections") return [existingTag];
if (setting === "RoomList.CustomSectionData")
return { [existingTag]: { tag: existingTag, name: "Existing" } };
return null;
});
jest.spyOn(Modal, "createDialog").mockReturnValue({
vi.spyOn(Modal, "createDialog").mockReturnValue({
finished: Promise.resolve([true, "My Section"]),
close: jest.fn(),
close: vi.fn(),
} as any);
const setValueSpy = jest.spyOn(SettingsStore, "setValue").mockResolvedValue(undefined);
const setValueSpy = vi.spyOn(SettingsStore, "setValue").mockResolvedValue(undefined);
await createSection(MetaSpace.Home);
@@ -270,28 +271,28 @@ describe("section", () => {
const existingSectionData = { [tag]: { tag, name: "Old Name" } };
beforeEach(() => {
jest.spyOn(SettingsStore, "getValue").mockReturnValue(existingSectionData);
jest.spyOn(SettingsStore, "setValue").mockResolvedValue(undefined);
vi.spyOn(SettingsStore, "getValue").mockReturnValue(existingSectionData);
vi.spyOn(SettingsStore, "setValue").mockResolvedValue(undefined);
});
it("does nothing if the tag is not a custom section tag", async () => {
const createDialogSpy = jest.spyOn(Modal, "createDialog");
const createDialogSpy = vi.spyOn(Modal, "createDialog");
await editSection("m.favourite");
expect(createDialogSpy).not.toHaveBeenCalled();
});
it("does nothing if the section does not exist", async () => {
jest.spyOn(SettingsStore, "getValue").mockReturnValue({});
const createDialogSpy = jest.spyOn(Modal, "createDialog");
vi.spyOn(SettingsStore, "getValue").mockReturnValue({});
const createDialogSpy = vi.spyOn(Modal, "createDialog");
await editSection(tag);
expect(createDialogSpy).not.toHaveBeenCalled();
});
it("opens the CreateSectionDialog with the current section name", async () => {
const createDialogSpy = jest.spyOn(Modal, "createDialog").mockReturnValue({
const createDialogSpy = vi.spyOn(Modal, "createDialog").mockReturnValue({
finished: Promise.resolve([false, ""]),
close: jest.fn(),
close: vi.fn(),
} as any);
await editSection(tag);
@@ -303,22 +304,22 @@ describe("section", () => {
[true, ""],
[true, "Old Name"],
])("does not save when shouldEdit=%s and name='%s'", async (shouldEdit, name) => {
jest.spyOn(Modal, "createDialog").mockReturnValue({
vi.spyOn(Modal, "createDialog").mockReturnValue({
finished: Promise.resolve([shouldEdit, name]),
close: jest.fn(),
close: vi.fn(),
} as any);
const setValueSpy = jest.spyOn(SettingsStore, "setValue").mockResolvedValue(undefined);
const setValueSpy = vi.spyOn(SettingsStore, "setValue").mockResolvedValue(undefined);
await editSection(tag);
expect(setValueSpy).not.toHaveBeenCalled();
});
it("saves the new name when confirmed with a different name", async () => {
jest.spyOn(Modal, "createDialog").mockReturnValue({
vi.spyOn(Modal, "createDialog").mockReturnValue({
finished: Promise.resolve([true, "New Name"]),
close: jest.fn(),
close: vi.fn(),
} as any);
const setValueSpy = jest.spyOn(SettingsStore, "setValue").mockResolvedValue(undefined);
const setValueSpy = vi.spyOn(SettingsStore, "setValue").mockResolvedValue(undefined);
await editSection(tag);
@@ -336,24 +337,24 @@ describe("section", () => {
const otherTag = "element.io.section.other";
beforeEach(() => {
jest.spyOn(SettingsStore, "getValue").mockImplementation((setting) => {
vi.spyOn(SettingsStore, "getValue").mockImplementation((setting) => {
if (setting === "RoomList.CustomSectionData")
return { [tag]: { tag, name: "My Section" }, [otherTag]: { tag: otherTag, name: "Other Section" } };
if (setting === "RoomList.OrderedCustomSections") return [otherTag, tag];
return null;
});
jest.spyOn(SettingsStore, "setValue").mockResolvedValue(undefined);
vi.spyOn(SettingsStore, "setValue").mockResolvedValue(undefined);
});
it("does nothing if the tag is not a custom section tag", async () => {
const createDialogSpy = jest.spyOn(Modal, "createDialog");
const createDialogSpy = vi.spyOn(Modal, "createDialog");
await deleteSection("m.favourite", false);
expect(createDialogSpy).not.toHaveBeenCalled();
});
it("does nothing if the section does not exist", async () => {
jest.spyOn(SettingsStore, "getValue").mockReturnValue({});
const createDialogSpy = jest.spyOn(Modal, "createDialog");
vi.spyOn(SettingsStore, "getValue").mockReturnValue({});
const createDialogSpy = vi.spyOn(Modal, "createDialog");
await deleteSection(tag, false);
expect(createDialogSpy).not.toHaveBeenCalled();
@@ -363,9 +364,9 @@ describe("section", () => {
[true, "empty"],
[false, "non-empty"],
])("opens the RemoveSectionDialog with isEmpty=%s for %s section", async (isEmpty) => {
const createDialogSpy = jest.spyOn(Modal, "createDialog").mockReturnValue({
const createDialogSpy = vi.spyOn(Modal, "createDialog").mockReturnValue({
finished: Promise.resolve([false]),
close: jest.fn(),
close: vi.fn(),
} as any);
await deleteSection(tag, isEmpty);
@@ -373,22 +374,22 @@ describe("section", () => {
});
it("does not save when user cancels", async () => {
jest.spyOn(Modal, "createDialog").mockReturnValue({
vi.spyOn(Modal, "createDialog").mockReturnValue({
finished: Promise.resolve([false]),
close: jest.fn(),
close: vi.fn(),
} as any);
const setValueSpy = jest.spyOn(SettingsStore, "setValue").mockResolvedValue(undefined);
const setValueSpy = vi.spyOn(SettingsStore, "setValue").mockResolvedValue(undefined);
await deleteSection(tag, false);
expect(setValueSpy).not.toHaveBeenCalled();
});
it("removes the section from ordered list and section data when confirmed", async () => {
jest.spyOn(Modal, "createDialog").mockReturnValue({
vi.spyOn(Modal, "createDialog").mockReturnValue({
finished: Promise.resolve([true]),
close: jest.fn(),
close: vi.fn(),
} as any);
const setValueSpy = jest.spyOn(SettingsStore, "setValue").mockResolvedValue(undefined);
const setValueSpy = vi.spyOn(SettingsStore, "setValue").mockResolvedValue(undefined);
await deleteSection(tag, false);
@@ -409,7 +410,7 @@ describe("section", () => {
orderedTags: string[],
customData: Record<string, { tag: string; name: string }> = {},
): void {
jest.spyOn(SettingsStore, "getValue").mockImplementation((setting) => {
vi.spyOn(SettingsStore, "getValue").mockImplementation((setting) => {
if (setting === "RoomList.OrderedCustomSections") return orderedTags;
if (setting === "RoomList.CustomSectionData") return customData;
return null;
@@ -472,7 +473,7 @@ describe("section", () => {
"moves $description and saves the new order at ACCOUNT level",
async ({ initial, customData, source, target, expected }) => {
mockSettings(initial, customData);
const setValueSpy = jest.spyOn(SettingsStore, "setValue").mockResolvedValue(undefined);
const setValueSpy = vi.spyOn(SettingsStore, "setValue").mockResolvedValue(undefined);
await reorderSection(source, target);
@@ -508,7 +509,7 @@ describe("section", () => {
},
])("does nothing when $description", async ({ source, target }) => {
mockSettings([customTag], { [customTag]: { tag: customTag, name: "A" } });
const setValueSpy = jest.spyOn(SettingsStore, "setValue").mockResolvedValue(undefined);
const setValueSpy = vi.spyOn(SettingsStore, "setValue").mockResolvedValue(undefined);
await reorderSection(source, target);
@@ -5,22 +5,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.
*/
// @vitest-environment happy-dom
import { describe, it, expect, beforeEach, vi } from "vitest";
import { shuffle } from "lodash";
import { mkMessage, stubClient } from "test-utils";
import type { Room } from "matrix-js-sdk/src/matrix";
import type { Sorter } from "../../../../../src/stores/room-list-v3/skip-list/sorters";
import type { RoomNotificationState } from "../../../../../src/stores/notifications/RoomNotificationState";
import { mkMessage, stubClient } from "../../../../test-utils";
import { RoomSkipList } from "../../../../../src/stores/room-list-v3/skip-list/RoomSkipList";
import { RecencySorter } from "../../../../../src/stores/room-list-v3/skip-list/sorters/RecencySorter";
import { AlphabeticSorter } from "../../../../../src/stores/room-list-v3/skip-list/sorters/AlphabeticSorter";
import { getMockedRooms } from "./getMockedRooms";
import { MetaSpace } from "../../../../../src/stores/spaces";
import { RoomNotificationStateStore } from "../../../../../src/stores/notifications/RoomNotificationStateStore";
import { FavouriteFilter } from "../../../../../src/stores/room-list-v3/skip-list/filters/FavouriteFilter";
import { FilterEnum } from "../../../../../src/stores/room-list-v3/skip-list/filters";
import { DefaultTagID } from "../../../../../src/stores/room-list-v3/skip-list/tag";
import { SDKContextClass } from "../../../../../src/contexts/SDKContextClass.ts";
import type { Sorter } from "./sorters";
import type { RoomNotificationState } from "../../notifications/RoomNotificationState";
import { RoomSkipList } from "./RoomSkipList";
import { RecencySorter } from "./sorters/RecencySorter";
import { AlphabeticSorter } from "./sorters/AlphabeticSorter";
import { getMockedRooms } from "./__mocks__";
import { MetaSpace } from "../../spaces";
import { RoomNotificationStateStore } from "../../notifications/RoomNotificationStateStore";
import { FavouriteFilter } from "./filters/FavouriteFilter";
import { FilterEnum } from "./filters";
import { DefaultTagID } from "./tag";
import { SDKContextClass } from "../../../contexts/SDKContextClass.ts";
describe("RoomSkipList", () => {
function generateSkipList(roomCount?: number): {
@@ -38,14 +41,14 @@ describe("RoomSkipList", () => {
}
beforeEach(() => {
jest.spyOn(SDKContextClass.instance.spaceStore, "isRoomInSpace").mockImplementation(
vi.spyOn(SDKContextClass.instance.spaceStore, "isRoomInSpace").mockImplementation(
(space) => space === MetaSpace.Home,
);
jest.spyOn(SDKContextClass.instance.spaceStore, "activeSpace", "get").mockImplementation(() => MetaSpace.Home);
jest.spyOn(SDKContextClass.instance.spaceStore, "storeReadyPromise", "get").mockImplementation(() =>
vi.spyOn(SDKContextClass.instance.spaceStore, "activeSpace", "get").mockImplementation(() => MetaSpace.Home);
vi.spyOn(SDKContextClass.instance.spaceStore, "storeReadyPromise", "get").mockImplementation(() =>
Promise.resolve(),
);
jest.spyOn(RoomNotificationStateStore.instance, "getRoomState").mockImplementation(() => {
vi.spyOn(RoomNotificationStateStore.instance, "getRoomState").mockImplementation(() => {
const state = {
mute: false,
} as unknown as RoomNotificationState;
@@ -90,7 +93,7 @@ describe("RoomSkipList", () => {
ts: totalRooms - i,
event: true,
});
jest.spyOn(room.getLiveTimeline(), "getEvents").mockReturnValue([event]);
vi.spyOn(room.getLiveTimeline(), "getEvents").mockReturnValue([event]);
skipList.reInsertRoom(room);
expect(skipList.size).toEqual(rooms.length);
}
@@ -6,8 +6,8 @@ Please see LICENSE files in the repository root for full details.
*/
import type { MatrixClient, Room } from "matrix-js-sdk/src/matrix";
import { mkMessage, mkStubRoom } from "../../../../test-utils";
import { vi } from "../../../../setup/adapter.ts";
import { vi } from "vitest";
import { mkMessage, mkStubRoom } from "test-utils";
export function getMockedRooms(client: MatrixClient, roomCount: number = 100): Room[] {
const rooms: Room[] = [];
@@ -5,18 +5,21 @@ 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.
*/
import { KnownMembership } from "matrix-js-sdk/src/types";
// @vitest-environment happy-dom
import { stubClient } from "../../../../../test-utils";
import { getMockedRooms } from "../getMockedRooms";
import { CallStore } from "../../../../../../src/stores/CallStore";
import type { Call } from "../../../../../../src/models/Call";
import { DefaultTagID } from "../../../../../../src/stores/room-list-v3/skip-list/tag";
import { RoomNotificationStateStore } from "../../../../../../src/stores/notifications/RoomNotificationStateStore";
import type { RoomNotificationState } from "../../../../../../src/stores/notifications/RoomNotificationState";
import * as utils from "../../../../../../src/utils/notifications";
import { UnreadSorter } from "../../../../../../src/stores/room-list-v3/skip-list/sorters/UnreadSorter";
import { NotificationLevel } from "../../../../../../src/stores/notifications/NotificationLevel";
import { describe, it, expect, vi } from "vitest";
import { KnownMembership } from "matrix-js-sdk/src/types";
import { stubClient } from "test-utils";
import { getMockedRooms } from "../__mocks__";
import { CallStore } from "../../../CallStore";
import type { Call } from "../../../../models/Call";
import { DefaultTagID } from "../tag";
import { RoomNotificationStateStore } from "../../../notifications/RoomNotificationStateStore";
import type { RoomNotificationState } from "../../../notifications/RoomNotificationState";
import * as utils from "../../../../utils/notifications";
import { UnreadSorter } from "./UnreadSorter";
import { NotificationLevel } from "../../../notifications/NotificationLevel";
describe("UnreadSorter", () => {
it("should sort correctly", () => {
@@ -27,12 +30,12 @@ describe("UnreadSorter", () => {
// Let's make rooms 23, 67, 53, 5 invites
const inviteRooms = [23, 67, 53, 5].map((i) => rooms[i]);
for (const room of inviteRooms) {
room.getMyMembership = jest.fn().mockReturnValue(KnownMembership.Invite);
room.getMyMembership = vi.fn().mockReturnValue(KnownMembership.Invite);
}
// Let's make rooms 66, 10, 78 have calls
const callRooms = [66, 10, 78].map((i) => rooms[i]);
jest.spyOn(CallStore.instance, "getCall").mockImplementation((roomId) => {
vi.spyOn(CallStore.instance, "getCall").mockImplementation((roomId) => {
if (callRooms.map((r) => r.roomId).includes(roomId)) {
// We don't really care about the call object
return true as unknown as Call;
@@ -48,7 +51,7 @@ describe("UnreadSorter", () => {
// Let's make 98, 80, 49, 24 muted rooms
const mutedRooms = [98, 80, 49, 24].map((i) => rooms[i]);
jest.spyOn(RoomNotificationStateStore.instance, "getRoomState").mockImplementation((room) => {
vi.spyOn(RoomNotificationStateStore.instance, "getRoomState").mockImplementation((room) => {
const isMention = mentionRooms.includes(room);
const hasUnreadCount = unreadRooms.includes(room);
const isActivityNotification = dotRooms.includes(room);
@@ -65,7 +68,7 @@ describe("UnreadSorter", () => {
// Let's make 28, 25 as rooms that are marked as unread
const markedAsUnreadRooms = [28, 25].map((i) => rooms[i]);
jest.spyOn(utils, "getMarkedUnreadState").mockImplementation((room) => markedAsUnreadRooms.includes(room));
vi.spyOn(utils, "getMarkedUnreadState").mockImplementation((room) => markedAsUnreadRooms.includes(room));
// Let's make 6, 48, 76, low priority rooms
const lowPriorityRooms = [6, 48, 76].map((i) => rooms[i]);
@@ -5,11 +5,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.
*/
// @vitest-environment happy-dom
import { describe, it, expect, vi } from "vitest";
import { Room, type RoomState } from "matrix-js-sdk/src/matrix";
import { KnownMembership } from "matrix-js-sdk/src/types";
import { mkEvent, mkMessage, mkRoom, stubClient } from "test-utils";
import { mkEvent, mkMessage, mkRoom, stubClient } from "../../../../../test-utils";
import { getLastTimestamp } from "../../../../../../src/stores/room-list-v3/skip-list/sorters/utils/getLastTimestamp";
import { getLastTimestamp } from "./getLastTimestamp";
describe("getLastTimestamp", () => {
it("should return last timestamp", () => {
@@ -47,7 +50,7 @@ describe("getLastTimestamp", () => {
const cli = stubClient();
const room = mkRoom(cli, "!new:example.org");
// Mock a membership event
jest.spyOn(room.getLiveTimeline(), "getState").mockImplementation((_) => {
vi.spyOn(room.getLiveTimeline(), "getState").mockImplementation((_) => {
return {
getStateEvents: () =>
mkEvent({
@@ -59,7 +62,7 @@ describe("getLastTimestamp", () => {
}),
} as unknown as RoomState;
});
jest.spyOn(room, "getMyMembership").mockReturnValue(KnownMembership.Invite);
vi.spyOn(room, "getMyMembership").mockReturnValue(KnownMembership.Invite);
expect(getLastTimestamp(room, "@john:matrix.org")).toBe(500);
});
@@ -82,8 +85,8 @@ describe("getLastTimestamp", () => {
event: true,
});
jest.spyOn(room, "getMyMembership").mockReturnValue(KnownMembership.Join);
jest.spyOn(room, "getBumpStamp").mockReturnValue(314);
vi.spyOn(room, "getMyMembership").mockReturnValue(KnownMembership.Join);
vi.spyOn(room, "getBumpStamp").mockReturnValue(314);
room.addLiveEvents([event1, event2], { addToState: true });
expect(getLastTimestamp(room, "@john:matrix.org")).toBe(314);
});
@@ -114,7 +117,7 @@ describe("getLastTimestamp", () => {
event: true,
});
jest.spyOn(room, "getMyMembership").mockReturnValue(KnownMembership.Join);
vi.spyOn(room, "getMyMembership").mockReturnValue(KnownMembership.Join);
room.addLiveEvents([event1, event2], { addToState: true });
expect(getLastTimestamp(room, "@john:matrix.org")).toBe(400);
@@ -145,7 +148,7 @@ describe("getLastTimestamp", () => {
event: true,
});
jest.spyOn(room, "getMyMembership").mockReturnValue(KnownMembership.Join);
vi.spyOn(room, "getMyMembership").mockReturnValue(KnownMembership.Join);
room.addLiveEvents([event1, event2], { addToState: true });
expect(getLastTimestamp(room, "@john:matrix.org")).toBe(5);
@@ -176,7 +179,7 @@ describe("getLastTimestamp", () => {
event: true,
});
jest.spyOn(room, "getMyMembership").mockReturnValue(KnownMembership.Join);
vi.spyOn(room, "getMyMembership").mockReturnValue(KnownMembership.Join);
room.addLiveEvents([event1, event2], { addToState: true });
expect(getLastTimestamp(room, "@john:matrix.org")).toBe(5);
@@ -6,10 +6,13 @@ 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.
*/
import { ConditionKind, EventType, type IPushRule, MatrixEvent, PushRuleActionName } from "matrix-js-sdk/src/matrix";
// @vitest-environment happy-dom
import { getChangedOverrideRoomMutePushRules } from "../../../../src/stores/room-list-v3/utils";
import { DEFAULT_PUSH_RULES, getDefaultRuleWithKind, makePushRule } from "../../../test-utils/pushRules";
import { describe, it, expect } from "vitest";
import { ConditionKind, EventType, type IPushRule, MatrixEvent, PushRuleActionName } from "matrix-js-sdk/src/matrix";
import { DEFAULT_PUSH_RULES, getDefaultRuleWithKind, makePushRule } from "test-utils/pushRules";
import { getChangedOverrideRoomMutePushRules } from "./utils";
describe("getChangedOverrideRoomMutePushRules()", () => {
const makePushRulesEvent = (overrideRules: IPushRule[] = []): MatrixEvent => {
@@ -6,8 +6,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.
*/
import { mocked, type MockedObject } from "jest-mock";
import fetchMock from "@fetch-mock/jest";
// @vitest-environment happy-dom
import { vi, describe, it, expect, beforeEach, type Mock, type MockedObject } from "vitest";
import fetchMock from "@fetch-mock/vitest";
import {
type MatrixClient,
ClientEvent,
@@ -34,18 +36,18 @@ import {
type CapabilitiesOpts,
WidgetLifecycle,
} from "@matrix-org/react-sdk-module-api/lib/lifecycles/WidgetLifecycle";
import { mkEvent, stubClient } from "test-utils";
import { SDKContextClass } from "../../../../src/contexts/SDKContextClass";
import { MatrixClientPeg } from "../../../../src/MatrixClientPeg";
import { ElementWidgetDriver } from "../../../../src/stores/widgets/ElementWidgetDriver";
import { mkEvent, stubClient } from "../../../test-utils";
import { ModuleRunner } from "../../../../src/modules/ModuleRunner";
import { ModuleApi } from "../../../../src/modules/Api";
import dis from "../../../../src/dispatcher/dispatcher";
import Modal from "../../../../src/Modal";
import SettingsStore from "../../../../src/settings/SettingsStore";
import { WidgetType } from "../../../../src/widgets/WidgetType.ts";
import SdkConfig from "../../../../src/SdkConfig.ts";
import { SDKContextClass } from "../../contexts/SDKContextClass";
import { MatrixClientPeg } from "../../MatrixClientPeg";
import { ElementWidgetDriver } from "./ElementWidgetDriver";
import { ModuleRunner } from "../../modules/ModuleRunner";
import { ModuleApi } from "../../modules/Api";
import dis from "../../dispatcher/dispatcher";
import Modal from "../../Modal";
import SettingsStore from "../../settings/SettingsStore";
import { WidgetType } from "../../widgets/WidgetType";
import SdkConfig from "../../SdkConfig";
describe("ElementWidgetDriver", () => {
let client: MockedObject<MatrixClient>;
@@ -63,15 +65,15 @@ describe("ElementWidgetDriver", () => {
"!1:example.org",
);
jest.spyOn(Modal, "createDialog").mockImplementation(() => {
vi.spyOn(Modal, "createDialog").mockImplementation(() => {
throw new Error("Should not have to create a dialog");
});
beforeEach(() => {
stubClient();
client = mocked(MatrixClientPeg.safeGet());
client = vi.mocked(MatrixClientPeg.safeGet());
client.cachedRtcTransports = {
wait: jest.fn(),
wait: vi.fn(),
} as any;
client.getUserId.mockReturnValue("@alice:example.org");
client.getSafeUserId.mockReturnValue("@alice:example.org");
@@ -162,13 +164,11 @@ describe("ElementWidgetDriver", () => {
const requestedCapabilities = new Set(["org.matrix.msc2931.navigate", "org.matrix.msc2762.timeline:*"]);
jest.spyOn(ModuleRunner.instance, "invoke").mockImplementation(
(lifecycleEvent, opts, widgetInfo, requested) => {
if (lifecycleEvent === WidgetLifecycle.CapabilitiesRequest) {
(opts as CapabilitiesOpts).approvedCapabilities = requested;
}
},
);
vi.spyOn(ModuleRunner.instance, "invoke").mockImplementation((lifecycleEvent, opts, widgetInfo, requested) => {
if (lifecycleEvent === WidgetLifecycle.CapabilitiesRequest) {
(opts as CapabilitiesOpts).approvedCapabilities = requested;
}
});
const approvedCapabilities = await driver.validateCapabilities(requestedCapabilities);
expect(approvedCapabilities).toEqual(requestedCapabilities);
@@ -177,13 +177,13 @@ describe("ElementWidgetDriver", () => {
it("approves identity via module api", async () => {
const driver = mkDefaultDriver();
jest.spyOn(ModuleRunner.instance, "invoke").mockImplementation((lifecycleEvent, opts, widgetInfo) => {
vi.spyOn(ModuleRunner.instance, "invoke").mockImplementation((lifecycleEvent, opts, widgetInfo) => {
if (lifecycleEvent === WidgetLifecycle.IdentityRequest) {
(opts as ApprovalOpts).approved = true;
}
});
const listener = jest.fn();
const listener = vi.fn();
const observer = new SimpleObservable<IOpenIDUpdate>();
observer.onUpdate(listener);
await driver.askOpenID(observer);
@@ -200,9 +200,7 @@ describe("ElementWidgetDriver", () => {
const requestedCapabilities = new Set(["org.matrix.msc2931.navigate", "org.matrix.msc2762.timeline:*"]);
jest.spyOn(ModuleApi.instance.widgetLifecycle, "preapproveCapabilities").mockResolvedValue(
requestedCapabilities,
);
vi.spyOn(ModuleApi.instance.widgetLifecycle, "preapproveCapabilities").mockResolvedValue(requestedCapabilities);
const approvedCapabilities = await driver.validateCapabilities(requestedCapabilities);
expect(approvedCapabilities).toEqual(requestedCapabilities);
@@ -213,14 +211,12 @@ describe("ElementWidgetDriver", () => {
const requestedCapabilities = new Set(["org.matrix.msc2931.navigate", "org.matrix.msc2762.timeline:*"]);
jest.spyOn(ModuleApi.instance.widgetLifecycle, "preapproveCapabilities").mockResolvedValue(undefined);
jest.spyOn(ModuleRunner.instance, "invoke").mockImplementation(
(lifecycleEvent, opts, widgetInfo, requested) => {
if (lifecycleEvent === WidgetLifecycle.CapabilitiesRequest) {
(opts as CapabilitiesOpts).approvedCapabilities = requested;
}
},
);
vi.spyOn(ModuleApi.instance.widgetLifecycle, "preapproveCapabilities").mockResolvedValue(undefined);
vi.spyOn(ModuleRunner.instance, "invoke").mockImplementation((lifecycleEvent, opts, widgetInfo, requested) => {
if (lifecycleEvent === WidgetLifecycle.CapabilitiesRequest) {
(opts as CapabilitiesOpts).approvedCapabilities = requested;
}
});
const approvedCapabilities = await driver.validateCapabilities(requestedCapabilities);
expect(approvedCapabilities).toEqual(requestedCapabilities);
@@ -229,9 +225,9 @@ describe("ElementWidgetDriver", () => {
it("approves identity via new widget lifecycle API", async () => {
const driver = mkDefaultDriver();
jest.spyOn(ModuleApi.instance.widgetLifecycle, "preapproveIdentity").mockResolvedValue(true);
vi.spyOn(ModuleApi.instance.widgetLifecycle, "preapproveIdentity").mockResolvedValue(true);
const listener = jest.fn();
const listener = vi.fn();
const observer = new SimpleObservable<IOpenIDUpdate>();
observer.onUpdate(listener);
await driver.askOpenID(observer);
@@ -246,14 +242,14 @@ describe("ElementWidgetDriver", () => {
it("falls back to legacy module API when new API returns false for identity", async () => {
const driver = mkDefaultDriver();
jest.spyOn(ModuleApi.instance.widgetLifecycle, "preapproveIdentity").mockResolvedValue(false);
jest.spyOn(ModuleRunner.instance, "invoke").mockImplementation((lifecycleEvent, opts, widgetInfo) => {
vi.spyOn(ModuleApi.instance.widgetLifecycle, "preapproveIdentity").mockResolvedValue(false);
vi.spyOn(ModuleRunner.instance, "invoke").mockImplementation((lifecycleEvent, opts, widgetInfo) => {
if (lifecycleEvent === WidgetLifecycle.IdentityRequest) {
(opts as ApprovalOpts).approved = true;
}
});
const listener = jest.fn();
const listener = vi.fn();
const observer = new SimpleObservable<IOpenIDUpdate>();
observer.onUpdate(listener);
await driver.askOpenID(observer);
@@ -297,7 +293,7 @@ describe("ElementWidgetDriver", () => {
});
it("sends encrypted messages", async () => {
const encryptToDeviceMessages = jest
const encryptToDeviceMessages = vi
.fn()
.mockImplementation(
(eventType, recipients: { userId: string; deviceId: string }[], content: object) => ({
@@ -373,7 +369,7 @@ describe("ElementWidgetDriver", () => {
});
it("stops if VoIP isn't supported", async () => {
jest.spyOn(client, "pollingTurnServers", "get").mockReturnValue(false);
vi.spyOn(client, "pollingTurnServers", "get").mockReturnValue(false);
const servers = driver.getTurnServers();
expect(await servers.next()).toEqual({ value: undefined, done: true });
});
@@ -435,7 +431,7 @@ describe("ElementWidgetDriver", () => {
it("gets the RTC transports from the homeserver", async () => {
const transports = [{ type: "livekit", livekit_service_url: "https://livekit-jwt.example.com" }];
client.cachedRtcTransports.wait.mockResolvedValue(transports);
vi.mocked(client.cachedRtcTransports.wait).mockResolvedValue(transports);
await expect(driver.getRtcTransports()).resolves.toEqual({ rtc_transports: transports });
});
@@ -450,18 +446,18 @@ describe("ElementWidgetDriver", () => {
429,
);
client.cachedRtcTransports.wait.mockRejectedValue(error);
vi.mocked(client.cachedRtcTransports.wait).mockRejectedValue(error);
await expect(driver.getRtcTransports()).rejects.toBe(error);
});
it("Should not fallback to well-known if config disallows and transport discovery not available", async () => {
const sdkConfigGet = SdkConfig.get;
jest.spyOn(SdkConfig, "get").mockImplementation((key?: any, altCaseName?: string): any => {
vi.spyOn(SdkConfig, "get").mockImplementation((key?: any, altCaseName?: string): any => {
if (key === "enable_client_well_known_lookups") return false;
return sdkConfigGet(key, altCaseName);
});
client.cachedRtcTransports.wait.mockRejectedValue(
vi.mocked(client.cachedRtcTransports.wait).mockRejectedValue(
new MatrixError({ errcode: "M_UNRECOGNIZED", error: "Not found" }, 404),
);
@@ -473,11 +469,11 @@ describe("ElementWidgetDriver", () => {
it("Should not fallback to well-known if config disallows and homerserver advertise no transports", async () => {
const sdkConfigGet = SdkConfig.get;
jest.spyOn(SdkConfig, "get").mockImplementation((key?: any, altCaseName?: string): any => {
vi.spyOn(SdkConfig, "get").mockImplementation((key?: any, altCaseName?: string): any => {
if (key === "enable_client_well_known_lookups") return false;
return sdkConfigGet(key, altCaseName);
});
client.cachedRtcTransports.wait.mockResolvedValue([]);
vi.mocked(client.cachedRtcTransports.wait).mockResolvedValue([]);
await expect(driver.getRtcTransports()).resolves.toEqual({ rtc_transports: [] });
@@ -487,11 +483,11 @@ describe("ElementWidgetDriver", () => {
it("Should fallback to well-known if config allows", async () => {
const sdkConfigGet = SdkConfig.get;
jest.spyOn(SdkConfig, "get").mockImplementation((key?: any, altCaseName?: string): any => {
vi.spyOn(SdkConfig, "get").mockImplementation((key?: any, altCaseName?: string): any => {
if (key === "enable_client_well_known_lookups") return true;
return sdkConfigGet(key, altCaseName);
});
client.cachedRtcTransports.wait.mockRejectedValue(
vi.mocked(client.cachedRtcTransports.wait).mockRejectedValue(
new MatrixError({ errcode: "M_UNRECOGNIZED", error: "Not found" }, 404),
);
@@ -514,7 +510,7 @@ describe("ElementWidgetDriver", () => {
});
it("reads related events from the current room", async () => {
jest.spyOn(SDKContextClass.instance.roomViewStore, "getRoomId").mockReturnValue("!this-room-id");
vi.spyOn(SDKContextClass.instance.roomViewStore, "getRoomId").mockReturnValue("!this-room-id");
client.relations.mockResolvedValue({
originalEvent: new MatrixEvent(),
@@ -585,7 +581,7 @@ describe("ElementWidgetDriver", () => {
beforeEach(() => {
stubClient();
driver = mkDefaultDriver();
jest.spyOn(dis, "dispatch").mockReset();
vi.spyOn(dis, "dispatch").mockReset();
});
it("sends chat effects", async () => {
@@ -746,7 +742,7 @@ describe("ElementWidgetDriver", () => {
});
const mockRoom: Partial<Room> = {
roomId: roomId,
_unstable_getStickyEvents: jest.fn().mockReturnValue([mockStickyEvent]),
_unstable_getStickyEvents: vi.fn().mockReturnValue([mockStickyEvent]),
};
client.getRoom.mockImplementation((roomId) => {
if (roomId === mockRoom.roomId) return mockRoom as Room;
@@ -803,7 +799,7 @@ describe("ElementWidgetDriver", () => {
describe("If the feature_dynamic_room_predecessors feature is not enabled", () => {
beforeEach(() => {
jest.spyOn(SettingsStore, "getValue").mockReturnValue(false);
vi.spyOn(SettingsStore, "getValue").mockReturnValue(false);
});
it("passes the flag through to getVisibleRooms", () => {
@@ -816,7 +812,7 @@ describe("ElementWidgetDriver", () => {
describe("If the feature_dynamic_room_predecessors is enabled", () => {
beforeEach(() => {
// Turn on feature_dynamic_room_predecessors setting
jest.spyOn(SettingsStore, "getValue").mockImplementation(
vi.spyOn(SettingsStore, "getValue").mockImplementation(
(settingName) => settingName === "feature_dynamic_room_predecessors",
);
});
@@ -1011,11 +1007,11 @@ describe("ElementWidgetDriver", () => {
room: "!1:example.org",
});
let driver: WidgetDriver;
let getStateEvents: jest.Mock;
let getStateEvents: Mock;
beforeEach(() => {
driver = mkDefaultDriver();
getStateEvents = jest.fn();
getStateEvents = vi.fn();
client.getRoom.mockReturnValue({
getLiveTimeline: () => ({ getState: () => ({ getStateEvents }) }),
} as unknown as Room);
@@ -6,15 +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.
*/
import { type MatrixClient, type Room } from "matrix-js-sdk/src/matrix";
import { mocked } from "jest-mock";
// @vitest-environment happy-dom
import WidgetStore, { type IApp } from "../../../src/stores/WidgetStore";
import { WidgetLayoutStore } from "../../../src/stores/widgets/WidgetLayoutStore";
import { stubClient } from "../../test-utils";
import defaultDispatcher from "../../../src/dispatcher/dispatcher";
import SettingsStore from "../../../src/settings/SettingsStore";
import { Action } from "../../../src/dispatcher/actions.ts";
import { vi, describe, it, expect, beforeEach, beforeAll, afterAll } from "vitest";
import { type MatrixClient, type Room } from "matrix-js-sdk/src/matrix";
import { stubClient } from "test-utils";
import WidgetStore, { type IApp } from "../WidgetStore";
import { WidgetLayoutStore } from "./WidgetLayoutStore";
import defaultDispatcher from "../../dispatcher/dispatcher";
import SettingsStore from "../../settings/SettingsStore";
import { Action } from "../../dispatcher/actions";
// setup test env values
const roomId = "!room:server";
@@ -49,9 +51,9 @@ describe("WidgetLayoutStore", () => {
];
// fake the WidgetStore.instance to just return an object with `getApps`
jest.spyOn(WidgetStore, "instance", "get").mockReturnValue({
on: jest.fn(),
off: jest.fn(),
vi.spyOn(WidgetStore, "instance", "get").mockReturnValue({
on: vi.fn(),
off: vi.fn(),
getApps: () => mockApps,
} as unknown as WidgetStore);
@@ -62,7 +64,7 @@ describe("WidgetLayoutStore", () => {
// we need to init a client so it does not error, when asking for DeviceStorage handlers (SettingsStore.setValue("Widgets.layout"))
client = stubClient();
roomUpdateListener = jest.fn();
roomUpdateListener = vi.fn();
// @ts-ignore bypass private ctor for tests
store = new WidgetLayoutStore();
store.addListener(`update_${roomId}`, roomUpdateListener);
@@ -167,7 +169,7 @@ describe("WidgetLayoutStore", () => {
});
it("should recalculate all rooms when the client is ready", async () => {
mocked(client.getVisibleRooms).mockReturnValue([mockRoom]);
vi.mocked(client.getVisibleRooms).mockReturnValue([mockRoom]);
await store.start();
expect(roomUpdateListener).toHaveBeenCalled();
@@ -183,9 +185,9 @@ describe("WidgetLayoutStore", () => {
it("should clear the layout and emit an update if there are no longer apps in the room", () => {
store.recalculateRoom(mockRoom);
mocked(roomUpdateListener).mockClear();
vi.mocked(roomUpdateListener).mockClear();
jest.spyOn(WidgetStore, "instance", "get").mockReturnValue(<WidgetStore>(
vi.spyOn(WidgetStore, "instance", "get").mockReturnValue(<WidgetStore>(
({ getApps: (): IApp[] => [] } as unknown as WidgetStore)
));
store.recalculateRoom(mockRoom);
@@ -236,7 +238,7 @@ describe("WidgetLayoutStore", () => {
store.moveToContainer(mockRoom, mockApps[0], "top");
store.copyLayoutToRoom(mockRoom);
expect(mocked(client.sendStateEvent).mock.calls).toMatchInlineSnapshot(`
expect(vi.mocked(client.sendStateEvent).mock.calls).toMatchInlineSnapshot(`
[
[
"!room:server",
@@ -272,17 +274,17 @@ describe("WidgetLayoutStore", () => {
// @ts-ignore bypass private ctor for tests
const store = new WidgetLayoutStore();
// @ts-ignore calling private method
store.onNotReady();
expect(() => store.onNotReady()).not.toThrow();
});
describe("when feature_dynamic_room_predecessors is not enabled", () => {
beforeAll(() => {
jest.spyOn(SettingsStore, "getValue").mockReturnValue(false);
vi.spyOn(SettingsStore, "getValue").mockReturnValue(false);
});
it("passes the flag in to getVisibleRooms", async () => {
mocked(client.getVisibleRooms).mockRestore();
mocked(client.getVisibleRooms).mockReturnValue([]);
vi.mocked(client.getVisibleRooms).mockRestore();
vi.mocked(client.getVisibleRooms).mockReturnValue([]);
// @ts-ignore bypass private ctor for tests
const store = new WidgetLayoutStore();
await store.start();
@@ -292,14 +294,14 @@ describe("WidgetLayoutStore", () => {
describe("when feature_dynamic_room_predecessors is enabled", () => {
beforeAll(() => {
jest.spyOn(SettingsStore, "getValue").mockImplementation(
vi.spyOn(SettingsStore, "getValue").mockImplementation(
(settingName) => settingName === "feature_dynamic_room_predecessors",
);
});
it("passes the flag in to getVisibleRooms", async () => {
mocked(client.getVisibleRooms).mockRestore();
mocked(client.getVisibleRooms).mockReturnValue([]);
vi.mocked(client.getVisibleRooms).mockRestore();
vi.mocked(client.getVisibleRooms).mockReturnValue([]);
// @ts-ignore bypass private ctor for tests
const store = new WidgetLayoutStore();
await store.start();
@@ -6,7 +6,19 @@ 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.
*/
import { mocked, type MockedFunction, type MockedObject } from "jest-mock";
// @vitest-environment happy-dom
import {
vi,
describe,
it,
expect,
beforeEach,
afterEach,
type Mock,
type MockedFunction,
type MockedObject,
} from "vitest";
import { findLast, last } from "lodash";
import {
MatrixEvent,
@@ -29,28 +41,54 @@ import {
WidgetApiDirection,
WidgetApiFromWidgetAction,
} from "matrix-widget-api";
import { waitFor } from "jest-matrix-react";
import type * as MatrixWidgetApi from "matrix-widget-api";
import { waitFor } from "test-utils-rtl";
import { stubClient, mkRoom, mkEvent } from "test-utils";
import { stubClient, mkRoom, mkEvent } from "../../../test-utils";
import { MatrixClientPeg } from "../../../../src/MatrixClientPeg";
import { ElementWidget, WidgetMessaging } from "../../../../src/stores/widgets/WidgetMessaging";
import ActiveWidgetStore from "../../../../src/stores/ActiveWidgetStore";
import SettingsStore from "../../../../src/settings/SettingsStore";
import defaultDispatcher from "../../../../src/dispatcher/dispatcher";
import { Action } from "../../../../src/dispatcher/actions";
import { SDKContextClass } from "../../../../src/contexts/SDKContextClass";
import { UPDATE_EVENT } from "../../../../src/stores/AsyncStore";
import { type IApp } from "../../../../src/utils/WidgetUtils-types";
import { ModalWidgetStore } from "../../../../src/stores/ModalWidgetStore";
import { ElementWidgetActions, type IViewRoomApiRequest } from "../../../../src/stores/widgets/ElementWidgetActions";
import { ElementWidgetCapabilities } from "../../../../src/stores/widgets/ElementWidgetCapabilities";
import { WidgetType } from "../../../../src/widgets/WidgetType";
import { IntegrationManagers } from "../../../../src/integrations/IntegrationManagers";
import { type IntegrationManagerInstance } from "../../../../src/integrations/IntegrationManagerInstance";
import { MatrixClientPeg } from "../../MatrixClientPeg";
import { ElementWidget, WidgetMessaging } from "./WidgetMessaging";
import ActiveWidgetStore from "../ActiveWidgetStore";
import SettingsStore from "../../settings/SettingsStore";
import defaultDispatcher from "../../dispatcher/dispatcher";
import { Action } from "../../dispatcher/actions";
import { SDKContextClass } from "../../contexts/SDKContextClass";
import { UPDATE_EVENT } from "../AsyncStore";
import { type IApp } from "../../utils/WidgetUtils-types";
import { ModalWidgetStore } from "../ModalWidgetStore";
import { ElementWidgetActions, type IViewRoomApiRequest } from "./ElementWidgetActions";
import { ElementWidgetCapabilities } from "./ElementWidgetCapabilities";
import { WidgetType } from "../../widgets/WidgetType";
import { IntegrationManagers } from "../../integrations/IntegrationManagers";
import { type IntegrationManagerInstance } from "../../integrations/IntegrationManagerInstance";
jest.mock("matrix-widget-api", () => ({
...jest.requireActual("matrix-widget-api"),
ClientWidgetApi: (jest.createMockFromModule("matrix-widget-api") as any).ClientWidgetApi,
vi.mock("matrix-widget-api", async () => {
const actual = await vi.importActual<typeof MatrixWidgetApi>("matrix-widget-api");
return {
...actual,
ClientWidgetApi: vi.fn(function () {
return {
on: vi.fn(),
once: vi.fn(),
feedEvent: vi.fn(),
feedToDevice: vi.fn(),
feedStateUpdate: vi.fn(),
setViewedRoomId: vi.fn(),
hasCapability: vi.fn(),
updateTheme: vi.fn(),
};
}),
};
});
vi.stubGlobal("matchMedia", (query: string) => ({
matches: false,
media: query,
onchange: null,
addListener: vi.fn(),
removeListener: vi.fn(),
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
dispatchEvent: vi.fn(),
}));
const originGetValue = SettingsStore.getValue;
@@ -62,7 +100,7 @@ describe("WidgetMessaging", () => {
beforeEach(() => {
stubClient();
client = mocked(MatrixClientPeg.safeGet());
client = vi.mocked(MatrixClientPeg.safeGet());
const app: IApp = {
id: "test",
@@ -81,7 +119,7 @@ describe("WidgetMessaging", () => {
});
// Start messaging without an iframe, since ClientWidgetApi is mocked
widget.start(null as unknown as HTMLIFrameElement);
messaging = mocked(last(mocked(ClientWidgetApi).mock.instances)!);
messaging = vi.mocked(last(vi.mocked(ClientWidgetApi).mock.instances)!);
messaging.feedStateUpdate.mockResolvedValue();
});
@@ -90,7 +128,7 @@ describe("WidgetMessaging", () => {
});
it("should replace parameters in widget url template", () => {
const spy = jest.spyOn(SettingsStore, "getValue").mockImplementation((setting) => {
const spy = vi.spyOn(SettingsStore, "getValue").mockImplementation((setting) => {
if (setting === "theme") return "my-theme-for-testing";
return originGetValue(setting);
});
@@ -101,7 +139,7 @@ describe("WidgetMessaging", () => {
});
it("should replace parameters in widget url template for popout", () => {
const spy = jest.spyOn(SettingsStore, "getValue").mockImplementation((setting) => {
const spy = vi.spyOn(SettingsStore, "getValue").mockImplementation((setting) => {
if (setting === "theme") return "my-theme-for-testing";
return originGetValue(setting);
});
@@ -166,7 +204,7 @@ describe("WidgetMessaging", () => {
it("informs widget of theme changes", () => {
let theme = "light";
const settingsSpy = jest
const settingsSpy = vi
.spyOn(SettingsStore, "getValue")
.mockImplementation((name) => (name === "theme" ? theme : null));
try {
@@ -244,7 +282,7 @@ describe("WidgetMessaging", () => {
room_id: event1.getRoomId(),
content: {},
});
const decryptingSpy1 = jest.spyOn(event1Encrypted, "isBeingDecrypted").mockReturnValue(true);
const decryptingSpy1 = vi.spyOn(event1Encrypted, "isBeingDecrypted").mockReturnValue(true);
client.emit(ClientEvent.Event, event1Encrypted);
const event2Encrypted = new MatrixEvent({
event_id: event2.getId(),
@@ -253,7 +291,7 @@ describe("WidgetMessaging", () => {
room_id: event2.getRoomId(),
content: {},
});
const decryptingSpy2 = jest.spyOn(event2Encrypted, "isBeingDecrypted").mockReturnValue(true);
const decryptingSpy2 = vi.spyOn(event2Encrypted, "isBeingDecrypted").mockReturnValue(true);
client.emit(ClientEvent.Event, event2Encrypted);
expect(messaging.feedEvent).not.toHaveBeenCalled();
@@ -329,14 +367,14 @@ describe("WidgetMessaging with stickyPromise", () => {
beforeEach(() => {
stubClient();
client = mocked(MatrixClientPeg.safeGet());
client = vi.mocked(MatrixClientPeg.safeGet());
});
afterEach(() => {
widget.stop();
});
it("should wait for the sticky promise to resolve before starting messaging", async () => {
jest.useFakeTimers();
vi.useFakeTimers();
const getStickyPromise = async () => {
return new Promise<void>((resolve) => {
setTimeout(() => {
@@ -361,12 +399,12 @@ describe("WidgetMessaging with stickyPromise", () => {
stickyPromise: getStickyPromise,
});
const setPersistenceSpy = jest.spyOn(ActiveWidgetStore.instance, "setWidgetPersistence");
const setPersistenceSpy = vi.spyOn(ActiveWidgetStore.instance, "setWidgetPersistence");
// Start messaging without an iframe, since ClientWidgetApi is mocked
widget.start(null as unknown as HTMLIFrameElement);
const emitSticky = async () => {
messaging = mocked(last(mocked(ClientWidgetApi).mock.instances)!);
messaging = vi.mocked(last(vi.mocked(ClientWidgetApi).mock.instances)!);
messaging?.hasCapability.mockReturnValue(true);
// messaging.transport.reply will be called but transport is undefined in this test environment
// This just makes sure the call doesn't throw
@@ -381,11 +419,11 @@ describe("WidgetMessaging with stickyPromise", () => {
await emitSticky();
expect(setPersistenceSpy).not.toHaveBeenCalled();
// Advance the fake timer so that the sticky promise resolves
jest.runAllTimers();
vi.runAllTimers();
// Use a real timer and wait for the next tick so the sticky promise can resolve
jest.useRealTimers();
vi.useRealTimers();
waitFor(() => expect(setPersistenceSpy).toHaveBeenCalled(), { interval: 5 });
await waitFor(() => expect(setPersistenceSpy).toHaveBeenCalled(), { interval: 5 });
});
});
@@ -397,7 +435,7 @@ describe("WidgetMessaging as an account widget", () => {
beforeEach(() => {
stubClient();
// I give up, getting the return type of spyOn right is hopeless
getRoomId = jest.spyOn(SDKContextClass.instance.roomViewStore, "getRoomId") as unknown as MockedFunction<
getRoomId = vi.spyOn(SDKContextClass.instance.roomViewStore, "getRoomId") as unknown as MockedFunction<
() => string | null
>;
getRoomId.mockReturnValue("!1:example.org");
@@ -418,7 +456,7 @@ describe("WidgetMessaging as an account widget", () => {
});
// Start messaging without an iframe, since ClientWidgetApi is mocked
widget.start(null as unknown as HTMLIFrameElement);
messaging = mocked(last(mocked(ClientWidgetApi).mock.instances)!);
messaging = vi.mocked(last(vi.mocked(ClientWidgetApi).mock.instances)!);
});
afterEach(() => {
@@ -475,28 +513,28 @@ describe("WidgetMessaging action handling", () => {
});
// Start messaging without an iframe, since ClientWidgetApi is mocked
widget.start(null as unknown as HTMLIFrameElement);
messaging = mocked(last(mocked(ClientWidgetApi).mock.instances)!);
Object.defineProperty(messaging, "transport", { value: { reply: jest.fn() } });
messaging = vi.mocked(last(vi.mocked(ClientWidgetApi).mock.instances)!);
Object.defineProperty(messaging, "transport", { value: { reply: vi.fn() } });
actionFns = Object.fromEntries(messaging.on.mock.calls as any);
});
afterEach(() => {
widget.stop();
jest.resetAllMocks();
vi.resetAllMocks();
});
describe("open modal widget", () => {
beforeEach(() => {
// Trivial mock of ModalWidgetStore
let hasModal = false;
jest.spyOn(ModalWidgetStore.instance, "openModalWidget").mockImplementation(() => {
vi.spyOn(ModalWidgetStore.instance, "openModalWidget").mockImplementation(() => {
if (hasModal) {
throw Error("Modal already in view");
}
hasModal = true;
});
jest.spyOn(ModalWidgetStore.instance, "canOpenModalWidget").mockImplementation(() => !hasModal);
jest.spyOn(ModalWidgetStore.instance, "closeModalWidget").mockImplementation(() => {
vi.spyOn(ModalWidgetStore.instance, "canOpenModalWidget").mockImplementation(() => !hasModal);
vi.spyOn(ModalWidgetStore.instance, "closeModalWidget").mockImplementation(() => {
if (!hasModal) {
throw Error("No modal in view");
}
@@ -514,7 +552,7 @@ describe("WidgetMessaging action handling", () => {
const ev = createTransportEvent<IModalWidgetOpenRequest>({ type: "foo", url: "bar" });
actionFns[`action:${WidgetApiFromWidgetAction.OpenModalWidget}`](ev);
expect(messaging.transport.reply).toHaveBeenCalledWith(ev.detail, {});
messaging.transport.reply.mockReset();
vi.mocked(messaging.transport.reply).mockReset();
actionFns[`action:${WidgetApiFromWidgetAction.OpenModalWidget}`](ev);
expect(messaging.transport.reply).toHaveBeenCalledWith(ev.detail, {
error: { message: "Unable to open modal at this time" },
@@ -524,7 +562,7 @@ describe("WidgetMessaging action handling", () => {
describe("view room", () => {
afterEach(() => {
jest.resetAllMocks();
vi.resetAllMocks();
});
it("errors on invalid room", () => {
const ev = createTransportEvent<IViewRoomApiRequest>({ room_id: null } as any);
@@ -545,7 +583,7 @@ describe("WidgetMessaging action handling", () => {
messaging.hasCapability.mockImplementation(
(capability) => capability === ElementWidgetCapabilities.CanChangeViewedRoom,
);
const dispatch = (defaultDispatcher.dispatch = jest.fn());
const dispatch = (defaultDispatcher.dispatch = vi.fn());
actionFns[`action:${ElementWidgetActions.ViewRoom}`](ev);
expect(messaging.transport.reply).toHaveBeenCalledWith(ev.detail, {});
expect(dispatch).toHaveBeenCalledWith({
@@ -557,9 +595,9 @@ describe("WidgetMessaging action handling", () => {
});
describe("always on screen", () => {
let setWidgetPersistence: jest.SpyInstance<void, Parameters<ActiveWidgetStore["setWidgetPersistence"]>>;
let setWidgetPersistence: Mock<ActiveWidgetStore["setWidgetPersistence"]>;
beforeEach(() => {
setWidgetPersistence = jest.spyOn(ActiveWidgetStore.instance, "setWidgetPersistence");
setWidgetPersistence = vi.spyOn(ActiveWidgetStore.instance, "setWidgetPersistence");
});
it("does nothing if the widget does not have permission", () => {
@@ -587,7 +625,7 @@ describe("WidgetMessaging action handling", () => {
actionFns[`action:${WidgetApiFromWidgetAction.UpdateAlwaysOnScreen}`](evOpen);
expect(messaging.transport.reply).toHaveBeenCalledWith(evOpen.detail, {});
expect(setWidgetPersistence).toHaveBeenCalledTimes(1);
messaging.transport.reply.mockReset();
vi.mocked(messaging.transport.reply).mockReset();
const evClose = createTransportEvent<IStickyActionRequest>({ value: false });
actionFns[`action:${WidgetApiFromWidgetAction.UpdateAlwaysOnScreen}`](evClose);
expect(messaging.transport.reply).toHaveBeenCalledWith(evClose.detail, {});
@@ -608,7 +646,7 @@ describe("WidgetMessaging action handling", () => {
(capability) => capability === MatrixCapabilities.StickerSending,
);
const ev = createTransportEvent<IStickerActionRequest>({ name: "foo", content: { url: "bar" } });
const dispatch = (defaultDispatcher.dispatch = jest.fn());
const dispatch = (defaultDispatcher.dispatch = vi.fn());
actionFns[`action:${WidgetApiFromWidgetAction.SendSticker}`](ev);
expect(messaging.transport.reply).toHaveBeenCalledWith(ev.detail, {});
expect(dispatch).toHaveBeenCalledWith({
@@ -627,10 +665,10 @@ describe("WidgetMessaging action handling for stickerpicker", () => {
let room: Room;
beforeEach(() => {
const client = mocked(stubClient());
const client = vi.mocked(stubClient());
room = mkRoom(client, "!1:example.org");
client.getRoom.mockImplementation((roomId) => (roomId === room.roomId ? room : null));
const getRoomId = jest.spyOn(SDKContextClass.instance.roomViewStore, "getRoomId") as unknown as MockedFunction<
const getRoomId = vi.spyOn(SDKContextClass.instance.roomViewStore, "getRoomId") as unknown as MockedFunction<
() => string | null
>;
getRoomId.mockReturnValue(room.roomId);
@@ -651,23 +689,23 @@ describe("WidgetMessaging action handling for stickerpicker", () => {
});
// Start messaging without an iframe, since ClientWidgetApi is mocked
widget.start(null as unknown as HTMLIFrameElement);
messaging = mocked(last(mocked(ClientWidgetApi).mock.instances)!);
Object.defineProperty(messaging, "transport", { value: { reply: jest.fn() } });
messaging = vi.mocked(last(vi.mocked(ClientWidgetApi).mock.instances)!);
Object.defineProperty(messaging, "transport", { value: { reply: vi.fn() } });
actionFns = Object.fromEntries(messaging.on.mock.calls as any);
});
afterEach(() => {
widget.stop();
jest.resetAllMocks();
vi.resetAllMocks();
});
describe("open integrations manager", () => {
let openIntegrationManager: jest.SpyInstance<void, Parameters<IntegrationManagerInstance["open"]>>;
let openIntegrationManager: Mock<IntegrationManagerInstance["open"]>;
beforeEach(() => {
// Trivial mock of ModalWidgetStore
openIntegrationManager = jest.fn();
openIntegrationManager = vi.fn();
const inst = IntegrationManagers.sharedInstance();
jest.spyOn(inst, "getPrimaryManager").mockImplementation(
vi.spyOn(inst, "getPrimaryManager").mockImplementation(
() =>
({
open: openIntegrationManager,
@@ -677,7 +715,7 @@ describe("WidgetMessaging action handling for stickerpicker", () => {
it("open the integration manager", () => {
const ev = createTransportEvent<IWidgetApiRequest>({ integType: "my_integ_type", integId: "my_integ_id" });
const dispatch = (defaultDispatcher.dispatch = jest.fn());
const dispatch = (defaultDispatcher.dispatch = vi.fn());
actionFns[`action:${ElementWidgetActions.OpenIntegrationManager}`](ev);
expect(dispatch).toHaveBeenCalledWith({
action: "stickerpicker_close",
@@ -6,20 +6,21 @@ 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.
*/
import { mocked } from "jest-mock";
// @vitest-environment happy-dom
import { vi, describe, it, expect, beforeEach } from "vitest";
import { type MatrixClient } from "matrix-js-sdk/src/matrix";
import { Widget, WidgetKind } from "matrix-widget-api";
import { TestSDKContext, stubClient } from "test-utils";
import { OIDCState, WidgetPermissionStore } from "../../../../src/stores/widgets/WidgetPermissionStore";
import SettingsStore from "../../../../src/settings/SettingsStore";
import { TestSDKContext } from "../../TestSDKContext";
import { type SettingLevel } from "../../../../src/settings/SettingLevel";
import { SDKContextClass } from "../../../../src/contexts/SDKContextClass";
import { stubClient } from "../../../test-utils";
import { ElementWidgetDriver } from "../../../../src/stores/widgets/ElementWidgetDriver";
import { WidgetType } from "../../../../src/widgets/WidgetType.ts";
import { OIDCState, WidgetPermissionStore } from "./WidgetPermissionStore";
import SettingsStore from "../../settings/SettingsStore";
import { type SettingLevel } from "../../settings/SettingLevel";
import { SDKContextClass } from "../../contexts/SDKContextClass";
import { ElementWidgetDriver } from "./ElementWidgetDriver";
import { WidgetType } from "../../widgets/WidgetType";
jest.mock("../../../../src/settings/SettingsStore");
vi.mock("../../settings/SettingsStore");
describe("WidgetPermissionStore", () => {
let widgetPermissionStore: WidgetPermissionStore;
@@ -42,10 +43,10 @@ describe("WidgetPermissionStore", () => {
beforeEach(() => {
settings = {}; // clear settings
mocked(SettingsStore.getValue).mockImplementation((setting: string) => {
vi.mocked(SettingsStore.getValue).mockImplementation((setting: string) => {
return settings[setting];
});
mocked(SettingsStore.setValue).mockImplementation(
vi.mocked(SettingsStore.setValue).mockImplementation(
(settingName: string, roomId: string | null, level: SettingLevel, value: any): Promise<void> => {
// the store doesn't use any specific level or room ID (room IDs are packed into keys in `value`)
settings[settingName] = value;
@@ -11,7 +11,7 @@ import { describe, it, expect, beforeEach } from "vitest";
import { type Room } from "matrix-js-sdk/src/matrix";
import { createTestClient } from "test-utils";
import { getMockedRooms } from "../../../test/unit-tests/stores/room-list-v3/skip-list/getMockedRooms";
import { getMockedRooms } from "../../stores/room-list-v3/skip-list/__mocks__";
import { DefaultTagID } from "../../stores/room-list-v3/skip-list/tag";
import { compareRoomsByRecency, sortRoomsByRecency } from "./sortRoomsByRecency";
+14 -10
View File
@@ -19,7 +19,7 @@ import {
type IContent,
} from "matrix-js-sdk/src/matrix";
import { CallType } from "matrix-js-sdk/src/webrtc/call";
import { mocked, type Mocked } from "jest-mock";
import { type Mocked } from "jest-mock";
import { type MatrixRTCSession } from "matrix-js-sdk/src/matrixrtc";
import { mkEvent, mkRoomMember, setupAsyncStoreWithClient, stubClient } from "./test-utils";
@@ -31,6 +31,7 @@ import { MockEventEmitter } from "./client";
import WidgetStore from "../../src/stores/WidgetStore";
import { WidgetMessagingStore } from "../../src/stores/widgets/WidgetMessagingStore";
import SettingsStore from "../../src/settings/SettingsStore";
import { vi, mocked } from "../setup/adapter.ts";
export class MockedCall extends Call {
public static readonly EVENT_TYPE = "org.example.mocked_call";
@@ -136,7 +137,7 @@ export function useMockedCalls() {
*/
export function enableCalls(): { enabledSettings: Set<string> } {
const enabledSettings = new Set(["feature_video_rooms", "feature_element_call_video_rooms", "feature_user_status"]);
jest.spyOn(SettingsStore, "getValue").mockImplementation((settingName): any => {
vi.spyOn(SettingsStore, "getValue").mockImplementation((settingName): any => {
if (settingName.startsWith("feature_")) return enabledSettings.has(settingName);
if (settingName === "activeCallRoomIds") return [];
return undefined;
@@ -153,11 +154,14 @@ export function setUpClientRoomAndStores(): {
roomSession: Mocked<MatrixRTCSession>;
} {
stubClient();
const client = mocked<MatrixClient>(MatrixClientPeg.safeGet());
// Cast at this vitest/jest-mock type-system boundary: `mocked()` produces a vitest-shaped mock type at
// compile time, but this helper is still consumed by not-yet-migrated jest tests that expect jest-mock's
// (structurally different, but runtime-equivalent) `Mocked<T>` shape.
const client = mocked<MatrixClient>(MatrixClientPeg.safeGet()) as unknown as Mocked<MatrixClient>;
DMRoomMap.makeShared(client);
client.cachedRtcTransports = {
wait: jest.fn().mockResolvedValue(undefined),
get: jest.fn().mockReturnValue(undefined),
wait: vi.fn().mockResolvedValue(undefined),
get: vi.fn().mockReturnValue(undefined),
} as unknown as any;
const room = new Room("!1:example.org", client, "@alice:example.org", {
pendingEventOrdering: PendingEventOrdering.Detached,
@@ -166,7 +170,7 @@ export function setUpClientRoomAndStores(): {
const alice = mkRoomMember(room.roomId, "@alice:example.org");
const bob = mkRoomMember(room.roomId, "@bob:example.org");
const carol = mkRoomMember(room.roomId, "@carol:example.org");
jest.spyOn(room, "getMember").mockImplementation((userId) => {
vi.spyOn(room, "getMember").mockImplementation((userId) => {
switch (userId) {
case alice.userId:
return alice;
@@ -179,16 +183,16 @@ export function setUpClientRoomAndStores(): {
}
});
jest.spyOn(room, "getMyMembership").mockReturnValue(KnownMembership.Join);
vi.spyOn(room, "getMyMembership").mockReturnValue(KnownMembership.Join);
client.getRoom.mockImplementation((roomId) => (roomId === room.roomId ? room : null));
const roomSession = new MockEventEmitter({
memberships: [],
getOldestMembership: jest.fn().mockReturnValue(undefined),
getConsensusCallIntent: jest.fn().mockReturnValue(undefined),
getOldestMembership: vi.fn().mockReturnValue(undefined),
getConsensusCallIntent: vi.fn().mockReturnValue(undefined),
room,
}) as Mocked<MatrixRTCSession>;
}) as unknown as Mocked<MatrixRTCSession>;
client.matrixRTC.getRoomSession.mockReturnValue(roomSession);
client.getRooms.mockReturnValue([room]);