Migrate more jest tests to vitest (#33898)
* Migrate more jest tests to vitest * Fix jest config * Fix jest config * Make remaining jest tests type-happy
This commit is contained in:
@@ -0,0 +1,11 @@
|
|||||||
|
/*
|
||||||
|
Copyright 2024 New Vector Ltd.
|
||||||
|
Copyright 2023 The Matrix.org Foundation C.I.C.
|
||||||
|
|
||||||
|
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
|
||||||
|
Please see LICENSE files in the repository root for full details.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export default function workerFactory(options) {
|
||||||
|
return jest.fn;
|
||||||
|
}
|
||||||
@@ -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.
|
Please see LICENSE files in the repository root for full details.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import { vi } from "vitest";
|
||||||
|
|
||||||
export default function workerFactory(options) {
|
export default function workerFactory(options) {
|
||||||
return jest.fn;
|
return vi.fn;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -41,10 +41,13 @@ const config: Config = {
|
|||||||
"decoderWorker\\.min\\.wasm": "<rootDir>/__mocks__/empty.js",
|
"decoderWorker\\.min\\.wasm": "<rootDir>/__mocks__/empty.js",
|
||||||
"waveWorker\\.min\\.js": "<rootDir>/__mocks__/empty.js",
|
"waveWorker\\.min\\.js": "<rootDir>/__mocks__/empty.js",
|
||||||
"context-filter-polyfill": "<rootDir>/__mocks__/empty.js",
|
"context-filter-polyfill": "<rootDir>/__mocks__/empty.js",
|
||||||
"workers/(.+)Factory": "<rootDir>/__mocks__/workerFactoryMock.js",
|
"workers/(.+)Factory": "<rootDir>/__mocks__/workerFactoryMock-jest.js",
|
||||||
".*\\?raw": "jest-raw-loader",
|
".*\\?raw": "jest-raw-loader",
|
||||||
"recorderWorkletFactory": "<rootDir>/__mocks__/empty.js",
|
"recorderWorkletFactory": "<rootDir>/__mocks__/empty.js",
|
||||||
"@vector-im/compound-web": "<rootDir>/node_modules/@vector-im/compound-web",
|
"@vector-im/compound-web": "<rootDir>/node_modules/@vector-im/compound-web",
|
||||||
|
"^vitest$": "<rootDir>/__mocks__/empty.js",
|
||||||
|
"jest-mock-vitest-adapter": "<rootDir>/test/setup/adapter.ts",
|
||||||
|
"test-utils-rtl": "<rootDir>/test/test-utils/jest-matrix-react.tsx",
|
||||||
},
|
},
|
||||||
transformIgnorePatterns: [
|
transformIgnorePatterns: [
|
||||||
`${path.join(__dirname, "../..")}/node_modules/.pnpm/(?!(mime|uuid|p-retry|is-network-error|react-merge-refs|is-ip|ip-regex|super-regex|function-timeout|time-span|convert-hrtime|clone-regexp|is-regexp|matrix-web-i18n|await-lock|@element-hq/web-shared-components|react-virtuoso|lodash|domutils|domhandler|domelementtype|dom-serializer|entities)).+$`,
|
`${path.join(__dirname, "../..")}/node_modules/.pnpm/(?!(mime|uuid|p-retry|is-network-error|react-merge-refs|is-ip|ip-regex|super-regex|function-timeout|time-span|convert-hrtime|clone-regexp|is-regexp|matrix-web-i18n|await-lock|@element-hq/web-shared-components|react-virtuoso|lodash|domutils|domhandler|domelementtype|dom-serializer|entities)).+$`,
|
||||||
|
|||||||
@@ -168,6 +168,7 @@
|
|||||||
"@types/ua-parser-js": "^0.7.36",
|
"@types/ua-parser-js": "^0.7.36",
|
||||||
"@typescript-eslint/eslint-plugin": "^8.19.0",
|
"@typescript-eslint/eslint-plugin": "^8.19.0",
|
||||||
"@typescript-eslint/parser": "^8.19.0",
|
"@typescript-eslint/parser": "^8.19.0",
|
||||||
|
"@vitest/spy": "catalog:",
|
||||||
"babel-jest": "^30.0.0",
|
"babel-jest": "^30.0.0",
|
||||||
"babel-loader": "^10.0.0",
|
"babel-loader": "^10.0.0",
|
||||||
"babel-plugin-jsx-remove-data-test-id": "^3.0.0",
|
"babel-plugin-jsx-remove-data-test-id": "^3.0.0",
|
||||||
|
|||||||
+14
-10
@@ -6,9 +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.
|
Please see LICENSE files in the repository root for full details.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import defaultDispatcher from "../../../src/dispatcher/dispatcher";
|
// @vitest-environment happy-dom
|
||||||
import { Action } from "../../../src/dispatcher/actions";
|
|
||||||
import { AsyncActionPayload } from "../../../src/dispatcher/payloads";
|
import { vi, describe, it, expect } from "vitest";
|
||||||
|
|
||||||
|
import defaultDispatcher from "./dispatcher";
|
||||||
|
import { Action } from "./actions";
|
||||||
|
import { AsyncActionPayload } from "./payloads";
|
||||||
|
|
||||||
describe("MatrixDispatcher", () => {
|
describe("MatrixDispatcher", () => {
|
||||||
it("should throw error if unregistering unknown token", () => {
|
it("should throw error if unregistering unknown token", () => {
|
||||||
@@ -21,8 +25,8 @@ describe("MatrixDispatcher", () => {
|
|||||||
const deferred1 = Promise.withResolvers<number>();
|
const deferred1 = Promise.withResolvers<number>();
|
||||||
const deferred2 = Promise.withResolvers<number>();
|
const deferred2 = Promise.withResolvers<number>();
|
||||||
|
|
||||||
const fn1 = jest.fn(() => deferred1.resolve(1));
|
const fn1 = vi.fn(() => deferred1.resolve(1));
|
||||||
const fn2 = jest.fn(() => deferred2.resolve(2));
|
const fn2 = vi.fn(() => deferred2.resolve(2));
|
||||||
|
|
||||||
defaultDispatcher.register(fn1);
|
defaultDispatcher.register(fn1);
|
||||||
defaultDispatcher.register(fn2);
|
defaultDispatcher.register(fn2);
|
||||||
@@ -37,8 +41,8 @@ describe("MatrixDispatcher", () => {
|
|||||||
const deferred1 = Promise.withResolvers<number>();
|
const deferred1 = Promise.withResolvers<number>();
|
||||||
const deferred2 = Promise.withResolvers<number>();
|
const deferred2 = Promise.withResolvers<number>();
|
||||||
|
|
||||||
const fn1 = jest.fn(() => deferred1.resolve(1));
|
const fn1 = vi.fn(() => deferred1.resolve(1));
|
||||||
const fn2 = jest.fn(() => deferred2.resolve(2));
|
const fn2 = vi.fn(() => deferred2.resolve(2));
|
||||||
|
|
||||||
defaultDispatcher.register(() => {
|
defaultDispatcher.register(() => {
|
||||||
defaultDispatcher.waitFor([id2]);
|
defaultDispatcher.waitFor([id2]);
|
||||||
@@ -53,7 +57,7 @@ describe("MatrixDispatcher", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("should not fire callback which was added during a dispatch", () => {
|
it("should not fire callback which was added during a dispatch", () => {
|
||||||
const fn2 = jest.fn();
|
const fn2 = vi.fn();
|
||||||
|
|
||||||
defaultDispatcher.register(() => {
|
defaultDispatcher.register(() => {
|
||||||
defaultDispatcher.register(fn2);
|
defaultDispatcher.register(fn2);
|
||||||
@@ -65,10 +69,10 @@ describe("MatrixDispatcher", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("should handle AsyncActionPayload", () => {
|
it("should handle AsyncActionPayload", () => {
|
||||||
const fn = jest.fn();
|
const fn = vi.fn();
|
||||||
defaultDispatcher.register(fn);
|
defaultDispatcher.register(fn);
|
||||||
|
|
||||||
const readyFn = jest.fn((dispatch) => {
|
const readyFn = vi.fn((dispatch) => {
|
||||||
dispatch({ action: "test" });
|
dispatch({ action: "test" });
|
||||||
});
|
});
|
||||||
defaultDispatcher.dispatch(new AsyncActionPayload(readyFn), true);
|
defaultDispatcher.dispatch(new AsyncActionPayload(readyFn), true);
|
||||||
+26
-19
@@ -14,7 +14,9 @@ See the License for the specific language governing permissions and
|
|||||||
limitations under the License.
|
limitations under the License.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { type Mocked } from "jest-mock";
|
// @vitest-environment happy-dom
|
||||||
|
|
||||||
|
import { vi, describe, it, expect, afterEach, type Mocked } from "vitest";
|
||||||
import {
|
import {
|
||||||
Direction,
|
Direction,
|
||||||
type MatrixClient,
|
type MatrixClient,
|
||||||
@@ -25,22 +27,27 @@ import {
|
|||||||
SyncState,
|
SyncState,
|
||||||
} from "matrix-js-sdk/src/matrix";
|
} from "matrix-js-sdk/src/matrix";
|
||||||
|
|
||||||
import EventIndex from "../../../src/indexing/EventIndex.ts";
|
import EventIndex from "./EventIndex.ts";
|
||||||
import { emitPromise, getMockClientWithEventEmitter, mockClientMethodsRooms, mockPlatformPeg } from "../../test-utils";
|
import {
|
||||||
import type BaseEventIndexManager from "../../../src/indexing/BaseEventIndexManager.ts";
|
emitPromise,
|
||||||
import { type ICrawlerCheckpoint } from "../../../src/indexing/BaseEventIndexManager.ts";
|
getMockClientWithEventEmitter,
|
||||||
import SettingsStore from "../../../src/settings/SettingsStore.ts";
|
mockClientMethodsRooms,
|
||||||
|
mockPlatformPeg,
|
||||||
|
} from "../../test/test-utils";
|
||||||
|
import type BaseEventIndexManager from "./BaseEventIndexManager.ts";
|
||||||
|
import { type ICrawlerCheckpoint } from "./BaseEventIndexManager.ts";
|
||||||
|
import SettingsStore from "../settings/SettingsStore.ts";
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
jest.restoreAllMocks();
|
vi.restoreAllMocks();
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("EventIndex", () => {
|
describe("EventIndex", () => {
|
||||||
it("crawls through the loaded checkpoints", async () => {
|
it("crawls through the loaded checkpoints", async () => {
|
||||||
const mockIndexingManager = {
|
const mockIndexingManager = {
|
||||||
loadCheckpoints: jest.fn(),
|
loadCheckpoints: vi.fn(),
|
||||||
removeCrawlerCheckpoint: jest.fn(),
|
removeCrawlerCheckpoint: vi.fn(),
|
||||||
isEventIndexEmpty: jest.fn().mockResolvedValue(false),
|
isEventIndexEmpty: vi.fn().mockResolvedValue(false),
|
||||||
} as any as Mocked<BaseEventIndexManager>;
|
} as any as Mocked<BaseEventIndexManager>;
|
||||||
mockPlatformPeg({ getEventIndexingManager: () => mockIndexingManager });
|
mockPlatformPeg({ getEventIndexingManager: () => mockIndexingManager });
|
||||||
|
|
||||||
@@ -48,11 +55,11 @@ describe("EventIndex", () => {
|
|||||||
const room2 = { roomId: "!room2:id" } as any as Room;
|
const room2 = { roomId: "!room2:id" } as any as Room;
|
||||||
const mockClient = getMockClientWithEventEmitter({
|
const mockClient = getMockClientWithEventEmitter({
|
||||||
getEventMapper: () => (obj: Partial<IEvent>) => new MatrixEvent(obj),
|
getEventMapper: () => (obj: Partial<IEvent>) => new MatrixEvent(obj),
|
||||||
createMessagesRequest: jest.fn(),
|
createMessagesRequest: vi.fn(),
|
||||||
...mockClientMethodsRooms([room1, room2]),
|
...mockClientMethodsRooms([room1, room2]),
|
||||||
});
|
});
|
||||||
|
|
||||||
jest.spyOn(SettingsStore, "getValueAt").mockImplementation((_level, settingName): any => {
|
vi.spyOn(SettingsStore, "getValueAt").mockImplementation((_level, settingName): any => {
|
||||||
if (settingName === "crawlerSleepTime") return 0;
|
if (settingName === "crawlerSleepTime") return 0;
|
||||||
return undefined;
|
return undefined;
|
||||||
});
|
});
|
||||||
@@ -90,11 +97,11 @@ describe("EventIndex", () => {
|
|||||||
|
|
||||||
it("adds checkpoints for the encrypted rooms after the first sync", async () => {
|
it("adds checkpoints for the encrypted rooms after the first sync", async () => {
|
||||||
const mockIndexingManager = {
|
const mockIndexingManager = {
|
||||||
loadCheckpoints: jest.fn().mockResolvedValue([]),
|
loadCheckpoints: vi.fn().mockResolvedValue([]),
|
||||||
isEventIndexEmpty: jest.fn().mockResolvedValue(true),
|
isEventIndexEmpty: vi.fn().mockResolvedValue(true),
|
||||||
addCrawlerCheckpoint: jest.fn(),
|
addCrawlerCheckpoint: vi.fn(),
|
||||||
removeCrawlerCheckpoint: jest.fn(),
|
removeCrawlerCheckpoint: vi.fn(),
|
||||||
commitLiveEvents: jest.fn(),
|
commitLiveEvents: vi.fn(),
|
||||||
} as any as Mocked<BaseEventIndexManager>;
|
} as any as Mocked<BaseEventIndexManager>;
|
||||||
mockPlatformPeg({ getEventIndexingManager: () => mockIndexingManager });
|
mockPlatformPeg({ getEventIndexingManager: () => mockIndexingManager });
|
||||||
|
|
||||||
@@ -111,11 +118,11 @@ describe("EventIndex", () => {
|
|||||||
}),
|
}),
|
||||||
} as any as Room;
|
} as any as Room;
|
||||||
const mockCrypto = {
|
const mockCrypto = {
|
||||||
isEncryptionEnabledInRoom: jest.fn().mockResolvedValue(true),
|
isEncryptionEnabledInRoom: vi.fn().mockResolvedValue(true),
|
||||||
};
|
};
|
||||||
const mockClient = getMockClientWithEventEmitter({
|
const mockClient = getMockClientWithEventEmitter({
|
||||||
getEventMapper: () => (obj: Partial<IEvent>) => new MatrixEvent(obj),
|
getEventMapper: () => (obj: Partial<IEvent>) => new MatrixEvent(obj),
|
||||||
createMessagesRequest: jest.fn(),
|
createMessagesRequest: vi.fn(),
|
||||||
getCrypto: () => mockCrypto as any,
|
getCrypto: () => mockCrypto as any,
|
||||||
...mockClientMethodsRooms([room1, room2]),
|
...mockClientMethodsRooms([room1, room2]),
|
||||||
});
|
});
|
||||||
+30
-27
@@ -6,16 +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.
|
Please see LICENSE files in the repository root for full details.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { ClientEvent, type MatrixClient, type Room, SyncState } from "matrix-js-sdk/src/matrix";
|
// @vitest-environment happy-dom
|
||||||
import { waitFor } from "jest-matrix-react";
|
|
||||||
|
|
||||||
import type BasePlatform from "../../../src/BasePlatform";
|
import { vi, describe, it, expect, beforeAll, beforeEach, afterEach } from "vitest";
|
||||||
import SdkConfig from "../../../src/SdkConfig";
|
import { ClientEvent, type MatrixClient, type Room, SyncState } from "matrix-js-sdk/src/matrix";
|
||||||
import { SettingLevel } from "../../../src/settings/SettingLevel";
|
import { waitFor } from "test-utils-rtl";
|
||||||
import SettingsStore from "../../../src/settings/SettingsStore";
|
|
||||||
import { mkStubRoom, mockPlatformPeg, stubClient } from "../../test-utils";
|
import type BasePlatform from "../BasePlatform";
|
||||||
import { SETTINGS, type SettingKey } from "../../../src/settings/Settings.tsx";
|
import SdkConfig from "../SdkConfig";
|
||||||
import MatrixClientBackedController from "../../../src/settings/controllers/MatrixClientBackedController.ts";
|
import { SettingLevel } from "./SettingLevel";
|
||||||
|
import SettingsStore from "./SettingsStore";
|
||||||
|
import { mkStubRoom, mockPlatformPeg, stubClient } from "../../test/test-utils";
|
||||||
|
import { SETTINGS, type SettingKey } from "./Settings.tsx";
|
||||||
|
import MatrixClientBackedController from "./controllers/MatrixClientBackedController.ts";
|
||||||
|
|
||||||
const TEST_DATA = [
|
const TEST_DATA = [
|
||||||
{
|
{
|
||||||
@@ -34,18 +37,18 @@ describe("SettingsStore", () => {
|
|||||||
let platformSettings: Record<string, any>;
|
let platformSettings: Record<string, any>;
|
||||||
|
|
||||||
beforeAll(() => {
|
beforeAll(() => {
|
||||||
jest.clearAllMocks();
|
vi.clearAllMocks();
|
||||||
platformSettings = {};
|
platformSettings = {};
|
||||||
mockPlatformPeg({
|
mockPlatformPeg({
|
||||||
isLevelSupported: jest.fn().mockReturnValue(true),
|
isLevelSupported: vi.fn().mockReturnValue(true),
|
||||||
supportsSetting: jest.fn().mockReturnValue(true),
|
supportsSetting: vi.fn().mockReturnValue(true),
|
||||||
setSettingValue: jest.fn().mockImplementation((settingName: string, value: any) => {
|
setSettingValue: vi.fn().mockImplementation((settingName: string, value: any) => {
|
||||||
platformSettings[settingName] = value;
|
platformSettings[settingName] = value;
|
||||||
}),
|
}),
|
||||||
getSettingValue: jest.fn().mockImplementation((settingName: string) => {
|
getSettingValue: vi.fn().mockImplementation((settingName: string) => {
|
||||||
return platformSettings[settingName];
|
return platformSettings[settingName];
|
||||||
}),
|
}),
|
||||||
reload: jest.fn(),
|
reload: vi.fn(),
|
||||||
} as unknown as BasePlatform);
|
} as unknown as BasePlatform);
|
||||||
|
|
||||||
TEST_DATA.forEach((d) => {
|
TEST_DATA.forEach((d) => {
|
||||||
@@ -100,21 +103,21 @@ describe("SettingsStore", () => {
|
|||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
client = stubClient();
|
client = stubClient();
|
||||||
room = mkStubRoom("!room:example.org", "Room", client);
|
room = mkStubRoom("!room:example.org", "Room", client);
|
||||||
client.getRooms = jest.fn().mockReturnValue([room]);
|
client.getRooms = vi.fn().mockReturnValue([room]);
|
||||||
client.getRoom = jest.fn().mockReturnValue(room);
|
client.getRoom = vi.fn().mockReturnValue(room);
|
||||||
});
|
});
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
jest.restoreAllMocks();
|
vi.restoreAllMocks();
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("Migrate media preview configuration", () => {
|
describe("Migrate media preview configuration", () => {
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
MatrixClientBackedController.matrixClient = client;
|
MatrixClientBackedController.matrixClient = client;
|
||||||
client.getAccountData = jest.fn().mockImplementation((type) => {
|
client.getAccountData = vi.fn().mockImplementation((type) => {
|
||||||
if (type === "im.vector.web.settings") {
|
if (type === "im.vector.web.settings") {
|
||||||
return {
|
return {
|
||||||
getContent: jest.fn().mockReturnValue({
|
getContent: vi.fn().mockReturnValue({
|
||||||
showImages: false,
|
showImages: false,
|
||||||
showAvatarsOnInvites: false,
|
showAvatarsOnInvites: false,
|
||||||
}),
|
}),
|
||||||
@@ -126,7 +129,7 @@ describe("SettingsStore", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("migrates media preview configuration immediately", async () => {
|
it("migrates media preview configuration immediately", async () => {
|
||||||
client.setAccountData = jest.fn();
|
client.setAccountData = vi.fn();
|
||||||
SettingsStore.runMigrations(false);
|
SettingsStore.runMigrations(false);
|
||||||
expect(client.setAccountData).toHaveBeenCalledWith("io.element.msc4278.media_preview_config", {
|
expect(client.setAccountData).toHaveBeenCalledWith("io.element.msc4278.media_preview_config", {
|
||||||
invite_avatars: "off",
|
invite_avatars: "off",
|
||||||
@@ -134,13 +137,13 @@ describe("SettingsStore", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
it("migrates media preview configuration once client is ready", async () => {
|
it("migrates media preview configuration once client is ready", async () => {
|
||||||
client.setAccountData = jest.fn();
|
client.setAccountData = vi.fn();
|
||||||
const mockInitialSync = (client.isInitialSyncComplete = jest.fn().mockReturnValue(false));
|
const mockInitialSync = (client.isInitialSyncComplete = vi.fn().mockReturnValue(false));
|
||||||
SettingsStore.runMigrations(false);
|
SettingsStore.runMigrations(false);
|
||||||
mockInitialSync.mockReturnValue(true);
|
mockInitialSync.mockReturnValue(true);
|
||||||
client.emit(ClientEvent.Sync, SyncState.Prepared, null);
|
client.emit(ClientEvent.Sync, SyncState.Prepared, null);
|
||||||
// Update is asynchronous
|
// Update is asynchronous
|
||||||
waitFor(() => {
|
await waitFor(() => {
|
||||||
expect(client.setAccountData).toHaveBeenCalledWith("io.element.msc4278.media_preview_config", {
|
expect(client.setAccountData).toHaveBeenCalledWith("io.element.msc4278.media_preview_config", {
|
||||||
invite_avatars: "off",
|
invite_avatars: "off",
|
||||||
media_previews: "off",
|
media_previews: "off",
|
||||||
@@ -149,15 +152,15 @@ describe("SettingsStore", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("does not migrate media preview configuration if the session is fresh", async () => {
|
it("does not migrate media preview configuration if the session is fresh", async () => {
|
||||||
client.setAccountData = jest.fn();
|
client.setAccountData = vi.fn();
|
||||||
SettingsStore.runMigrations(true);
|
SettingsStore.runMigrations(true);
|
||||||
client.emit(ClientEvent.Sync, SyncState.Prepared, null);
|
client.emit(ClientEvent.Sync, SyncState.Prepared, null);
|
||||||
expect(client.setAccountData).not.toHaveBeenCalled();
|
expect(client.setAccountData).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("does not migrate media preview configuration if the account data is already set", async () => {
|
it("does not migrate media preview configuration if the account data is already set", async () => {
|
||||||
client.setAccountData = jest.fn();
|
client.setAccountData = vi.fn();
|
||||||
client.getAccountData = jest.fn().mockReturnValue({});
|
client.getAccountData = vi.fn().mockReturnValue({});
|
||||||
SettingsStore.runMigrations(false);
|
SettingsStore.runMigrations(false);
|
||||||
client.emit(ClientEvent.Sync, SyncState.Prepared, null);
|
client.emit(ClientEvent.Sync, SyncState.Prepared, null);
|
||||||
expect(client.setAccountData).not.toHaveBeenCalled();
|
expect(client.setAccountData).not.toHaveBeenCalled();
|
||||||
@@ -10,6 +10,8 @@ Please see LICENSE files in the repository root for full details.
|
|||||||
import { logger } from "matrix-js-sdk/src/logger";
|
import { logger } from "matrix-js-sdk/src/logger";
|
||||||
import { type ReactNode } from "react";
|
import { type ReactNode } from "react";
|
||||||
import { ClientEvent } from "matrix-js-sdk/src/matrix";
|
import { ClientEvent } from "matrix-js-sdk/src/matrix";
|
||||||
|
// Imports directly from shared-components to avoid an import cycle
|
||||||
|
import { _t } from "@element-hq/web-shared-components";
|
||||||
|
|
||||||
import DeviceSettingsHandler from "./handlers/DeviceSettingsHandler";
|
import DeviceSettingsHandler from "./handlers/DeviceSettingsHandler";
|
||||||
import RoomDeviceSettingsHandler from "./handlers/RoomDeviceSettingsHandler";
|
import RoomDeviceSettingsHandler from "./handlers/RoomDeviceSettingsHandler";
|
||||||
@@ -18,7 +20,6 @@ import RoomAccountSettingsHandler from "./handlers/RoomAccountSettingsHandler";
|
|||||||
import AccountSettingsHandler from "./handlers/AccountSettingsHandler";
|
import AccountSettingsHandler from "./handlers/AccountSettingsHandler";
|
||||||
import RoomSettingsHandler from "./handlers/RoomSettingsHandler";
|
import RoomSettingsHandler from "./handlers/RoomSettingsHandler";
|
||||||
import ConfigSettingsHandler from "./handlers/ConfigSettingsHandler";
|
import ConfigSettingsHandler from "./handlers/ConfigSettingsHandler";
|
||||||
import { _t } from "../languageHandler";
|
|
||||||
import dis from "../dispatcher/dispatcher";
|
import dis from "../dispatcher/dispatcher";
|
||||||
import {
|
import {
|
||||||
type IFeature,
|
type IFeature,
|
||||||
|
|||||||
+3
-1
@@ -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.
|
Please see LICENSE files in the repository root for full details.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { ImageSize, suggestedSize } from "../../../../src/settings/enums/ImageSize";
|
import { describe, it, expect } from "vitest";
|
||||||
|
|
||||||
|
import { ImageSize, suggestedSize } from "./ImageSize";
|
||||||
|
|
||||||
describe("ImageSize", () => {
|
describe("ImageSize", () => {
|
||||||
describe("suggestedSize", () => {
|
describe("suggestedSize", () => {
|
||||||
+8
-4
@@ -6,10 +6,14 @@ SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Com
|
|||||||
Please see LICENSE files in the repository root for full details.
|
Please see LICENSE files in the repository root for full details.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import SettingsStore from "../../../../src/settings/SettingsStore";
|
// @vitest-environment happy-dom
|
||||||
import ThemeWatcher from "../../../../src/settings/watchers/ThemeWatcher";
|
|
||||||
import { type SettingLevel } from "../../../../src/settings/SettingLevel";
|
import { describe, it, expect } from "vitest";
|
||||||
import { type SettingKey, type Settings } from "../../../../src/settings/Settings.tsx";
|
|
||||||
|
import SettingsStore from "../SettingsStore";
|
||||||
|
import ThemeWatcher from "./ThemeWatcher";
|
||||||
|
import { type SettingLevel } from "../SettingLevel";
|
||||||
|
import { type SettingKey, type Settings } from "../Settings.tsx";
|
||||||
|
|
||||||
function makeMatchMedia(values: any) {
|
function makeMatchMedia(values: any) {
|
||||||
class FakeMediaQueryList {
|
class FakeMediaQueryList {
|
||||||
@@ -5,9 +5,12 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
|||||||
Please see LICENSE files in the repository root for full details.
|
Please see LICENSE files in the repository root for full details.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { beforeEach } from "vitest";
|
import { vi, beforeEach } from "vitest";
|
||||||
import fetchMock, { manageFetchMockGlobally } from "@fetch-mock/vitest";
|
import fetchMock, { manageFetchMockGlobally } from "@fetch-mock/vitest";
|
||||||
|
|
||||||
|
import { mocks } from "../../test/setup/mocks.ts";
|
||||||
|
import SdkConfig, { DEFAULTS } from "../SdkConfig";
|
||||||
|
|
||||||
manageFetchMockGlobally();
|
manageFetchMockGlobally();
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
@@ -16,3 +19,16 @@ beforeEach(() => {
|
|||||||
fetchMock.catch(404);
|
fetchMock.catch(404);
|
||||||
fetchMock.mockGlobal();
|
fetchMock.mockGlobal();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// set up AudioContext API mock
|
||||||
|
vi.stubGlobal("AudioContext", function () {
|
||||||
|
return mocks.AudioContext;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (globalThis.window === undefined) {
|
||||||
|
// We are in a node environment, stub a basic window so singletons work
|
||||||
|
vi.stubGlobal("window", {});
|
||||||
|
}
|
||||||
|
|
||||||
|
// uninitialised SdkConfig causes lots of warnings in console, init with defaults
|
||||||
|
SdkConfig.put(DEFAULTS);
|
||||||
|
|||||||
+27
-25
@@ -6,19 +6,21 @@
|
|||||||
* Please see LICENSE files in the repository root for full details.
|
* Please see LICENSE files in the repository root for full details.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
// @vitest-environment happy-dom
|
||||||
|
|
||||||
|
import { vi, describe, it, test, expect, beforeEach } from "vitest";
|
||||||
import { EventTimeline, EventType, type IEvent, type MatrixClient, MatrixEvent, Room } from "matrix-js-sdk/src/matrix";
|
import { EventTimeline, EventType, type IEvent, type MatrixClient, MatrixEvent, Room } from "matrix-js-sdk/src/matrix";
|
||||||
import { mocked } from "jest-mock";
|
|
||||||
|
|
||||||
import { createTestClient } from "../../test-utils";
|
import { createTestClient } from "../../test/test-utils";
|
||||||
import PinningUtils from "../../../src/utils/PinningUtils";
|
import PinningUtils from "./PinningUtils";
|
||||||
import SettingsStore from "../../../src/settings/SettingsStore";
|
import SettingsStore from "../settings/SettingsStore";
|
||||||
import { isContentActionable } from "../../../src/utils/EventUtils";
|
import { isContentActionable } from "./EventUtils";
|
||||||
import { ReadPinsEventId } from "../../../src/components/views/right_panel/types";
|
import { ReadPinsEventId } from "../components/views/right_panel/types";
|
||||||
|
|
||||||
jest.mock("../../../src/utils/EventUtils", () => {
|
vi.mock("./EventUtils", () => {
|
||||||
return {
|
return {
|
||||||
isContentActionable: jest.fn(),
|
isContentActionable: vi.fn(),
|
||||||
canPinEvent: jest.fn(),
|
canPinEvent: vi.fn(),
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -26,7 +28,7 @@ describe("PinningUtils", () => {
|
|||||||
const roomId = "!room:example.org";
|
const roomId = "!room:example.org";
|
||||||
const userId = "@alice:example.org";
|
const userId = "@alice:example.org";
|
||||||
|
|
||||||
const mockedIsContentActionable = mocked(isContentActionable);
|
const mockedIsContentActionable = vi.mocked(isContentActionable);
|
||||||
|
|
||||||
let matrixClient: MatrixClient;
|
let matrixClient: MatrixClient;
|
||||||
let room: Room;
|
let room: Room;
|
||||||
@@ -52,14 +54,14 @@ describe("PinningUtils", () => {
|
|||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
// Enable feature pinning
|
// Enable feature pinning
|
||||||
jest.spyOn(SettingsStore, "getValue").mockReturnValue(true);
|
vi.spyOn(SettingsStore, "getValue").mockReturnValue(true);
|
||||||
mockedIsContentActionable.mockImplementation(() => true);
|
mockedIsContentActionable.mockImplementation(() => true);
|
||||||
|
|
||||||
matrixClient = createTestClient();
|
matrixClient = createTestClient();
|
||||||
room = new Room(roomId, matrixClient, userId);
|
room = new Room(roomId, matrixClient, userId);
|
||||||
matrixClient.getRoom = jest.fn().mockReturnValue(room);
|
matrixClient.getRoom = vi.fn().mockReturnValue(room);
|
||||||
|
|
||||||
jest.spyOn(
|
vi.spyOn(
|
||||||
matrixClient.getRoom(roomId)!.getLiveTimeline().getState(EventTimeline.FORWARDS)!,
|
matrixClient.getRoom(roomId)!.getLiveTimeline().getState(EventTimeline.FORWARDS)!,
|
||||||
"mayClientSendStateEvent",
|
"mayClientSendStateEvent",
|
||||||
).mockReturnValue(true);
|
).mockReturnValue(true);
|
||||||
@@ -96,14 +98,14 @@ describe("PinningUtils", () => {
|
|||||||
|
|
||||||
describe("isPinned", () => {
|
describe("isPinned", () => {
|
||||||
test("should return false if no room", () => {
|
test("should return false if no room", () => {
|
||||||
matrixClient.getRoom = jest.fn().mockReturnValue(undefined);
|
matrixClient.getRoom = vi.fn().mockReturnValue(undefined);
|
||||||
const event = makePinEvent();
|
const event = makePinEvent();
|
||||||
|
|
||||||
expect(PinningUtils.isPinned(matrixClient, event)).toBe(false);
|
expect(PinningUtils.isPinned(matrixClient, event)).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("should return false if no pinned event", () => {
|
test("should return false if no pinned event", () => {
|
||||||
jest.spyOn(
|
vi.spyOn(
|
||||||
matrixClient.getRoom(roomId)!.getLiveTimeline().getState(EventTimeline.FORWARDS)!,
|
matrixClient.getRoom(roomId)!.getLiveTimeline().getState(EventTimeline.FORWARDS)!,
|
||||||
"getStateEvents",
|
"getStateEvents",
|
||||||
).mockReturnValue(null);
|
).mockReturnValue(null);
|
||||||
@@ -113,7 +115,7 @@ describe("PinningUtils", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("should return false if pinned events do not contain the event id", () => {
|
test("should return false if pinned events do not contain the event id", () => {
|
||||||
jest.spyOn(
|
vi.spyOn(
|
||||||
matrixClient.getRoom(roomId)!.getLiveTimeline().getState(EventTimeline.FORWARDS)!,
|
matrixClient.getRoom(roomId)!.getLiveTimeline().getState(EventTimeline.FORWARDS)!,
|
||||||
"getStateEvents",
|
"getStateEvents",
|
||||||
).mockReturnValue({
|
).mockReturnValue({
|
||||||
@@ -127,7 +129,7 @@ describe("PinningUtils", () => {
|
|||||||
|
|
||||||
test("should return true if pinned events contains the event id", () => {
|
test("should return true if pinned events contains the event id", () => {
|
||||||
const event = makePinEvent();
|
const event = makePinEvent();
|
||||||
jest.spyOn(
|
vi.spyOn(
|
||||||
matrixClient.getRoom(roomId)!.getLiveTimeline().getState(EventTimeline.FORWARDS)!,
|
matrixClient.getRoom(roomId)!.getLiveTimeline().getState(EventTimeline.FORWARDS)!,
|
||||||
"getStateEvents",
|
"getStateEvents",
|
||||||
).mockReturnValue({
|
).mockReturnValue({
|
||||||
@@ -149,14 +151,14 @@ describe("PinningUtils", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("should return false if no room", () => {
|
test("should return false if no room", () => {
|
||||||
matrixClient.getRoom = jest.fn().mockReturnValue(undefined);
|
matrixClient.getRoom = vi.fn().mockReturnValue(undefined);
|
||||||
const event = makePinEvent();
|
const event = makePinEvent();
|
||||||
|
|
||||||
expect(PinningUtils.canPin(matrixClient, event)).toBe(false);
|
expect(PinningUtils.canPin(matrixClient, event)).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("should return false if client cannot send state event", () => {
|
test("should return false if client cannot send state event", () => {
|
||||||
jest.spyOn(
|
vi.spyOn(
|
||||||
matrixClient.getRoom(roomId)!.getLiveTimeline().getState(EventTimeline.FORWARDS)!,
|
matrixClient.getRoom(roomId)!.getLiveTimeline().getState(EventTimeline.FORWARDS)!,
|
||||||
"mayClientSendStateEvent",
|
"mayClientSendStateEvent",
|
||||||
).mockReturnValue(false);
|
).mockReturnValue(false);
|
||||||
@@ -201,7 +203,7 @@ describe("PinningUtils", () => {
|
|||||||
|
|
||||||
describe("pinOrUnpinEvent", () => {
|
describe("pinOrUnpinEvent", () => {
|
||||||
test("should do nothing if no room", async () => {
|
test("should do nothing if no room", async () => {
|
||||||
matrixClient.getRoom = jest.fn().mockReturnValue(undefined);
|
matrixClient.getRoom = vi.fn().mockReturnValue(undefined);
|
||||||
const event = makePinEvent();
|
const event = makePinEvent();
|
||||||
|
|
||||||
await PinningUtils.pinOrUnpinEvent(matrixClient, event);
|
await PinningUtils.pinOrUnpinEvent(matrixClient, event);
|
||||||
@@ -216,7 +218,7 @@ describe("PinningUtils", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("should pin the event if not pinned", async () => {
|
test("should pin the event if not pinned", async () => {
|
||||||
jest.spyOn(
|
vi.spyOn(
|
||||||
matrixClient.getRoom(roomId)!.getLiveTimeline().getState(EventTimeline.FORWARDS)!,
|
matrixClient.getRoom(roomId)!.getLiveTimeline().getState(EventTimeline.FORWARDS)!,
|
||||||
"getStateEvents",
|
"getStateEvents",
|
||||||
).mockReturnValue({
|
).mockReturnValue({
|
||||||
@@ -224,8 +226,8 @@ describe("PinningUtils", () => {
|
|||||||
getContent: () => ({ pinned: ["$otherEventId"] }),
|
getContent: () => ({ pinned: ["$otherEventId"] }),
|
||||||
});
|
});
|
||||||
|
|
||||||
jest.spyOn(room, "getAccountData").mockReturnValue({
|
vi.spyOn(room, "getAccountData").mockReturnValue({
|
||||||
getContent: jest.fn().mockReturnValue({
|
getContent: vi.fn().mockReturnValue({
|
||||||
event_ids: ["$otherEventId"],
|
event_ids: ["$otherEventId"],
|
||||||
}),
|
}),
|
||||||
} as unknown as MatrixEvent);
|
} as unknown as MatrixEvent);
|
||||||
@@ -247,7 +249,7 @@ describe("PinningUtils", () => {
|
|||||||
test("should unpin the event if already pinned", async () => {
|
test("should unpin the event if already pinned", async () => {
|
||||||
const event = makePinEvent();
|
const event = makePinEvent();
|
||||||
|
|
||||||
jest.spyOn(
|
vi.spyOn(
|
||||||
matrixClient.getRoom(roomId)!.getLiveTimeline().getState(EventTimeline.FORWARDS)!,
|
matrixClient.getRoom(roomId)!.getLiveTimeline().getState(EventTimeline.FORWARDS)!,
|
||||||
"getStateEvents",
|
"getStateEvents",
|
||||||
).mockReturnValue({
|
).mockReturnValue({
|
||||||
@@ -271,7 +273,7 @@ describe("PinningUtils", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("should return false if client cannot send state event", () => {
|
test("should return false if client cannot send state event", () => {
|
||||||
jest.spyOn(
|
vi.spyOn(
|
||||||
matrixClient.getRoom(roomId)!.getLiveTimeline().getState(EventTimeline.FORWARDS)!,
|
matrixClient.getRoom(roomId)!.getLiveTimeline().getState(EventTimeline.FORWARDS)!,
|
||||||
"mayClientSendStateEvent",
|
"mayClientSendStateEvent",
|
||||||
).mockReturnValue(false);
|
).mockReturnValue(false);
|
||||||
+8
-6
@@ -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.
|
Please see LICENSE files in the repository root for full details.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { Singleflight } from "../../../src/utils/Singleflight";
|
import { vi, describe, it, expect, afterEach } from "vitest";
|
||||||
|
|
||||||
|
import { Singleflight } from "./Singleflight";
|
||||||
|
|
||||||
describe("Singleflight", () => {
|
describe("Singleflight", () => {
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
@@ -28,7 +30,7 @@ describe("Singleflight", () => {
|
|||||||
const instance = {};
|
const instance = {};
|
||||||
const key = "test";
|
const key = "test";
|
||||||
const val = {}; // unique object for reference check
|
const val = {}; // unique object for reference check
|
||||||
const fn = jest.fn().mockReturnValue(val);
|
const fn = vi.fn().mockReturnValue(val);
|
||||||
const sf = Singleflight.for(instance, key);
|
const sf = Singleflight.for(instance, key);
|
||||||
const r1 = sf.do(fn);
|
const r1 = sf.do(fn);
|
||||||
expect(r1).toBe(val);
|
expect(r1).toBe(val);
|
||||||
@@ -42,7 +44,7 @@ describe("Singleflight", () => {
|
|||||||
const instance = {};
|
const instance = {};
|
||||||
const key = "test";
|
const key = "test";
|
||||||
const val = {}; // unique object for reference check
|
const val = {}; // unique object for reference check
|
||||||
const fn = jest.fn().mockReturnValue(val);
|
const fn = vi.fn().mockReturnValue(val);
|
||||||
let sf = Singleflight.for(instance, key);
|
let sf = Singleflight.for(instance, key);
|
||||||
const r1 = sf.do(fn);
|
const r1 = sf.do(fn);
|
||||||
expect(r1).toBe(val);
|
expect(r1).toBe(val);
|
||||||
@@ -57,7 +59,7 @@ describe("Singleflight", () => {
|
|||||||
const instance = {};
|
const instance = {};
|
||||||
const key = "test";
|
const key = "test";
|
||||||
const val = {}; // unique object for reference check
|
const val = {}; // unique object for reference check
|
||||||
const fn = jest.fn().mockReturnValue(val);
|
const fn = vi.fn().mockReturnValue(val);
|
||||||
const sf = Singleflight.for(instance, key);
|
const sf = Singleflight.for(instance, key);
|
||||||
const r1 = sf.do(fn);
|
const r1 = sf.do(fn);
|
||||||
expect(r1).toBe(val);
|
expect(r1).toBe(val);
|
||||||
@@ -72,7 +74,7 @@ describe("Singleflight", () => {
|
|||||||
const instance = {};
|
const instance = {};
|
||||||
const key = "test";
|
const key = "test";
|
||||||
const val = {}; // unique object for reference check
|
const val = {}; // unique object for reference check
|
||||||
const fn = jest.fn().mockReturnValue(val);
|
const fn = vi.fn().mockReturnValue(val);
|
||||||
const sf = Singleflight.for(instance, key);
|
const sf = Singleflight.for(instance, key);
|
||||||
const r1 = sf.do(fn);
|
const r1 = sf.do(fn);
|
||||||
expect(r1).toBe(val);
|
expect(r1).toBe(val);
|
||||||
@@ -87,7 +89,7 @@ describe("Singleflight", () => {
|
|||||||
const instance = {};
|
const instance = {};
|
||||||
const key = "test";
|
const key = "test";
|
||||||
const val = {}; // unique object for reference check
|
const val = {}; // unique object for reference check
|
||||||
const fn = jest.fn().mockReturnValue(val);
|
const fn = vi.fn().mockReturnValue(val);
|
||||||
const sf = Singleflight.for(instance, key);
|
const sf = Singleflight.for(instance, key);
|
||||||
const r1 = sf.do(fn);
|
const r1 = sf.do(fn);
|
||||||
expect(r1).toBe(val);
|
expect(r1).toBe(val);
|
||||||
@@ -5,12 +5,16 @@ SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Com
|
|||||||
Please see LICENSE files in the repository root for full details.
|
Please see LICENSE files in the repository root for full details.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { onSubmitPreventDefault } from "../../../src/utils/form.ts";
|
// @vitest-environment happy-dom
|
||||||
|
|
||||||
|
import { vi, describe, it, expect } from "vitest";
|
||||||
|
|
||||||
|
import { onSubmitPreventDefault } from "./form.ts";
|
||||||
|
|
||||||
describe("onSubmitPreventDefault", () => {
|
describe("onSubmitPreventDefault", () => {
|
||||||
it("should preventDefault", () => {
|
it("should preventDefault", () => {
|
||||||
const event = new SubmitEvent("submit");
|
const event = new SubmitEvent("submit");
|
||||||
const spy = jest.spyOn(event, "preventDefault");
|
const spy = vi.spyOn(event, "preventDefault");
|
||||||
|
|
||||||
onSubmitPreventDefault(event);
|
onSubmitPreventDefault(event);
|
||||||
expect(spy).toHaveBeenCalled();
|
expect(spy).toHaveBeenCalled();
|
||||||
@@ -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.
|
Please see LICENSE files in the repository root for full details.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { EnhancedMap, mapDiff } from "../../../src/utils/maps";
|
import { describe, it, expect } from "vitest";
|
||||||
|
|
||||||
|
import { EnhancedMap, mapDiff } from "./maps";
|
||||||
|
|
||||||
describe("maps", () => {
|
describe("maps", () => {
|
||||||
describe("mapDiff", () => {
|
describe("mapDiff", () => {
|
||||||
@@ -6,8 +6,6 @@ SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Com
|
|||||||
Please see LICENSE files in the repository root for full details.
|
Please see LICENSE files in the repository root for full details.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// @vitest-environment happy-dom
|
|
||||||
|
|
||||||
import { vi, describe, it, expect, beforeEach, afterAll } from "vitest";
|
import { vi, describe, it, expect, beforeEach, afterAll } from "vitest";
|
||||||
import fetchMock from "@fetch-mock/vitest";
|
import fetchMock from "@fetch-mock/vitest";
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
/*
|
||||||
|
Copyright 2026 Element Creations Ltd.
|
||||||
|
|
||||||
|
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
|
||||||
|
Please see LICENSE files in the repository root for full details.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { vi } from "vitest";
|
||||||
|
import { mocked as jestMocked } from "jest-mock";
|
||||||
|
|
||||||
|
const isJest = typeof jest !== "undefined";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Subset of the vitest API surface, with jest equivalents for the same functions when running under jest.
|
||||||
|
*/
|
||||||
|
const adapter = {
|
||||||
|
fn: isJest ? (jest.fn as unknown as typeof vi.fn) : vi.fn,
|
||||||
|
spyOn: isJest ? (jest.spyOn as unknown as typeof vi.spyOn) : vi.spyOn,
|
||||||
|
mocked: isJest ? (jestMocked as typeof vi.mocked) : vi.mocked,
|
||||||
|
} as Pick<typeof vi, "fn" | "spyOn" | "mocked">;
|
||||||
|
|
||||||
|
const mocked = adapter.mocked;
|
||||||
|
export { adapter as vi, mocked };
|
||||||
|
|
||||||
|
export { type Mocked, type MockedObject } from "vitest";
|
||||||
@@ -6,23 +6,25 @@ SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Com
|
|||||||
Please see LICENSE files in the repository root for full details.
|
Please see LICENSE files in the repository root for full details.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import { vi } from "./adapter.ts";
|
||||||
|
|
||||||
export const mocks = {
|
export const mocks = {
|
||||||
AudioBufferSourceNode: {
|
AudioBufferSourceNode: {
|
||||||
connect: jest.fn(),
|
connect: vi.fn(),
|
||||||
start: jest.fn(),
|
start: vi.fn(),
|
||||||
stop: jest.fn(),
|
stop: vi.fn(),
|
||||||
} as unknown as AudioBufferSourceNode,
|
} as unknown as AudioBufferSourceNode,
|
||||||
AudioContext: {
|
AudioContext: {
|
||||||
close: jest.fn(),
|
close: vi.fn(),
|
||||||
createMediaElementSource: jest.fn(),
|
createMediaElementSource: vi.fn(),
|
||||||
createMediaStreamDestination: jest.fn(),
|
createMediaStreamDestination: vi.fn(),
|
||||||
createMediaStreamSource: jest.fn(),
|
createMediaStreamSource: vi.fn(),
|
||||||
createStreamTrackSource: jest.fn(),
|
createStreamTrackSource: vi.fn(),
|
||||||
createBufferSource: jest.fn((): AudioBufferSourceNode => ({ ...mocks.AudioBufferSourceNode })),
|
createBufferSource: vi.fn((): AudioBufferSourceNode => ({ ...mocks.AudioBufferSourceNode })),
|
||||||
getOutputTimestamp: jest.fn(),
|
getOutputTimestamp: vi.fn(),
|
||||||
resume: jest.fn(),
|
resume: vi.fn(),
|
||||||
setSinkId: jest.fn(),
|
setSinkId: vi.fn(),
|
||||||
suspend: jest.fn(),
|
suspend: vi.fn(),
|
||||||
decodeAudioData: jest.fn(),
|
decodeAudioData: vi.fn(),
|
||||||
} as unknown as AudioContext,
|
} as unknown as AudioContext,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import { env } from "process";
|
|||||||
import "@testing-library/jest-dom";
|
import "@testing-library/jest-dom";
|
||||||
import "blob-polyfill";
|
import "blob-polyfill";
|
||||||
import { secureRandomString } from "matrix-js-sdk/src/randomstring";
|
import { secureRandomString } from "matrix-js-sdk/src/randomstring";
|
||||||
import { mocked } from "jest-mock";
|
import { mocked } from "jest-mock-vitest-adapter";
|
||||||
|
|
||||||
import { PredictableRandom } from "./test-utils/predictableRandom";
|
import { PredictableRandom } from "./test-utils/predictableRandom";
|
||||||
import * as rageshake from "../src/rageshake/rageshake";
|
import * as rageshake from "../src/rageshake/rageshake";
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Com
|
|||||||
Please see LICENSE files in the repository root for full details.
|
Please see LICENSE files in the repository root for full details.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { type MockedObject } from "jest-mock";
|
import { type MockedObject } from "jest-mock-vitest-adapter";
|
||||||
import {
|
import {
|
||||||
type MatrixClient,
|
type MatrixClient,
|
||||||
MatrixEvent,
|
MatrixEvent,
|
||||||
@@ -165,7 +165,7 @@ export const mockGeolocation = (): MockedObject<Geolocation> => {
|
|||||||
* See for error codes: https://developer.mozilla.org/en-US/docs/Web/API/GeolocationPositionError
|
* See for error codes: https://developer.mozilla.org/en-US/docs/Web/API/GeolocationPositionError
|
||||||
*/
|
*/
|
||||||
export const watchPositionMockImplementation = (delays: number[], errorCodes: number[] = []) => {
|
export const watchPositionMockImplementation = (delays: number[], errorCodes: number[] = []) => {
|
||||||
return (callback: PositionCallback, error: PositionErrorCallback): number => {
|
return (callback: PositionCallback, error?: PositionErrorCallback | null): number => {
|
||||||
const position = makeGeolocationPosition({});
|
const position = makeGeolocationPosition({});
|
||||||
|
|
||||||
let totalDelay = 0;
|
let totalDelay = 0;
|
||||||
@@ -173,7 +173,7 @@ export const watchPositionMockImplementation = (delays: number[], errorCodes: nu
|
|||||||
totalDelay += delayMs;
|
totalDelay += delayMs;
|
||||||
const timeout = window.setTimeout(() => {
|
const timeout = window.setTimeout(() => {
|
||||||
if (errorCodes[index]) {
|
if (errorCodes[index]) {
|
||||||
error(getMockGeolocationPositionError(errorCodes[index], "error message"));
|
error?.(getMockGeolocationPositionError(errorCodes[index], "error message"));
|
||||||
} else {
|
} else {
|
||||||
callback({ ...position, timestamp: position.timestamp + totalDelay });
|
callback({ ...position, timestamp: position.timestamp + totalDelay });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,11 +7,14 @@ Please see LICENSE files in the repository root for full details.
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import EventEmitter from "events";
|
import EventEmitter from "events";
|
||||||
import { type MethodLikeKeys, mocked, type MockedObject, type PropertyLikeKeys } from "jest-mock";
|
import { type MockedObject } from "vitest";
|
||||||
|
import { type MethodLikeKeys, type PropertyLikeKeys } from "jest-mock";
|
||||||
|
import { type MockedObjectDeep } from "@vitest/spy";
|
||||||
import { Feature, ServerSupport } from "matrix-js-sdk/src/feature";
|
import { Feature, ServerSupport } from "matrix-js-sdk/src/feature";
|
||||||
import { type MatrixClient, type Room, User } from "matrix-js-sdk/src/matrix";
|
import { type MatrixClient, type Room, User } from "matrix-js-sdk/src/matrix";
|
||||||
|
|
||||||
import { MatrixClientPeg } from "../../src/MatrixClientPeg";
|
import { MatrixClientPeg } from "../../src/MatrixClientPeg";
|
||||||
|
import { vi } from "../setup/adapter.ts";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Mocked generic class with a real EventEmitter.
|
* Mocked generic class with a real EventEmitter.
|
||||||
@@ -53,7 +56,7 @@ export class MockClientWithEventEmitter extends EventEmitter {
|
|||||||
* eg
|
* eg
|
||||||
* ```
|
* ```
|
||||||
* const mockClient = getMockClientWithEventEmitter({
|
* const mockClient = getMockClientWithEventEmitter({
|
||||||
getUserId: jest.fn().mockReturnValue(aliceId),
|
getUserId: vi.fn().mockReturnValue(aliceId),
|
||||||
});
|
});
|
||||||
* ```
|
* ```
|
||||||
*
|
*
|
||||||
@@ -62,10 +65,10 @@ export class MockClientWithEventEmitter extends EventEmitter {
|
|||||||
export const getMockClientWithEventEmitter = (
|
export const getMockClientWithEventEmitter = (
|
||||||
mockProperties: Partial<Record<keyof MatrixClient, unknown>>,
|
mockProperties: Partial<Record<keyof MatrixClient, unknown>>,
|
||||||
): MockedObject<MatrixClient> => {
|
): MockedObject<MatrixClient> => {
|
||||||
const mock = mocked(new MockClientWithEventEmitter(mockProperties) as unknown as MatrixClient);
|
const mock = vi.mocked(new MockClientWithEventEmitter(mockProperties) as unknown as MatrixClient);
|
||||||
|
|
||||||
jest.spyOn(MatrixClientPeg, "get").mockReturnValue(mock);
|
vi.spyOn(MatrixClientPeg, "get").mockReturnValue(mock);
|
||||||
jest.spyOn(MatrixClientPeg, "safeGet").mockReturnValue(mock);
|
vi.spyOn(MatrixClientPeg, "safeGet").mockReturnValue(mock);
|
||||||
|
|
||||||
// @ts-ignore simplified test stub
|
// @ts-ignore simplified test stub
|
||||||
mock.canSupport = new Map();
|
mock.canSupport = new Map();
|
||||||
@@ -76,8 +79,8 @@ export const getMockClientWithEventEmitter = (
|
|||||||
};
|
};
|
||||||
|
|
||||||
export const unmockClientPeg = () => {
|
export const unmockClientPeg = () => {
|
||||||
jest.spyOn(MatrixClientPeg, "get").mockRestore();
|
vi.spyOn(MatrixClientPeg, "get").mockRestore();
|
||||||
jest.spyOn(MatrixClientPeg, "safeGet").mockRestore();
|
vi.spyOn(MatrixClientPeg, "safeGet").mockRestore();
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -88,19 +91,20 @@ export const unmockClientPeg = () => {
|
|||||||
});
|
});
|
||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
export const mockClientMethodsUser = (userId = "@alice:domain") => ({
|
export const mockClientMethodsUser = (userId = "@alice:domain") =>
|
||||||
getUserId: jest.fn().mockReturnValue(userId),
|
({
|
||||||
getDomain: jest.fn().mockReturnValue(userId.split(":")[1]),
|
getUserId: vi.fn().mockReturnValue(userId),
|
||||||
getSafeUserId: jest.fn().mockReturnValue(userId),
|
getDomain: vi.fn().mockReturnValue(userId.split(":")[1]),
|
||||||
getUser: jest.fn().mockReturnValue(new User(userId)),
|
getSafeUserId: vi.fn().mockReturnValue(userId),
|
||||||
isGuest: jest.fn().mockReturnValue(false),
|
getUser: vi.fn().mockReturnValue(new User(userId)),
|
||||||
mxcUrlToHttp: jest.fn().mockReturnValue("mock-mxcUrlToHttp"),
|
isGuest: vi.fn().mockReturnValue(false),
|
||||||
credentials: { userId },
|
mxcUrlToHttp: vi.fn().mockReturnValue("mock-mxcUrlToHttp"),
|
||||||
getThreePids: jest.fn().mockResolvedValue({ threepids: [] }),
|
credentials: { userId },
|
||||||
getAccessToken: jest.fn(),
|
getThreePids: vi.fn().mockResolvedValue({ threepids: [] }),
|
||||||
getDeviceId: jest.fn(),
|
getAccessToken: vi.fn(),
|
||||||
getAccountData: jest.fn(),
|
getDeviceId: vi.fn(),
|
||||||
});
|
getAccountData: vi.fn(),
|
||||||
|
}) satisfies MockedObjectDeep<any>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns basic mocked client methods related to rendering events
|
* Returns basic mocked client methods related to rendering events
|
||||||
@@ -110,58 +114,60 @@ export const mockClientMethodsUser = (userId = "@alice:domain") => ({
|
|||||||
});
|
});
|
||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
export const mockClientMethodsEvents = () => ({
|
export const mockClientMethodsEvents = () =>
|
||||||
decryptEventIfNeeded: jest.fn(),
|
({
|
||||||
getPushActionsForEvent: jest.fn(),
|
decryptEventIfNeeded: vi.fn(),
|
||||||
});
|
getPushActionsForEvent: vi.fn(),
|
||||||
|
}) satisfies MockedObjectDeep<any>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns basic mocked pushProcessor
|
* Returns basic mocked pushProcessor
|
||||||
*/
|
*/
|
||||||
export const mockClientPushProcessor = () => ({
|
export const mockClientPushProcessor = () =>
|
||||||
pushProcessor: {
|
({
|
||||||
getPushRuleById: jest.fn(),
|
pushProcessor: {
|
||||||
ruleMatchesEvent: jest.fn(),
|
getPushRuleById: vi.fn(),
|
||||||
},
|
ruleMatchesEvent: vi.fn(),
|
||||||
});
|
},
|
||||||
|
}) satisfies MockedObjectDeep<any>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns basic mocked client methods related to server support
|
* Returns basic mocked client methods related to server support
|
||||||
*/
|
*/
|
||||||
export const mockClientMethodsServer = (): Partial<Record<MethodLikeKeys<MatrixClient>, unknown>> => ({
|
export const mockClientMethodsServer = (): Partial<Record<MethodLikeKeys<MatrixClient>, unknown>> => ({
|
||||||
getIdentityServerUrl: jest.fn(),
|
getIdentityServerUrl: vi.fn(),
|
||||||
getHomeserverUrl: jest.fn(),
|
getHomeserverUrl: vi.fn(),
|
||||||
getCapabilities: jest.fn().mockResolvedValue({}),
|
getCapabilities: vi.fn().mockResolvedValue({}),
|
||||||
getCachedCapabilities: jest.fn().mockResolvedValue({}),
|
getCachedCapabilities: vi.fn().mockResolvedValue({}),
|
||||||
getClientWellKnown: jest.fn().mockReturnValue({}),
|
getClientWellKnown: vi.fn().mockReturnValue({}),
|
||||||
waitForClientWellKnown: jest.fn().mockResolvedValue({}),
|
waitForClientWellKnown: vi.fn().mockResolvedValue({}),
|
||||||
doesServerSupportUnstableFeature: jest.fn().mockResolvedValue(false),
|
doesServerSupportUnstableFeature: vi.fn().mockResolvedValue(false),
|
||||||
isVersionSupported: jest.fn().mockResolvedValue(false),
|
isVersionSupported: vi.fn().mockResolvedValue(false),
|
||||||
getVersions: jest.fn().mockResolvedValue({}),
|
getVersions: vi.fn().mockResolvedValue({}),
|
||||||
isFallbackICEServerAllowed: jest.fn(),
|
isFallbackICEServerAllowed: vi.fn(),
|
||||||
});
|
});
|
||||||
|
|
||||||
export const mockClientMethodsDevice = (
|
export const mockClientMethodsDevice = (
|
||||||
deviceId = "test-device-id",
|
deviceId = "test-device-id",
|
||||||
): Partial<Record<MethodLikeKeys<MatrixClient>, unknown>> => ({
|
): Partial<Record<MethodLikeKeys<MatrixClient>, unknown>> => ({
|
||||||
getDeviceId: jest.fn().mockReturnValue(deviceId),
|
getDeviceId: vi.fn().mockReturnValue(deviceId),
|
||||||
getDevices: jest.fn().mockResolvedValue({ devices: [] }),
|
getDevices: vi.fn().mockResolvedValue({ devices: [] }),
|
||||||
});
|
});
|
||||||
|
|
||||||
export const mockClientMethodsCrypto = (): Partial<
|
export const mockClientMethodsCrypto = (): Partial<
|
||||||
Record<MethodLikeKeys<MatrixClient> & PropertyLikeKeys<MatrixClient>, unknown>
|
Record<MethodLikeKeys<MatrixClient> & PropertyLikeKeys<MatrixClient>, unknown>
|
||||||
> => ({
|
> => ({
|
||||||
isKeyBackupKeyStored: jest.fn(),
|
isKeyBackupKeyStored: vi.fn(),
|
||||||
getCrossSigningCacheCallbacks: jest.fn().mockReturnValue({ getCrossSigningKeyCache: jest.fn() }),
|
getCrossSigningCacheCallbacks: vi.fn().mockReturnValue({ getCrossSigningKeyCache: vi.fn() }),
|
||||||
secretStorage: {
|
secretStorage: {
|
||||||
hasKey: jest.fn(),
|
hasKey: vi.fn(),
|
||||||
isStored: jest.fn().mockResolvedValue(null),
|
isStored: vi.fn().mockResolvedValue(null),
|
||||||
getDefaultKeyId: jest.fn().mockResolvedValue(null),
|
getDefaultKeyId: vi.fn().mockResolvedValue(null),
|
||||||
},
|
},
|
||||||
getCrypto: jest.fn().mockReturnValue({
|
getCrypto: vi.fn().mockReturnValue({
|
||||||
getUserDeviceInfo: jest.fn(),
|
getUserDeviceInfo: vi.fn(),
|
||||||
getDeviceVerificationStatus: jest.fn().mockResolvedValue(null),
|
getDeviceVerificationStatus: vi.fn().mockResolvedValue(null),
|
||||||
getCrossSigningStatus: jest.fn().mockResolvedValue({
|
getCrossSigningStatus: vi.fn().mockResolvedValue({
|
||||||
publicKeysOnDevice: true,
|
publicKeysOnDevice: true,
|
||||||
privateKeysInSecretStorage: false,
|
privateKeysInSecretStorage: false,
|
||||||
privateKeysCachedLocally: {
|
privateKeysCachedLocally: {
|
||||||
@@ -170,19 +176,19 @@ export const mockClientMethodsCrypto = (): Partial<
|
|||||||
userSigningKey: true,
|
userSigningKey: true,
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
isCrossSigningReady: jest.fn().mockResolvedValue(true),
|
isCrossSigningReady: vi.fn().mockResolvedValue(true),
|
||||||
isSecretStorageReady: jest.fn(),
|
isSecretStorageReady: vi.fn(),
|
||||||
getSessionBackupPrivateKey: jest.fn(),
|
getSessionBackupPrivateKey: vi.fn(),
|
||||||
getVersion: jest.fn().mockReturnValue("Version 0"),
|
getVersion: vi.fn().mockReturnValue("Version 0"),
|
||||||
getOwnDeviceKeys: jest.fn().mockReturnValue(new Promise(() => {})),
|
getOwnDeviceKeys: vi.fn().mockReturnValue(new Promise(() => {})),
|
||||||
getCrossSigningKeyId: jest.fn(),
|
getCrossSigningKeyId: vi.fn(),
|
||||||
isEncryptionEnabledInRoom: jest.fn().mockResolvedValue(false),
|
isEncryptionEnabledInRoom: vi.fn().mockResolvedValue(false),
|
||||||
getKeyBackupInfo: jest.fn().mockResolvedValue(null),
|
getKeyBackupInfo: vi.fn().mockResolvedValue(null),
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
export const mockClientMethodsRooms = (rooms: Room[] = []): Partial<Record<MethodLikeKeys<MatrixClient>, unknown>> => ({
|
export const mockClientMethodsRooms = (rooms: Room[] = []): Partial<Record<MethodLikeKeys<MatrixClient>, unknown>> => ({
|
||||||
getRooms: jest.fn().mockReturnValue(rooms),
|
getRooms: vi.fn().mockReturnValue(rooms),
|
||||||
getRoom: jest.fn((roomId) => rooms.find((r) => r.roomId === roomId) ?? null),
|
getRoom: vi.fn((roomId) => rooms.find((r) => r.roomId === roomId) ?? null),
|
||||||
isRoomEncrypted: jest.fn(),
|
isRoomEncrypted: vi.fn(),
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -6,19 +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.
|
Please see LICENSE files in the repository root for full details.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import { vi } from "../setup/adapter.ts";
|
||||||
|
|
||||||
export const REPEATABLE_DATE = new Date(2022, 10, 17, 16, 58, 32, 517);
|
export const REPEATABLE_DATE = new Date(2022, 10, 17, 16, 58, 32, 517);
|
||||||
|
|
||||||
const RealDateTimeFormat = global.Intl.DateTimeFormat;
|
const RealDateTimeFormat = globalThis.Intl.DateTimeFormat;
|
||||||
|
|
||||||
// allow setting default locale and set timezone
|
// allow setting default locale and set timezone
|
||||||
// defaults to en-GB / Europe/London
|
// defaults to en-GB / Europe/London
|
||||||
// so tests run the same everywhere
|
// so tests run the same everywhere
|
||||||
export const mockIntlDateTimeFormat = (defaultLocale = "en-GB", defaultTimezone = "Europe/London"): void => {
|
export const mockIntlDateTimeFormat = (defaultLocale = "en-GB", defaultTimezone = "Europe/London"): void => {
|
||||||
jest.spyOn(global.Intl, "DateTimeFormat").mockImplementation(
|
vi.spyOn(globalThis.Intl, "DateTimeFormat").mockImplementation(function (locale, options) {
|
||||||
(locale, options) => new RealDateTimeFormat(locale || defaultLocale, { ...options, timeZone: defaultTimezone }),
|
return new RealDateTimeFormat(locale || defaultLocale, { ...options, timeZone: defaultTimezone });
|
||||||
);
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
export const unmockIntlDateTimeFormat = (): void => {
|
export const unmockIntlDateTimeFormat = (): void => {
|
||||||
jest.spyOn(global.Intl, "DateTimeFormat").mockRestore();
|
vi.spyOn(globalThis.Intl, "DateTimeFormat").mockRestore();
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Com
|
|||||||
Please see LICENSE files in the repository root for full details.
|
Please see LICENSE files in the repository root for full details.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { type RenderResult, screen, waitFor } from "jest-matrix-react";
|
import { type RenderResult, screen, waitFor } from "test-utils-rtl";
|
||||||
|
|
||||||
export * from "./beacon";
|
export * from "./beacon";
|
||||||
export * from "./client";
|
export * from "./client";
|
||||||
|
|||||||
@@ -6,11 +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.
|
Please see LICENSE files in the repository root for full details.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { type MethodLikeKeys, mocked, type MockedObject } from "jest-mock";
|
import { type MethodLikeKeys } from "jest-mock";
|
||||||
|
import { type MockedObject } from "vitest";
|
||||||
|
|
||||||
import BasePlatform from "../../src/BasePlatform";
|
import BasePlatform from "../../src/BasePlatform";
|
||||||
import PlatformPeg from "../../src/PlatformPeg";
|
import PlatformPeg from "../../src/PlatformPeg";
|
||||||
import * as SessionLock from "../../src/utils/SessionLock";
|
import * as SessionLock from "../../src/utils/SessionLock";
|
||||||
|
import { vi } from "../setup/adapter.ts";
|
||||||
|
|
||||||
// doesn't implement abstract
|
// doesn't implement abstract
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
@@ -38,10 +40,10 @@ export const mockPlatformPeg = (
|
|||||||
platformMocks: Partial<Record<MethodLikeKeys<BasePlatform>, unknown>> = {},
|
platformMocks: Partial<Record<MethodLikeKeys<BasePlatform>, unknown>> = {},
|
||||||
): MockedObject<BasePlatform> => {
|
): MockedObject<BasePlatform> => {
|
||||||
const mockPlatform = new MockPlatform(platformMocks);
|
const mockPlatform = new MockPlatform(platformMocks);
|
||||||
jest.spyOn(PlatformPeg, "get").mockReturnValue(mockPlatform);
|
vi.spyOn(PlatformPeg, "get").mockReturnValue(mockPlatform);
|
||||||
return mocked(mockPlatform);
|
return vi.mocked(mockPlatform);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const unmockPlatformPeg = () => {
|
export const unmockPlatformPeg = () => {
|
||||||
jest.spyOn(PlatformPeg, "get").mockRestore();
|
vi.spyOn(PlatformPeg, "get").mockRestore();
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Com
|
|||||||
Please see LICENSE files in the repository root for full details.
|
Please see LICENSE files in the repository root for full details.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { type Mocked } from "jest-mock";
|
import { type Mocked } from "jest-mock-vitest-adapter";
|
||||||
import {
|
import {
|
||||||
type MatrixClient,
|
type MatrixClient,
|
||||||
MatrixEvent,
|
MatrixEvent,
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Com
|
|||||||
Please see LICENSE files in the repository root for full details.
|
Please see LICENSE files in the repository root for full details.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { type MockedObject } from "jest-mock";
|
import { type MockedObject } from "jest-mock-vitest-adapter";
|
||||||
import { type EventTimeline, EventType, type MatrixClient, type MatrixEvent, Room } from "matrix-js-sdk/src/matrix";
|
import { type EventTimeline, EventType, type MatrixClient, type MatrixEvent, Room } from "matrix-js-sdk/src/matrix";
|
||||||
import { KnownMembership } from "matrix-js-sdk/src/types";
|
import { KnownMembership } from "matrix-js-sdk/src/types";
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ Please see LICENSE files in the repository root for full details.
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import EventEmitter from "events";
|
import EventEmitter from "events";
|
||||||
import { mocked, type MockedObject } from "jest-mock";
|
import { type MockedObject } from "vitest";
|
||||||
import {
|
import {
|
||||||
MatrixEvent,
|
MatrixEvent,
|
||||||
type Room,
|
type Room,
|
||||||
@@ -48,6 +48,7 @@ import { type ValidatedServerConfig } from "../../src/utils/ValidatedServerConfi
|
|||||||
import { EnhancedMap } from "../../src/utils/maps";
|
import { EnhancedMap } from "../../src/utils/maps";
|
||||||
import { type AsyncStoreWithClient } from "../../src/stores/AsyncStoreWithClient";
|
import { type AsyncStoreWithClient } from "../../src/stores/AsyncStoreWithClient";
|
||||||
import MatrixClientBackedSettingsHandler from "../../src/settings/handlers/MatrixClientBackedSettingsHandler";
|
import MatrixClientBackedSettingsHandler from "../../src/settings/handlers/MatrixClientBackedSettingsHandler";
|
||||||
|
import { vi } from "../setup/adapter.ts";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Stub out the MatrixClient, and configure the MatrixClientPeg object to
|
* Stub out the MatrixClient, and configure the MatrixClientPeg object to
|
||||||
@@ -66,10 +67,10 @@ export function stubClient(): MatrixClient {
|
|||||||
//
|
//
|
||||||
// 'sandbox.restore()' doesn't work correctly on inherited methods,
|
// 'sandbox.restore()' doesn't work correctly on inherited methods,
|
||||||
// so we do this for each method
|
// so we do this for each method
|
||||||
jest.spyOn(peg, "get");
|
vi.spyOn(peg, "get");
|
||||||
jest.spyOn(peg, "safeGet");
|
vi.spyOn(peg, "safeGet");
|
||||||
jest.spyOn(peg, "unset");
|
vi.spyOn(peg, "unset");
|
||||||
jest.spyOn(peg, "replaceUsingCreds");
|
vi.spyOn(peg, "replaceUsingCreds");
|
||||||
// MatrixClientPeg.safeGet() is called a /lot/, so implement it with our own
|
// MatrixClientPeg.safeGet() is called a /lot/, so implement it with our own
|
||||||
// fast stub function rather than a sinon stub
|
// fast stub function rather than a sinon stub
|
||||||
peg.get = () => client;
|
peg.get = () => client;
|
||||||
@@ -90,64 +91,64 @@ export function createTestClient(): MatrixClient {
|
|||||||
let createdRoom: Room | undefined;
|
let createdRoom: Room | undefined;
|
||||||
|
|
||||||
const client = {
|
const client = {
|
||||||
getHomeserverUrl: jest.fn(),
|
getHomeserverUrl: vi.fn(),
|
||||||
getIdentityServerUrl: jest.fn(),
|
getIdentityServerUrl: vi.fn(),
|
||||||
getDomain: jest.fn().mockReturnValue("matrix.org"),
|
getDomain: vi.fn().mockReturnValue("matrix.org"),
|
||||||
getUserId: jest.fn().mockReturnValue("@userId:matrix.org"),
|
getUserId: vi.fn().mockReturnValue("@userId:matrix.org"),
|
||||||
getSafeUserId: jest.fn().mockReturnValue("@userId:matrix.org"),
|
getSafeUserId: vi.fn().mockReturnValue("@userId:matrix.org"),
|
||||||
getUserIdLocalpart: jest.fn().mockResolvedValue("userId"),
|
getUserIdLocalpart: vi.fn().mockResolvedValue("userId"),
|
||||||
getUser: jest.fn().mockReturnValue({ on: jest.fn(), off: jest.fn() }),
|
getUser: vi.fn().mockReturnValue({ on: vi.fn(), off: vi.fn() }),
|
||||||
getDevice: jest.fn(),
|
getDevice: vi.fn(),
|
||||||
getDeviceId: jest.fn().mockReturnValue("ABCDEFGHI"),
|
getDeviceId: vi.fn().mockReturnValue("ABCDEFGHI"),
|
||||||
deviceId: "ABCDEFGHI",
|
deviceId: "ABCDEFGHI",
|
||||||
getDevices: jest.fn().mockResolvedValue({ devices: [{ device_id: "ABCDEFGHI" }] }),
|
getDevices: vi.fn().mockResolvedValue({ devices: [{ device_id: "ABCDEFGHI" }] }),
|
||||||
getSessionId: jest.fn().mockReturnValue("iaszphgvfku"),
|
getSessionId: vi.fn().mockReturnValue("iaszphgvfku"),
|
||||||
credentials: { userId: "@userId:matrix.org" },
|
credentials: { userId: "@userId:matrix.org" },
|
||||||
getAccessToken: jest.fn(),
|
getAccessToken: vi.fn(),
|
||||||
|
|
||||||
secretStorage: {
|
secretStorage: {
|
||||||
get: jest.fn(),
|
get: vi.fn(),
|
||||||
isStored: jest.fn().mockReturnValue(false),
|
isStored: vi.fn().mockReturnValue(false),
|
||||||
checkKey: jest.fn().mockResolvedValue(false),
|
checkKey: vi.fn().mockResolvedValue(false),
|
||||||
hasKey: jest.fn().mockReturnValue(false),
|
hasKey: vi.fn().mockReturnValue(false),
|
||||||
getDefaultKeyId: jest.fn().mockResolvedValue(null),
|
getDefaultKeyId: vi.fn().mockResolvedValue(null),
|
||||||
},
|
},
|
||||||
|
|
||||||
store: {
|
store: {
|
||||||
getPendingEvents: jest.fn().mockResolvedValue([]),
|
getPendingEvents: vi.fn().mockResolvedValue([]),
|
||||||
setPendingEvents: jest.fn().mockResolvedValue(undefined),
|
setPendingEvents: vi.fn().mockResolvedValue(undefined),
|
||||||
storeRoom: jest.fn(),
|
storeRoom: vi.fn(),
|
||||||
removeRoom: jest.fn(),
|
removeRoom: vi.fn(),
|
||||||
},
|
},
|
||||||
|
|
||||||
getCrypto: jest.fn().mockReturnValue({
|
getCrypto: vi.fn().mockReturnValue({
|
||||||
getOwnDeviceKeys: jest.fn().mockResolvedValue({ ed25519: "ed25519", curve25519: "curve25519" }),
|
getOwnDeviceKeys: vi.fn().mockResolvedValue({ ed25519: "ed25519", curve25519: "curve25519" }),
|
||||||
getUserDeviceInfo: jest.fn().mockResolvedValue(new Map()),
|
getUserDeviceInfo: vi.fn().mockResolvedValue(new Map()),
|
||||||
getUserVerificationStatus: jest.fn(),
|
getUserVerificationStatus: vi.fn(),
|
||||||
getDeviceVerificationStatus: jest.fn(),
|
getDeviceVerificationStatus: vi.fn(),
|
||||||
resetKeyBackup: jest.fn(),
|
resetKeyBackup: vi.fn(),
|
||||||
isEncryptionEnabledInRoom: jest.fn().mockResolvedValue(false),
|
isEncryptionEnabledInRoom: vi.fn().mockResolvedValue(false),
|
||||||
isStateEncryptionEnabledInRoom: jest.fn().mockResolvedValue(false),
|
isStateEncryptionEnabledInRoom: vi.fn().mockResolvedValue(false),
|
||||||
getVerificationRequestsToDeviceInProgress: jest.fn().mockReturnValue([]),
|
getVerificationRequestsToDeviceInProgress: vi.fn().mockReturnValue([]),
|
||||||
setDeviceIsolationMode: jest.fn(),
|
setDeviceIsolationMode: vi.fn(),
|
||||||
prepareToEncrypt: jest.fn(),
|
prepareToEncrypt: vi.fn(),
|
||||||
bootstrapCrossSigning: jest.fn(),
|
bootstrapCrossSigning: vi.fn(),
|
||||||
getActiveSessionBackupVersion: jest.fn().mockResolvedValue(null),
|
getActiveSessionBackupVersion: vi.fn().mockResolvedValue(null),
|
||||||
isKeyBackupTrusted: jest.fn().mockResolvedValue({}),
|
isKeyBackupTrusted: vi.fn().mockResolvedValue({}),
|
||||||
createRecoveryKeyFromPassphrase: jest.fn().mockResolvedValue({
|
createRecoveryKeyFromPassphrase: vi.fn().mockResolvedValue({
|
||||||
privateKey: new Uint8Array(32),
|
privateKey: new Uint8Array(32),
|
||||||
encodedPrivateKey: "encoded private key",
|
encodedPrivateKey: "encoded private key",
|
||||||
}),
|
}),
|
||||||
bootstrapSecretStorage: jest.fn(),
|
bootstrapSecretStorage: vi.fn(),
|
||||||
isDehydrationSupported: jest.fn().mockResolvedValue(false),
|
isDehydrationSupported: vi.fn().mockResolvedValue(false),
|
||||||
restoreKeyBackup: jest.fn(),
|
restoreKeyBackup: vi.fn(),
|
||||||
restoreKeyBackupWithPassphrase: jest.fn(),
|
restoreKeyBackupWithPassphrase: vi.fn(),
|
||||||
loadSessionBackupPrivateKeyFromSecretStorage: jest.fn(),
|
loadSessionBackupPrivateKeyFromSecretStorage: vi.fn(),
|
||||||
storeSessionBackupPrivateKey: jest.fn(),
|
storeSessionBackupPrivateKey: vi.fn(),
|
||||||
checkKeyBackupAndEnable: jest.fn().mockResolvedValue(null),
|
checkKeyBackupAndEnable: vi.fn().mockResolvedValue(null),
|
||||||
getKeyBackupInfo: jest.fn().mockResolvedValue(null),
|
getKeyBackupInfo: vi.fn().mockResolvedValue(null),
|
||||||
getEncryptionInfoForEvent: jest.fn().mockResolvedValue(null),
|
getEncryptionInfoForEvent: vi.fn().mockResolvedValue(null),
|
||||||
getCrossSigningStatus: jest.fn().mockResolvedValue({
|
getCrossSigningStatus: vi.fn().mockResolvedValue({
|
||||||
publicKeysOnDevice: false,
|
publicKeysOnDevice: false,
|
||||||
privateKeysInSecretStorage: false,
|
privateKeysInSecretStorage: false,
|
||||||
privateKeysCachedLocally: {
|
privateKeysCachedLocally: {
|
||||||
@@ -156,17 +157,17 @@ export function createTestClient(): MatrixClient {
|
|||||||
userSigningKey: false,
|
userSigningKey: false,
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
isCrossSigningReady: jest.fn().mockResolvedValue(false),
|
isCrossSigningReady: vi.fn().mockResolvedValue(false),
|
||||||
disableKeyStorage: jest.fn(),
|
disableKeyStorage: vi.fn(),
|
||||||
resetEncryption: jest.fn(),
|
resetEncryption: vi.fn(),
|
||||||
getSessionBackupPrivateKey: jest.fn().mockResolvedValue(null),
|
getSessionBackupPrivateKey: vi.fn().mockResolvedValue(null),
|
||||||
isSecretStorageReady: jest.fn().mockResolvedValue(false),
|
isSecretStorageReady: vi.fn().mockResolvedValue(false),
|
||||||
deleteKeyBackupVersion: jest.fn(),
|
deleteKeyBackupVersion: vi.fn(),
|
||||||
crossSignDevice: jest.fn(),
|
crossSignDevice: vi.fn(),
|
||||||
}),
|
}),
|
||||||
|
|
||||||
getPushActionsForEvent: jest.fn(),
|
getPushActionsForEvent: vi.fn(),
|
||||||
getRoom: jest.fn().mockImplementation((roomId) => {
|
getRoom: vi.fn().mockImplementation((roomId) => {
|
||||||
// If the test called `createRoom`, return the mocked room it created.
|
// If the test called `createRoom`, return the mocked room it created.
|
||||||
if (createdRoom) {
|
if (createdRoom) {
|
||||||
return createdRoom;
|
return createdRoom;
|
||||||
@@ -174,32 +175,32 @@ export function createTestClient(): MatrixClient {
|
|||||||
return mkStubRoom(roomId, "My room", client);
|
return mkStubRoom(roomId, "My room", client);
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
getRooms: jest.fn().mockReturnValue([]),
|
getRooms: vi.fn().mockReturnValue([]),
|
||||||
getVisibleRooms: jest.fn().mockReturnValue([]),
|
getVisibleRooms: vi.fn().mockReturnValue([]),
|
||||||
loginFlows: jest.fn(),
|
loginFlows: vi.fn(),
|
||||||
on: eventEmitter.on.bind(eventEmitter),
|
on: eventEmitter.on.bind(eventEmitter),
|
||||||
once: eventEmitter.once.bind(eventEmitter),
|
once: eventEmitter.once.bind(eventEmitter),
|
||||||
off: eventEmitter.off.bind(eventEmitter),
|
off: eventEmitter.off.bind(eventEmitter),
|
||||||
removeListener: eventEmitter.removeListener.bind(eventEmitter),
|
removeListener: eventEmitter.removeListener.bind(eventEmitter),
|
||||||
emit: eventEmitter.emit.bind(eventEmitter),
|
emit: eventEmitter.emit.bind(eventEmitter),
|
||||||
isRoomEncrypted: jest.fn().mockReturnValue(false),
|
isRoomEncrypted: vi.fn().mockReturnValue(false),
|
||||||
peekInRoom: jest.fn().mockResolvedValue(mkStubRoom(undefined, undefined, undefined)),
|
peekInRoom: vi.fn().mockResolvedValue(mkStubRoom(undefined, undefined, undefined)),
|
||||||
stopPeeking: jest.fn(),
|
stopPeeking: vi.fn(),
|
||||||
|
|
||||||
getEventTimeline: jest.fn().mockResolvedValue([]),
|
getEventTimeline: vi.fn().mockResolvedValue([]),
|
||||||
paginateEventTimeline: jest.fn().mockResolvedValue(undefined),
|
paginateEventTimeline: vi.fn().mockResolvedValue(undefined),
|
||||||
sendReadReceipt: jest.fn().mockResolvedValue(undefined),
|
sendReadReceipt: vi.fn().mockResolvedValue(undefined),
|
||||||
getRoomIdForAlias: jest.fn().mockResolvedValue(undefined),
|
getRoomIdForAlias: vi.fn().mockResolvedValue(undefined),
|
||||||
getRoomDirectoryVisibility: jest.fn().mockResolvedValue(undefined),
|
getRoomDirectoryVisibility: vi.fn().mockResolvedValue(undefined),
|
||||||
getProfileInfo: jest.fn().mockResolvedValue({}),
|
getProfileInfo: vi.fn().mockResolvedValue({}),
|
||||||
getThirdpartyProtocols: jest.fn().mockResolvedValue({}),
|
getThirdpartyProtocols: vi.fn().mockResolvedValue({}),
|
||||||
getClientWellKnown: jest.fn().mockReturnValue(null),
|
getClientWellKnown: vi.fn().mockReturnValue(null),
|
||||||
waitForClientWellKnown: jest.fn().mockResolvedValue({}),
|
waitForClientWellKnown: vi.fn().mockResolvedValue({}),
|
||||||
supportsVoip: jest.fn().mockReturnValue(true),
|
supportsVoip: vi.fn().mockReturnValue(true),
|
||||||
getTurnServers: jest.fn().mockReturnValue([]),
|
getTurnServers: vi.fn().mockReturnValue([]),
|
||||||
getTurnServersExpiry: jest.fn().mockReturnValue(2 ^ 32),
|
getTurnServersExpiry: vi.fn().mockReturnValue(2 ^ 32),
|
||||||
getThirdpartyUser: jest.fn().mockResolvedValue([]),
|
getThirdpartyUser: vi.fn().mockResolvedValue([]),
|
||||||
getAccountData: jest.fn().mockImplementation((type) => {
|
getAccountData: vi.fn().mockImplementation((type) => {
|
||||||
return mkEvent({
|
return mkEvent({
|
||||||
user: "@user:example.com",
|
user: "@user:example.com",
|
||||||
room: undefined,
|
room: undefined,
|
||||||
@@ -208,26 +209,26 @@ export function createTestClient(): MatrixClient {
|
|||||||
content: {},
|
content: {},
|
||||||
});
|
});
|
||||||
}),
|
}),
|
||||||
getAccountDataFromServer: jest.fn(),
|
getAccountDataFromServer: vi.fn(),
|
||||||
|
|
||||||
mxcUrlToHttp: jest.fn().mockImplementation((mxc: string) => `http://this.is.a.url/${mxc.substring(6)}`),
|
mxcUrlToHttp: vi.fn().mockImplementation((mxc: string) => `http://this.is.a.url/${mxc.substring(6)}`),
|
||||||
setAccountData: jest.fn(),
|
setAccountData: vi.fn(),
|
||||||
deleteAccountData: jest.fn(),
|
deleteAccountData: vi.fn(),
|
||||||
setRoomAccountData: jest.fn(),
|
setRoomAccountData: vi.fn(),
|
||||||
setRoomName: jest.fn(),
|
setRoomName: vi.fn(),
|
||||||
setRoomTopic: jest.fn(),
|
setRoomTopic: vi.fn(),
|
||||||
setRoomReadMarkers: jest.fn().mockResolvedValue({}),
|
setRoomReadMarkers: vi.fn().mockResolvedValue({}),
|
||||||
sendTyping: jest.fn().mockResolvedValue({}),
|
sendTyping: vi.fn().mockResolvedValue({}),
|
||||||
sendMessage: jest.fn().mockResolvedValue({}),
|
sendMessage: vi.fn().mockResolvedValue({}),
|
||||||
sendStateEvent: jest.fn().mockResolvedValue(undefined),
|
sendStateEvent: vi.fn().mockResolvedValue(undefined),
|
||||||
sendRtcDecline: jest.fn().mockResolvedValue(undefined),
|
sendRtcDecline: vi.fn().mockResolvedValue(undefined),
|
||||||
getSyncState: jest.fn().mockReturnValue("SYNCING"),
|
getSyncState: vi.fn().mockReturnValue("SYNCING"),
|
||||||
generateClientSecret: () => "t35tcl1Ent5ECr3T",
|
generateClientSecret: () => "t35tcl1Ent5ECr3T",
|
||||||
isGuest: jest.fn().mockReturnValue(false),
|
isGuest: vi.fn().mockReturnValue(false),
|
||||||
getRoomHierarchy: jest.fn().mockReturnValue({
|
getRoomHierarchy: vi.fn().mockReturnValue({
|
||||||
rooms: [],
|
rooms: [],
|
||||||
}),
|
}),
|
||||||
createRoom: jest.fn(async (createOpts?: ICreateRoomOpts) => {
|
createRoom: vi.fn(async (createOpts?: ICreateRoomOpts) => {
|
||||||
const initialState = createOpts?.initial_state?.map((event, i) =>
|
const initialState = createOpts?.initial_state?.map((event, i) =>
|
||||||
mkEvent({
|
mkEvent({
|
||||||
...event,
|
...event,
|
||||||
@@ -244,60 +245,60 @@ export function createTestClient(): MatrixClient {
|
|||||||
);
|
);
|
||||||
return { room_id: "!1:example.org" };
|
return { room_id: "!1:example.org" };
|
||||||
}),
|
}),
|
||||||
setPowerLevel: jest.fn().mockResolvedValue(undefined),
|
setPowerLevel: vi.fn().mockResolvedValue(undefined),
|
||||||
pushRules: {},
|
pushRules: {},
|
||||||
decryptEventIfNeeded: () => Promise.resolve(),
|
decryptEventIfNeeded: () => Promise.resolve(),
|
||||||
isUserIgnored: jest.fn().mockReturnValue(false),
|
isUserIgnored: vi.fn().mockReturnValue(false),
|
||||||
getCapabilities: jest.fn().mockResolvedValue({}),
|
getCapabilities: vi.fn().mockResolvedValue({}),
|
||||||
getCachedCapabilities: jest.fn().mockReturnValue({}),
|
getCachedCapabilities: vi.fn().mockReturnValue({}),
|
||||||
supportsThreads: jest.fn().mockReturnValue(false),
|
supportsThreads: vi.fn().mockReturnValue(false),
|
||||||
supportsIntentionalMentions: jest.fn().mockReturnValue(false),
|
supportsIntentionalMentions: vi.fn().mockReturnValue(false),
|
||||||
getRoomUpgradeHistory: jest.fn().mockReturnValue([]),
|
getRoomUpgradeHistory: vi.fn().mockReturnValue([]),
|
||||||
getOpenIdToken: jest.fn().mockResolvedValue(undefined),
|
getOpenIdToken: vi.fn().mockResolvedValue(undefined),
|
||||||
registerWithIdentityServer: jest.fn().mockResolvedValue({}),
|
registerWithIdentityServer: vi.fn().mockResolvedValue({}),
|
||||||
getIdentityAccount: jest.fn().mockResolvedValue({}),
|
getIdentityAccount: vi.fn().mockResolvedValue({}),
|
||||||
getTerms: jest.fn().mockResolvedValue({ policies: [] }),
|
getTerms: vi.fn().mockResolvedValue({ policies: [] }),
|
||||||
agreeToTerms: jest.fn(),
|
agreeToTerms: vi.fn(),
|
||||||
doesServerSupportUnstableFeature: jest.fn().mockResolvedValue(undefined),
|
doesServerSupportUnstableFeature: vi.fn().mockResolvedValue(undefined),
|
||||||
isVersionSupported: jest.fn().mockResolvedValue(undefined),
|
isVersionSupported: vi.fn().mockResolvedValue(undefined),
|
||||||
getPushRules: jest.fn().mockResolvedValue(undefined),
|
getPushRules: vi.fn().mockResolvedValue(undefined),
|
||||||
getPushers: jest.fn().mockResolvedValue({ pushers: [] }),
|
getPushers: vi.fn().mockResolvedValue({ pushers: [] }),
|
||||||
getThreePids: jest.fn().mockResolvedValue({ threepids: [] }),
|
getThreePids: vi.fn().mockResolvedValue({ threepids: [] }),
|
||||||
bulkLookupThreePids: jest.fn().mockResolvedValue({ threepids: [] }),
|
bulkLookupThreePids: vi.fn().mockResolvedValue({ threepids: [] }),
|
||||||
setAvatarUrl: jest.fn().mockResolvedValue(undefined),
|
setAvatarUrl: vi.fn().mockResolvedValue(undefined),
|
||||||
setDisplayName: jest.fn().mockResolvedValue(undefined),
|
setDisplayName: vi.fn().mockResolvedValue(undefined),
|
||||||
setPusher: jest.fn().mockResolvedValue(undefined),
|
setPusher: vi.fn().mockResolvedValue(undefined),
|
||||||
setPushRuleEnabled: jest.fn().mockResolvedValue(undefined),
|
setPushRuleEnabled: vi.fn().mockResolvedValue(undefined),
|
||||||
setPushRuleActions: jest.fn().mockResolvedValue(undefined),
|
setPushRuleActions: vi.fn().mockResolvedValue(undefined),
|
||||||
relations: jest.fn().mockResolvedValue({
|
relations: vi.fn().mockResolvedValue({
|
||||||
events: [],
|
events: [],
|
||||||
}),
|
}),
|
||||||
hasLazyLoadMembersEnabled: jest.fn().mockReturnValue(false),
|
hasLazyLoadMembersEnabled: vi.fn().mockReturnValue(false),
|
||||||
isInitialSyncComplete: jest.fn().mockReturnValue(true),
|
isInitialSyncComplete: vi.fn().mockReturnValue(true),
|
||||||
fetchRoomEvent: jest.fn().mockRejectedValue({}),
|
fetchRoomEvent: vi.fn().mockRejectedValue({}),
|
||||||
makeTxnId: jest.fn().mockImplementation(() => `t${txnId++}`),
|
makeTxnId: vi.fn().mockImplementation(() => `t${txnId++}`),
|
||||||
sendToDevice: jest.fn().mockResolvedValue(undefined),
|
sendToDevice: vi.fn().mockResolvedValue(undefined),
|
||||||
queueToDevice: jest.fn().mockResolvedValue(undefined),
|
queueToDevice: vi.fn().mockResolvedValue(undefined),
|
||||||
cancelPendingEvent: jest.fn(),
|
cancelPendingEvent: vi.fn(),
|
||||||
|
|
||||||
getMediaHandler: jest.fn().mockReturnValue({
|
getMediaHandler: vi.fn().mockReturnValue({
|
||||||
setVideoInput: jest.fn(),
|
setVideoInput: vi.fn(),
|
||||||
setAudioInput: jest.fn(),
|
setAudioInput: vi.fn(),
|
||||||
setAudioSettings: jest.fn(),
|
setAudioSettings: vi.fn(),
|
||||||
stopAllStreams: jest.fn(),
|
stopAllStreams: vi.fn(),
|
||||||
} as unknown as MediaHandler),
|
} as unknown as MediaHandler),
|
||||||
uploadContent: jest.fn(),
|
uploadContent: vi.fn(),
|
||||||
getEventMapper: (_options?: MapperOpts) => (event: Partial<IEvent>) => new MatrixEvent(event),
|
getEventMapper: (_options?: MapperOpts) => (event: Partial<IEvent>) => new MatrixEvent(event),
|
||||||
leaveRoomChain: jest.fn((roomId) => ({ [roomId]: null })),
|
leaveRoomChain: vi.fn((roomId) => ({ [roomId]: null })),
|
||||||
requestPasswordEmailToken: jest.fn().mockRejectedValue({}),
|
requestPasswordEmailToken: vi.fn().mockRejectedValue({}),
|
||||||
setPassword: jest.fn().mockRejectedValue({}),
|
setPassword: vi.fn().mockRejectedValue({}),
|
||||||
groupCallEventHandler: { groupCalls: new Map<string, GroupCall>() },
|
groupCallEventHandler: { groupCalls: new Map<string, GroupCall>() },
|
||||||
redactEvent: jest.fn(),
|
redactEvent: vi.fn(),
|
||||||
|
|
||||||
createMessagesRequest: jest.fn().mockResolvedValue({
|
createMessagesRequest: vi.fn().mockResolvedValue({
|
||||||
chunk: [],
|
chunk: [],
|
||||||
}),
|
}),
|
||||||
sendEvent: jest.fn().mockImplementation((roomId, type, content) => {
|
sendEvent: vi.fn().mockImplementation((roomId, type, content) => {
|
||||||
return new MatrixEvent({
|
return new MatrixEvent({
|
||||||
type,
|
type,
|
||||||
sender: "@me:localhost",
|
sender: "@me:localhost",
|
||||||
@@ -306,61 +307,61 @@ export function createTestClient(): MatrixClient {
|
|||||||
room_id: roomId,
|
room_id: roomId,
|
||||||
});
|
});
|
||||||
}),
|
}),
|
||||||
resendEvent: jest.fn().mockResolvedValue({}),
|
resendEvent: vi.fn().mockResolvedValue({}),
|
||||||
|
|
||||||
_unstable_sendDelayedEvent: jest.fn(),
|
_unstable_sendDelayedEvent: vi.fn(),
|
||||||
_unstable_sendDelayedStateEvent: jest.fn(),
|
_unstable_sendDelayedStateEvent: vi.fn(),
|
||||||
_unstable_cancelScheduledDelayedEvent: jest.fn(),
|
_unstable_cancelScheduledDelayedEvent: vi.fn(),
|
||||||
_unstable_restartScheduledDelayedEvent: jest.fn(),
|
_unstable_restartScheduledDelayedEvent: vi.fn(),
|
||||||
_unstable_sendScheduledDelayedEvent: jest.fn(),
|
_unstable_sendScheduledDelayedEvent: vi.fn(),
|
||||||
_unstable_sendStickyEvent: jest.fn(),
|
_unstable_sendStickyEvent: vi.fn(),
|
||||||
_unstable_sendStickyDelayedEvent: jest.fn(),
|
_unstable_sendStickyDelayedEvent: vi.fn(),
|
||||||
_unstable_getRTCTransports: jest.fn(),
|
_unstable_getRTCTransports: vi.fn(),
|
||||||
searchUserDirectory: jest.fn().mockResolvedValue({ limited: false, results: [] }),
|
searchUserDirectory: vi.fn().mockResolvedValue({ limited: false, results: [] }),
|
||||||
setDeviceVerified: jest.fn(),
|
setDeviceVerified: vi.fn(),
|
||||||
joinRoom: jest.fn(),
|
joinRoom: vi.fn(),
|
||||||
getSyncStateData: jest.fn(),
|
getSyncStateData: vi.fn(),
|
||||||
getDehydratedDevice: jest.fn(),
|
getDehydratedDevice: vi.fn(),
|
||||||
exportRoomKeys: jest.fn(),
|
exportRoomKeys: vi.fn(),
|
||||||
knockRoom: jest.fn(),
|
knockRoom: vi.fn(),
|
||||||
leave: jest.fn(),
|
leave: vi.fn(),
|
||||||
getVersions: jest.fn().mockResolvedValue({ versions: ["v1.1"] }),
|
getVersions: vi.fn().mockResolvedValue({ versions: ["v1.1"] }),
|
||||||
requestAdd3pidEmailToken: jest.fn(),
|
requestAdd3pidEmailToken: vi.fn(),
|
||||||
requestAdd3pidMsisdnToken: jest.fn(),
|
requestAdd3pidMsisdnToken: vi.fn(),
|
||||||
submitMsisdnTokenOtherUrl: jest.fn(),
|
submitMsisdnTokenOtherUrl: vi.fn(),
|
||||||
deleteThreePid: jest.fn().mockResolvedValue({}),
|
deleteThreePid: vi.fn().mockResolvedValue({}),
|
||||||
bindThreePid: jest.fn().mockResolvedValue({}),
|
bindThreePid: vi.fn().mockResolvedValue({}),
|
||||||
unbindThreePid: jest.fn().mockResolvedValue({}),
|
unbindThreePid: vi.fn().mockResolvedValue({}),
|
||||||
requestEmailToken: jest.fn(),
|
requestEmailToken: vi.fn(),
|
||||||
addThreePidOnly: jest.fn(),
|
addThreePidOnly: vi.fn(),
|
||||||
requestMsisdnToken: jest.fn(),
|
requestMsisdnToken: vi.fn(),
|
||||||
submitMsisdnToken: jest.fn(),
|
submitMsisdnToken: vi.fn(),
|
||||||
getMediaConfig: jest.fn(),
|
getMediaConfig: vi.fn(),
|
||||||
baseUrl: "https://matrix-client.matrix.org",
|
baseUrl: "https://matrix-client.matrix.org",
|
||||||
matrixRTC: createStubMatrixRTC(),
|
matrixRTC: createStubMatrixRTC(),
|
||||||
isFallbackICEServerAllowed: jest.fn().mockReturnValue(false),
|
isFallbackICEServerAllowed: vi.fn().mockReturnValue(false),
|
||||||
getAuthIssuer: jest.fn(),
|
getAuthIssuer: vi.fn(),
|
||||||
getOrCreateFilter: jest.fn(),
|
getOrCreateFilter: vi.fn(),
|
||||||
sendStickerMessage: jest.fn(),
|
sendStickerMessage: vi.fn(),
|
||||||
getLocalAliases: jest.fn().mockReturnValue([]),
|
getLocalAliases: vi.fn().mockReturnValue([]),
|
||||||
uploadDeviceSigningKeys: jest.fn(),
|
uploadDeviceSigningKeys: vi.fn(),
|
||||||
isKeyBackupKeyStored: jest.fn().mockResolvedValue(null),
|
isKeyBackupKeyStored: vi.fn().mockResolvedValue(null),
|
||||||
getIgnoredUsers: jest.fn().mockReturnValue([]),
|
getIgnoredUsers: vi.fn().mockReturnValue([]),
|
||||||
setIgnoredUsers: jest.fn(),
|
setIgnoredUsers: vi.fn(),
|
||||||
reportRoom: jest.fn(),
|
reportRoom: vi.fn(),
|
||||||
pushProcessor: {
|
pushProcessor: {
|
||||||
getPushRuleById: jest.fn(),
|
getPushRuleById: vi.fn(),
|
||||||
},
|
},
|
||||||
search: jest.fn().mockResolvedValue({}),
|
search: vi.fn().mockResolvedValue({}),
|
||||||
processRoomEventsSearch: jest.fn().mockResolvedValue({ highlights: [], results: [] }),
|
processRoomEventsSearch: vi.fn().mockResolvedValue({ highlights: [], results: [] }),
|
||||||
invite: jest.fn(),
|
invite: vi.fn(),
|
||||||
kick: jest.fn(),
|
kick: vi.fn(),
|
||||||
ban: jest.fn(),
|
ban: vi.fn(),
|
||||||
sendTextMessage: jest.fn(),
|
sendTextMessage: vi.fn(),
|
||||||
deleteRoomTag: jest.fn().mockResolvedValue({}),
|
deleteRoomTag: vi.fn().mockResolvedValue({}),
|
||||||
setRoomTag: jest.fn().mockResolvedValue({}),
|
setRoomTag: vi.fn().mockResolvedValue({}),
|
||||||
getExtendedProfileProperty: jest.fn(),
|
getExtendedProfileProperty: vi.fn(),
|
||||||
setExtendedProfileProperty: jest.fn().mockResolvedValue(undefined),
|
setExtendedProfileProperty: vi.fn().mockResolvedValue(undefined),
|
||||||
} as unknown as MatrixClient;
|
} as unknown as MatrixClient;
|
||||||
|
|
||||||
client.reEmitter = new ReEmitter(client);
|
client.reEmitter = new ReEmitter(client);
|
||||||
@@ -379,7 +380,7 @@ export function createTestClient(): MatrixClient {
|
|||||||
|
|
||||||
export function createStubMatrixRTC(): MatrixRTCSessionManager {
|
export function createStubMatrixRTC(): MatrixRTCSessionManager {
|
||||||
const eventEmitterMatrixRTCSessionManager = new EventEmitter();
|
const eventEmitterMatrixRTCSessionManager = new EventEmitter();
|
||||||
const mockGetRoomSession = jest.fn();
|
const mockGetRoomSession = vi.fn();
|
||||||
mockGetRoomSession.mockImplementation((roomId) => {
|
mockGetRoomSession.mockImplementation((roomId) => {
|
||||||
const session = new EventEmitter() as MatrixRTCSession;
|
const session = new EventEmitter() as MatrixRTCSession;
|
||||||
session.memberships = [];
|
session.memberships = [];
|
||||||
@@ -388,9 +389,9 @@ export function createStubMatrixRTC(): MatrixRTCSessionManager {
|
|||||||
return session;
|
return session;
|
||||||
});
|
});
|
||||||
return {
|
return {
|
||||||
start: jest.fn(),
|
start: vi.fn(),
|
||||||
stop: jest.fn(),
|
stop: vi.fn(),
|
||||||
getActiveRoomSession: jest.fn(),
|
getActiveRoomSession: vi.fn(),
|
||||||
getRoomSession: mockGetRoomSession,
|
getRoomSession: mockGetRoomSession,
|
||||||
on: eventEmitterMatrixRTCSessionManager.on.bind(eventEmitterMatrixRTCSessionManager),
|
on: eventEmitterMatrixRTCSessionManager.on.bind(eventEmitterMatrixRTCSessionManager),
|
||||||
off: eventEmitterMatrixRTCSessionManager.off.bind(eventEmitterMatrixRTCSessionManager),
|
off: eventEmitterMatrixRTCSessionManager.off.bind(eventEmitterMatrixRTCSessionManager),
|
||||||
@@ -673,42 +674,42 @@ export function mkStubRoom(
|
|||||||
const eventEmitter = new EventEmitter();
|
const eventEmitter = new EventEmitter();
|
||||||
|
|
||||||
return {
|
return {
|
||||||
canInvite: jest.fn().mockReturnValue(false),
|
canInvite: vi.fn().mockReturnValue(false),
|
||||||
client,
|
client,
|
||||||
findThreadForEvent: jest.fn(),
|
findThreadForEvent: vi.fn(),
|
||||||
createThreadsTimelineSets: jest.fn().mockReturnValue(new Promise(() => {})),
|
createThreadsTimelineSets: vi.fn().mockReturnValue(new Promise(() => {})),
|
||||||
currentState: {
|
currentState: {
|
||||||
getStateEvents: jest.fn((_type, key) => (key === undefined ? [] : null)),
|
getStateEvents: vi.fn((_type, key) => (key === undefined ? [] : null)),
|
||||||
getMember: jest.fn(),
|
getMember: vi.fn(),
|
||||||
mayClientSendStateEvent: jest.fn().mockReturnValue(true),
|
mayClientSendStateEvent: vi.fn().mockReturnValue(true),
|
||||||
maySendStateEvent: jest.fn().mockReturnValue(true),
|
maySendStateEvent: vi.fn().mockReturnValue(true),
|
||||||
maySendRedactionForEvent: jest.fn().mockReturnValue(true),
|
maySendRedactionForEvent: vi.fn().mockReturnValue(true),
|
||||||
maySendEvent: jest.fn().mockReturnValue(true),
|
maySendEvent: vi.fn().mockReturnValue(true),
|
||||||
maySendMessage: jest.fn().mockReturnValue(true),
|
maySendMessage: vi.fn().mockReturnValue(true),
|
||||||
members: {},
|
members: {},
|
||||||
getHistoryVisibility: jest.fn().mockReturnValue(HistoryVisibility.Shared),
|
getHistoryVisibility: vi.fn().mockReturnValue(HistoryVisibility.Shared),
|
||||||
getJoinRule: jest.fn().mockReturnValue(JoinRule.Invite),
|
getJoinRule: vi.fn().mockReturnValue(JoinRule.Invite),
|
||||||
on: jest.fn(),
|
on: vi.fn(),
|
||||||
off: jest.fn(),
|
off: vi.fn(),
|
||||||
removeListener: jest.fn(),
|
removeListener: vi.fn(),
|
||||||
} as unknown as RoomState,
|
} as unknown as RoomState,
|
||||||
eventShouldLiveIn: jest.fn().mockReturnValue({ shouldLiveInRoom: true, shouldLiveInThread: false }),
|
eventShouldLiveIn: vi.fn().mockReturnValue({ shouldLiveInRoom: true, shouldLiveInThread: false }),
|
||||||
fetchRoomThreads: jest.fn().mockReturnValue(Promise.resolve()),
|
fetchRoomThreads: vi.fn().mockReturnValue(Promise.resolve()),
|
||||||
findEventById: jest.fn().mockReturnValue(undefined),
|
findEventById: vi.fn().mockReturnValue(undefined),
|
||||||
findPredecessor: jest.fn().mockReturnValue({ roomId: "", eventId: null }),
|
findPredecessor: vi.fn().mockReturnValue({ roomId: "", eventId: null }),
|
||||||
getAltAliases: jest.fn().mockReturnValue([]),
|
getAltAliases: vi.fn().mockReturnValue([]),
|
||||||
getAvatarUrl: () => "mxc://avatar.url/room.png",
|
getAvatarUrl: () => "mxc://avatar.url/room.png",
|
||||||
getCanonicalAlias: jest.fn(),
|
getCanonicalAlias: vi.fn(),
|
||||||
getDMInviter: jest.fn(),
|
getDMInviter: vi.fn(),
|
||||||
getEventReadUpTo: jest.fn(() => null),
|
getEventReadUpTo: vi.fn(() => null),
|
||||||
getInvitedAndJoinedMemberCount: jest.fn().mockReturnValue(1),
|
getInvitedAndJoinedMemberCount: vi.fn().mockReturnValue(1),
|
||||||
getJoinRule: jest.fn().mockReturnValue("invite"),
|
getJoinRule: vi.fn().mockReturnValue("invite"),
|
||||||
getJoinedMemberCount: jest.fn().mockReturnValue(1),
|
getJoinedMemberCount: vi.fn().mockReturnValue(1),
|
||||||
getJoinedMembers: jest.fn().mockReturnValue([]),
|
getJoinedMembers: vi.fn().mockReturnValue([]),
|
||||||
getLiveTimeline: jest.fn().mockReturnValue(stubTimeline),
|
getLiveTimeline: vi.fn().mockReturnValue(stubTimeline),
|
||||||
getLastLiveEvent: jest.fn().mockReturnValue(undefined),
|
getLastLiveEvent: vi.fn().mockReturnValue(undefined),
|
||||||
getLastActiveTimestamp: jest.fn().mockReturnValue(1183140000),
|
getLastActiveTimestamp: vi.fn().mockReturnValue(1183140000),
|
||||||
getMember: jest.fn().mockReturnValue({
|
getMember: vi.fn().mockReturnValue({
|
||||||
userId: "@member:domain.bla",
|
userId: "@member:domain.bla",
|
||||||
name: "Member",
|
name: "Member",
|
||||||
rawDisplayName: "Member",
|
rawDisplayName: "Member",
|
||||||
@@ -718,29 +719,29 @@ export function mkStubRoom(
|
|||||||
events: {},
|
events: {},
|
||||||
isKicked: () => false,
|
isKicked: () => false,
|
||||||
}),
|
}),
|
||||||
getMembers: jest.fn().mockReturnValue([]),
|
getMembers: vi.fn().mockReturnValue([]),
|
||||||
getEncryptionTargetMembers: jest.fn().mockReturnValue([]),
|
getEncryptionTargetMembers: vi.fn().mockReturnValue([]),
|
||||||
getMembersWithMembership: jest.fn().mockReturnValue([]),
|
getMembersWithMembership: vi.fn().mockReturnValue([]),
|
||||||
getMxcAvatarUrl: () => "mxc://avatar.url/room.png",
|
getMxcAvatarUrl: () => "mxc://avatar.url/room.png",
|
||||||
getMyMembership: jest.fn().mockReturnValue(KnownMembership.Join),
|
getMyMembership: vi.fn().mockReturnValue(KnownMembership.Join),
|
||||||
getPendingEvents: jest.fn().mockReturnValue([]),
|
getPendingEvents: vi.fn().mockReturnValue([]),
|
||||||
getReceiptsForEvent: jest.fn().mockReturnValue([]),
|
getReceiptsForEvent: vi.fn().mockReturnValue([]),
|
||||||
getRecommendedVersion: jest.fn().mockReturnValue(Promise.resolve("")),
|
getRecommendedVersion: vi.fn().mockReturnValue(Promise.resolve("")),
|
||||||
getThreads: jest.fn().mockReturnValue([]),
|
getThreads: vi.fn().mockReturnValue([]),
|
||||||
getType: jest.fn().mockReturnValue(undefined),
|
getType: vi.fn().mockReturnValue(undefined),
|
||||||
getUnfilteredTimelineSet: jest.fn(),
|
getUnfilteredTimelineSet: vi.fn(),
|
||||||
getUnreadNotificationCount: jest.fn(() => 0),
|
getUnreadNotificationCount: vi.fn(() => 0),
|
||||||
getRoomUnreadNotificationCount: jest.fn().mockReturnValue(0),
|
getRoomUnreadNotificationCount: vi.fn().mockReturnValue(0),
|
||||||
getVersion: jest.fn().mockReturnValue("1"),
|
getVersion: vi.fn().mockReturnValue("1"),
|
||||||
getBumpStamp: jest.fn().mockReturnValue(0),
|
getBumpStamp: vi.fn().mockReturnValue(0),
|
||||||
getAccountData: jest.fn(),
|
getAccountData: vi.fn(),
|
||||||
hasMembershipState: () => false,
|
hasMembershipState: () => false,
|
||||||
isElementVideoRoom: jest.fn().mockReturnValue(false),
|
isElementVideoRoom: vi.fn().mockReturnValue(false),
|
||||||
isSpaceRoom: jest.fn().mockReturnValue(false),
|
isSpaceRoom: vi.fn().mockReturnValue(false),
|
||||||
isCallRoom: jest.fn().mockReturnValue(false),
|
isCallRoom: vi.fn().mockReturnValue(false),
|
||||||
hasEncryptionStateEvent: jest.fn().mockReturnValue(false),
|
hasEncryptionStateEvent: vi.fn().mockReturnValue(false),
|
||||||
loadMembersIfNeeded: jest.fn(),
|
loadMembersIfNeeded: vi.fn(),
|
||||||
maySendMessage: jest.fn().mockReturnValue(true),
|
maySendMessage: vi.fn().mockReturnValue(true),
|
||||||
myUserId: client?.getUserId(),
|
myUserId: client?.getUserId(),
|
||||||
name,
|
name,
|
||||||
normalizedName: normalize(name || ""),
|
normalizedName: normalize(name || ""),
|
||||||
@@ -750,8 +751,8 @@ export function mkStubRoom(
|
|||||||
removeListener: eventEmitter.removeListener.bind(eventEmitter),
|
removeListener: eventEmitter.removeListener.bind(eventEmitter),
|
||||||
emit: eventEmitter.emit.bind(eventEmitter),
|
emit: eventEmitter.emit.bind(eventEmitter),
|
||||||
roomId,
|
roomId,
|
||||||
setBlacklistUnverifiedDevices: jest.fn(),
|
setBlacklistUnverifiedDevices: vi.fn(),
|
||||||
setUnreadNotificationCount: jest.fn(),
|
setUnreadNotificationCount: vi.fn(),
|
||||||
tags: {},
|
tags: {},
|
||||||
timeline: [],
|
timeline: [],
|
||||||
} as unknown as Room;
|
} as unknown as Room;
|
||||||
@@ -828,8 +829,8 @@ export const mkRoom = (
|
|||||||
roomId: string,
|
roomId: string,
|
||||||
rooms?: ReturnType<typeof mkStubRoom>[],
|
rooms?: ReturnType<typeof mkStubRoom>[],
|
||||||
): MockedObject<Room> => {
|
): MockedObject<Room> => {
|
||||||
const room = mocked(mkStubRoom(roomId, roomId, client));
|
const room = vi.mocked(mkStubRoom(roomId, roomId, client));
|
||||||
mocked(room.currentState).getStateEvents.mockImplementation(mockStateEventImplementation([]));
|
vi.mocked(room.currentState).getStateEvents.mockImplementation(mockStateEventImplementation([]));
|
||||||
rooms?.push(room);
|
rooms?.push(room);
|
||||||
return room;
|
return room;
|
||||||
};
|
};
|
||||||
@@ -858,10 +859,10 @@ export const mkSpace = (
|
|||||||
rooms?: ReturnType<typeof mkStubRoom>[],
|
rooms?: ReturnType<typeof mkStubRoom>[],
|
||||||
children: string[] = [],
|
children: string[] = [],
|
||||||
): MockedObject<Room> => {
|
): MockedObject<Room> => {
|
||||||
const space = mocked(mkRoom(client, spaceId, rooms));
|
const space = vi.mocked(mkRoom(client, spaceId, rooms));
|
||||||
space.isSpaceRoom.mockReturnValue(true);
|
space.isSpaceRoom.mockReturnValue(true);
|
||||||
space.getType.mockReturnValue(RoomType.Space);
|
space.getType.mockReturnValue(RoomType.Space);
|
||||||
mocked(space.currentState).getStateEvents.mockImplementation(
|
vi.mocked(space.currentState).getStateEvents.mockImplementation(
|
||||||
mockStateEventImplementation(
|
mockStateEventImplementation(
|
||||||
children.map((roomId) =>
|
children.map((roomId) =>
|
||||||
mkEvent({
|
mkEvent({
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Com
|
|||||||
Please see LICENSE files in the repository root for full details.
|
Please see LICENSE files in the repository root for full details.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { act } from "jest-matrix-react";
|
import { act } from "test-utils-rtl";
|
||||||
|
|
||||||
import type EventEmitter from "events";
|
import type EventEmitter from "events";
|
||||||
import { type ActionPayload } from "../../src/dispatcher/payloads";
|
import { type ActionPayload } from "../../src/dispatcher/payloads";
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Com
|
|||||||
Please see LICENSE files in the repository root for full details.
|
Please see LICENSE files in the repository root for full details.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { type Mocked, mocked, type MockedObject } from "jest-mock";
|
import { type Mocked, mocked } from "jest-mock-vitest-adapter";
|
||||||
import {
|
import {
|
||||||
MatrixEvent,
|
MatrixEvent,
|
||||||
type Room,
|
type Room,
|
||||||
@@ -1468,7 +1468,7 @@ describe("DeviceListener", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
function mockKeyBackupFromServer(client: MockedObject<MatrixClient>, enabled: boolean) {
|
function mockKeyBackupFromServer(client: Mocked<MatrixClient>, enabled: boolean) {
|
||||||
client.getAccountDataFromServer.mockImplementation(async (eventType: string) => {
|
client.getAccountDataFromServer.mockImplementation(async (eventType: string) => {
|
||||||
switch (eventType) {
|
switch (eventType) {
|
||||||
case ACCOUNT_DATA_KEY_M_KEY_BACKUP:
|
case ACCOUNT_DATA_KEY_M_KEY_BACKUP:
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import { logger } from "matrix-js-sdk/src/logger";
|
|||||||
import * as MatrixJs from "matrix-js-sdk/src/matrix";
|
import * as MatrixJs from "matrix-js-sdk/src/matrix";
|
||||||
import { decodeBase64, encodeUnpaddedBase64 } from "matrix-js-sdk/src/matrix";
|
import { decodeBase64, encodeUnpaddedBase64 } from "matrix-js-sdk/src/matrix";
|
||||||
import * as encryptAESSecretStorageItemModule from "matrix-js-sdk/src/utils/encryptAESSecretStorageItem";
|
import * as encryptAESSecretStorageItemModule from "matrix-js-sdk/src/utils/encryptAESSecretStorageItem";
|
||||||
import { mocked, type MockedObject } from "jest-mock";
|
import { mocked, type MockedObject } from "jest-mock-vitest-adapter";
|
||||||
import fetchMock from "@fetch-mock/jest";
|
import fetchMock from "@fetch-mock/jest";
|
||||||
|
|
||||||
import StorageEvictedDialog from "../../src/components/views/dialogs/StorageEvictedDialog";
|
import StorageEvictedDialog from "../../src/components/views/dialogs/StorageEvictedDialog";
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ Copyright 2022 The Matrix.org Foundation C.I.C.
|
|||||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
|
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
|
||||||
Please see LICENSE files in the repository root for full details.
|
Please see LICENSE files in the repository root for full details.
|
||||||
*/
|
*/
|
||||||
import { mocked, type MockedObject } from "jest-mock";
|
import { mocked, type MockedObject } from "jest-mock-vitest-adapter";
|
||||||
import {
|
import {
|
||||||
ClientEvent,
|
ClientEvent,
|
||||||
type MatrixClient,
|
type MatrixClient,
|
||||||
@@ -602,7 +602,7 @@ describe("Notifier", () => {
|
|||||||
slotDescription: { application: "m.call", id: "" },
|
slotDescription: { application: "m.call", id: "" },
|
||||||
} as unknown as MatrixRTCSession;
|
} as unknown as MatrixRTCSession;
|
||||||
|
|
||||||
mockClient.matrixRTC.getRoomSession.mockReturnValue(mockRtcSession);
|
mocked(mockClient.matrixRTC.getRoomSession).mockReturnValue(mockRtcSession);
|
||||||
|
|
||||||
emitCallNotificationEvent();
|
emitCallNotificationEvent();
|
||||||
expect(ToastStore.sharedInstance().addOrReplaceToast).not.toHaveBeenCalled();
|
expect(ToastStore.sharedInstance().addOrReplaceToast).not.toHaveBeenCalled();
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ Please see LICENSE files in the repository root for full details.
|
|||||||
import "fake-indexeddb/auto";
|
import "fake-indexeddb/auto";
|
||||||
import React, { type ComponentProps, createRef, type RefObject } from "react";
|
import React, { type ComponentProps, createRef, type RefObject } from "react";
|
||||||
import { fireEvent, render, type RenderResult, screen, waitFor, within, act } from "jest-matrix-react";
|
import { fireEvent, render, type RenderResult, screen, waitFor, within, act } from "jest-matrix-react";
|
||||||
import { type Mocked, mocked } from "jest-mock";
|
import { type Mocked, mocked } from "jest-mock-vitest-adapter";
|
||||||
import { ClientEvent, type MatrixClient, MatrixEvent, Room, SyncState } from "matrix-js-sdk/src/matrix";
|
import { ClientEvent, type MatrixClient, MatrixEvent, Room, SyncState } from "matrix-js-sdk/src/matrix";
|
||||||
import { type MediaHandler } from "matrix-js-sdk/src/webrtc/mediaHandler";
|
import { type MediaHandler } from "matrix-js-sdk/src/webrtc/mediaHandler";
|
||||||
import * as MatrixJs from "matrix-js-sdk/src/matrix";
|
import * as MatrixJs from "matrix-js-sdk/src/matrix";
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ Please see LICENSE files in the repository root for full details.
|
|||||||
|
|
||||||
import React from "react";
|
import React from "react";
|
||||||
import { fireEvent, render, screen, waitForElementToBeRemoved } from "jest-matrix-react";
|
import { fireEvent, render, screen, waitForElementToBeRemoved } from "jest-matrix-react";
|
||||||
import { mocked, type MockedObject } from "jest-mock";
|
import { mocked, type MockedObject } from "jest-mock-vitest-adapter";
|
||||||
import fetchMock from "@fetch-mock/jest";
|
import fetchMock from "@fetch-mock/jest";
|
||||||
import { DELEGATED_OIDC_COMPATIBILITY, IdentityProviderBrand, type OidcClientConfig } from "matrix-js-sdk/src/matrix";
|
import { DELEGATED_OIDC_COMPATIBILITY, IdentityProviderBrand, type OidcClientConfig } from "matrix-js-sdk/src/matrix";
|
||||||
import { logger } from "matrix-js-sdk/src/logger";
|
import { logger } from "matrix-js-sdk/src/logger";
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ Please see LICENSE files in the repository root for full details.
|
|||||||
import React from "react";
|
import React from "react";
|
||||||
import { fireEvent, render, screen, waitFor, waitForElementToBeRemoved } from "jest-matrix-react";
|
import { fireEvent, render, screen, waitFor, waitForElementToBeRemoved } from "jest-matrix-react";
|
||||||
import { createClient, type MatrixClient, MatrixError, type OidcClientConfig } from "matrix-js-sdk/src/matrix";
|
import { createClient, type MatrixClient, MatrixError, type OidcClientConfig } from "matrix-js-sdk/src/matrix";
|
||||||
import { mocked, type MockedObject } from "jest-mock";
|
import { mocked, type MockedObject } from "jest-mock-vitest-adapter";
|
||||||
import fetchMock from "@fetch-mock/jest";
|
import fetchMock from "@fetch-mock/jest";
|
||||||
|
|
||||||
import SdkConfig, { DEFAULTS } from "../../../../../src/SdkConfig";
|
import SdkConfig, { DEFAULTS } from "../../../../../src/SdkConfig";
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ import userEvent from "@testing-library/user-event";
|
|||||||
import { type MatrixClient, MatrixError, Room, RoomType } from "matrix-js-sdk/src/matrix";
|
import { type MatrixClient, MatrixError, Room, RoomType } from "matrix-js-sdk/src/matrix";
|
||||||
import { KnownMembership } from "matrix-js-sdk/src/types";
|
import { KnownMembership } from "matrix-js-sdk/src/types";
|
||||||
import { sleep } from "matrix-js-sdk/src/utils";
|
import { sleep } from "matrix-js-sdk/src/utils";
|
||||||
import { mocked, type Mocked } from "jest-mock";
|
import { mocked, type Mocked } from "jest-mock-vitest-adapter";
|
||||||
import { UserVerificationStatus } from "matrix-js-sdk/src/crypto-api";
|
import { UserVerificationStatus } from "matrix-js-sdk/src/crypto-api";
|
||||||
|
|
||||||
import InviteDialog from "../../../../../src/components/views/dialogs/InviteDialog";
|
import InviteDialog from "../../../../../src/components/views/dialogs/InviteDialog";
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ Please see LICENSE files in the repository root for full details.
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import React from "react";
|
import React from "react";
|
||||||
import { mocked, type MockedObject } from "jest-mock";
|
import { mocked, type MockedObject } from "jest-mock-vitest-adapter";
|
||||||
import { Device, DeviceVerification, type MatrixClient } from "matrix-js-sdk/src/matrix";
|
import { Device, DeviceVerification, type MatrixClient } from "matrix-js-sdk/src/matrix";
|
||||||
import { type CryptoApi, DeviceVerificationStatus, type KeyBackupInfo } from "matrix-js-sdk/src/crypto-api";
|
import { type CryptoApi, DeviceVerificationStatus, type KeyBackupInfo } from "matrix-js-sdk/src/crypto-api";
|
||||||
import { fireEvent, render, type RenderResult, screen, waitFor } from "jest-matrix-react";
|
import { fireEvent, render, type RenderResult, screen, waitFor } from "jest-matrix-react";
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ Please see LICENSE files in the repository root for full details.
|
|||||||
|
|
||||||
import React, { type ReactElement } from "react";
|
import React, { type ReactElement } from "react";
|
||||||
import { render, screen, waitFor } from "jest-matrix-react";
|
import { render, screen, waitFor } from "jest-matrix-react";
|
||||||
import { mocked, type MockedObject } from "jest-mock";
|
import { mocked, type MockedObject } from "jest-mock-vitest-adapter";
|
||||||
import { ClientEvent, MatrixEvent, type MatrixClient } from "matrix-js-sdk/src/matrix";
|
import { ClientEvent, MatrixEvent, type MatrixClient } from "matrix-js-sdk/src/matrix";
|
||||||
|
|
||||||
import SettingsStore, { type CallbackFn } from "../../../../../src/settings/SettingsStore";
|
import SettingsStore, { type CallbackFn } from "../../../../../src/settings/SettingsStore";
|
||||||
@@ -258,7 +258,7 @@ describe("<UserSettingsDialog />", () => {
|
|||||||
it("displays an indicator when user needs to set up recovery", async () => {
|
it("displays an indicator when user needs to set up recovery", async () => {
|
||||||
// Initially, the user doesn't have secret storage, so it should display
|
// Initially, the user doesn't have secret storage, so it should display
|
||||||
// an indicator.
|
// an indicator.
|
||||||
mockClient.secretStorage.getDefaultKeyId.mockResolvedValue(null);
|
mocked(mockClient.secretStorage.getDefaultKeyId).mockResolvedValue(null);
|
||||||
|
|
||||||
const { container } = render(getComponent());
|
const { container } = render(getComponent());
|
||||||
|
|
||||||
@@ -271,7 +271,7 @@ describe("<UserSettingsDialog />", () => {
|
|||||||
|
|
||||||
// The user now has secret storage. Trigger an update and check that
|
// The user now has secret storage. Trigger an update and check that
|
||||||
// the indicator disappears.
|
// the indicator disappears.
|
||||||
mockClient.secretStorage.getDefaultKeyId.mockResolvedValue("foo");
|
mocked(mockClient.secretStorage.getDefaultKeyId).mockResolvedValue("foo");
|
||||||
mockClient.emit(ClientEvent.AccountData, new MatrixEvent({ type: "m.secret_storage.default_key" }));
|
mockClient.emit(ClientEvent.AccountData, new MatrixEvent({ type: "m.secret_storage.default_key" }));
|
||||||
|
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
|
|||||||
+1
-1
@@ -9,7 +9,7 @@ Please see LICENSE files in the repository root for full details.
|
|||||||
import React, { act } from "react";
|
import React, { act } from "react";
|
||||||
import { render } from "jest-matrix-react";
|
import { render } from "jest-matrix-react";
|
||||||
import { type CryptoApi } from "matrix-js-sdk/src/crypto-api";
|
import { type CryptoApi } from "matrix-js-sdk/src/crypto-api";
|
||||||
import { type Mocked } from "jest-mock";
|
import { type Mocked } from "jest-mock-vitest-adapter";
|
||||||
import { type MatrixClient } from "matrix-js-sdk/src/matrix";
|
import { type MatrixClient } from "matrix-js-sdk/src/matrix";
|
||||||
|
|
||||||
import { getMockClientWithEventEmitter } from "../../../../../test-utils";
|
import { getMockClientWithEventEmitter } from "../../../../../test-utils";
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import React from "react";
|
|||||||
import { EventType, getHttpUriForMxc, type IContent, type MatrixClient, MatrixEvent } from "matrix-js-sdk/src/matrix";
|
import { EventType, getHttpUriForMxc, type IContent, type MatrixClient, MatrixEvent } from "matrix-js-sdk/src/matrix";
|
||||||
import { fireEvent, render, screen } from "jest-matrix-react";
|
import { fireEvent, render, screen } from "jest-matrix-react";
|
||||||
import fetchMock from "@fetch-mock/jest";
|
import fetchMock from "@fetch-mock/jest";
|
||||||
import { type MockedObject } from "jest-mock";
|
import { type MockedObject } from "jest-mock-vitest-adapter";
|
||||||
|
|
||||||
import MatrixClientContext from "../../../../../src/contexts/MatrixClientContext";
|
import MatrixClientContext from "../../../../../src/contexts/MatrixClientContext";
|
||||||
import { type RoomPermalinkCreator } from "../../../../../src/utils/permalinks/Permalinks";
|
import { type RoomPermalinkCreator } from "../../../../../src/utils/permalinks/Permalinks";
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ Please see LICENSE files in the repository root for full details.
|
|||||||
|
|
||||||
import React, { type ComponentProps } from "react";
|
import React, { type ComponentProps } from "react";
|
||||||
import { type MatrixClient, type MatrixEvent, PushRuleKind, type Room } from "matrix-js-sdk/src/matrix";
|
import { type MatrixClient, type MatrixEvent, PushRuleKind, type Room } from "matrix-js-sdk/src/matrix";
|
||||||
import { mocked, type MockedObject } from "jest-mock";
|
import { mocked, type MockedObject } from "jest-mock-vitest-adapter";
|
||||||
import { act, render, waitFor } from "jest-matrix-react";
|
import { act, render, waitFor } from "jest-matrix-react";
|
||||||
import { PushProcessor } from "matrix-js-sdk/src/pushprocessor";
|
import { PushProcessor } from "matrix-js-sdk/src/pushprocessor";
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -11,7 +11,7 @@ import React from "react";
|
|||||||
import { type MatrixClient, ThreepidMedium } from "matrix-js-sdk/src/matrix";
|
import { type MatrixClient, ThreepidMedium } from "matrix-js-sdk/src/matrix";
|
||||||
import { logger } from "matrix-js-sdk/src/logger";
|
import { logger } from "matrix-js-sdk/src/logger";
|
||||||
import userEvent from "@testing-library/user-event";
|
import userEvent from "@testing-library/user-event";
|
||||||
import { type MockedObject } from "jest-mock";
|
import { type MockedObject } from "jest-mock-vitest-adapter";
|
||||||
|
|
||||||
import AccountUserSettingsTab from "../../../../../../../src/components/views/settings/tabs/user/AccountUserSettingsTab";
|
import AccountUserSettingsTab from "../../../../../../../src/components/views/settings/tabs/user/AccountUserSettingsTab";
|
||||||
import { SdkContextClass, SDKContext } from "../../../../../../../src/contexts/SDKContext";
|
import { SdkContextClass, SDKContext } from "../../../../../../../src/contexts/SDKContext";
|
||||||
|
|||||||
+1
-1
@@ -18,7 +18,7 @@ import {
|
|||||||
} from "../../../../../../test-utils";
|
} from "../../../../../../test-utils";
|
||||||
import MatrixClientBackedController from "../../../../../../../src/settings/controllers/MatrixClientBackedController";
|
import MatrixClientBackedController from "../../../../../../../src/settings/controllers/MatrixClientBackedController";
|
||||||
import MatrixClientBackedSettingsHandler from "../../../../../../../src/settings/handlers/MatrixClientBackedSettingsHandler";
|
import MatrixClientBackedSettingsHandler from "../../../../../../../src/settings/handlers/MatrixClientBackedSettingsHandler";
|
||||||
import type { MockedObject } from "jest-mock";
|
import type { MockedObject } from "jest-mock-vitest-adapter";
|
||||||
import {
|
import {
|
||||||
MEDIA_PREVIEW_ACCOUNT_DATA_TYPE,
|
MEDIA_PREVIEW_ACCOUNT_DATA_TYPE,
|
||||||
type MediaPreviewConfig,
|
type MediaPreviewConfig,
|
||||||
|
|||||||
+1
-1
@@ -33,7 +33,7 @@ import {
|
|||||||
MatrixError,
|
MatrixError,
|
||||||
type MatrixClient,
|
type MatrixClient,
|
||||||
} from "matrix-js-sdk/src/matrix";
|
} from "matrix-js-sdk/src/matrix";
|
||||||
import { mocked, type MockedObject } from "jest-mock";
|
import { mocked, type MockedObject } from "jest-mock-vitest-adapter";
|
||||||
import fetchMock from "@fetch-mock/jest";
|
import fetchMock from "@fetch-mock/jest";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ import {
|
|||||||
Visibility,
|
Visibility,
|
||||||
} from "matrix-js-sdk/src/matrix";
|
} from "matrix-js-sdk/src/matrix";
|
||||||
import userEvent from "@testing-library/user-event";
|
import userEvent from "@testing-library/user-event";
|
||||||
import { type MockedObject } from "jest-mock";
|
import { type MockedObject } from "jest-mock-vitest-adapter";
|
||||||
|
|
||||||
import * as createRoomModule from "../../../../../src/createRoom";
|
import * as createRoomModule from "../../../../../src/createRoom";
|
||||||
import SpaceCreateMenu, { createSpace } from "../../../../../src/components/views/spaces/SpaceCreateMenu";
|
import SpaceCreateMenu, { createSpace } from "../../../../../src/components/views/spaces/SpaceCreateMenu";
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ Please see LICENSE files in the repository root for full details.
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import React, { type ComponentProps } from "react";
|
import React, { type ComponentProps } from "react";
|
||||||
import { mocked, type Mocked } from "jest-mock";
|
import { mocked, type Mocked } from "jest-mock-vitest-adapter";
|
||||||
import { render, type RenderResult } from "jest-matrix-react";
|
import { render, type RenderResult } from "jest-matrix-react";
|
||||||
import { TypedEventEmitter, type IMyDevice, type MatrixClient, Device } from "matrix-js-sdk/src/matrix";
|
import { TypedEventEmitter, type IMyDevice, type MatrixClient, Device } from "matrix-js-sdk/src/matrix";
|
||||||
import { type VerificationRequest, VerificationRequestEvent } from "matrix-js-sdk/src/crypto-api";
|
import { type VerificationRequest, VerificationRequestEvent } from "matrix-js-sdk/src/crypto-api";
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import { DialogContent, type DialogProps } from "@matrix-org/react-sdk-module-ap
|
|||||||
import { screen, within } from "jest-matrix-react";
|
import { screen, within } from "jest-matrix-react";
|
||||||
import userEvent from "@testing-library/user-event";
|
import userEvent from "@testing-library/user-event";
|
||||||
import { type MatrixClient } from "matrix-js-sdk/src/matrix";
|
import { type MatrixClient } from "matrix-js-sdk/src/matrix";
|
||||||
import { type Mocked } from "jest-mock";
|
import { type Mocked } from "jest-mock-vitest-adapter";
|
||||||
|
|
||||||
import { ProxiedModuleApi } from "../../../src/modules/ProxiedModuleApi";
|
import { ProxiedModuleApi } from "../../../src/modules/ProxiedModuleApi";
|
||||||
import { getMockClientWithEventEmitter, mkRoom, stubClient } from "../../test-utils";
|
import { getMockClientWithEventEmitter, mkRoom, stubClient } from "../../test-utils";
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ import {
|
|||||||
} from "matrix-js-sdk/src/matrix";
|
} from "matrix-js-sdk/src/matrix";
|
||||||
import { KnownMembership } from "matrix-js-sdk/src/types";
|
import { KnownMembership } from "matrix-js-sdk/src/types";
|
||||||
import { logger } from "matrix-js-sdk/src/logger";
|
import { logger } from "matrix-js-sdk/src/logger";
|
||||||
import { type Mocked } from "jest-mock";
|
import { type Mocked } from "jest-mock-vitest-adapter";
|
||||||
|
|
||||||
import { OwnBeaconStore, OwnBeaconStoreEvent } from "../../../src/stores/OwnBeaconStore";
|
import { OwnBeaconStore, OwnBeaconStoreEvent } from "../../../src/stores/OwnBeaconStore";
|
||||||
import {
|
import {
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Com
|
|||||||
Please see LICENSE files in the repository root for full details.
|
Please see LICENSE files in the repository root for full details.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { mocked } from "jest-mock";
|
import { mocked } from "jest-mock-vitest-adapter";
|
||||||
import { KnownMembership, MatrixError, Room } from "matrix-js-sdk/src/matrix";
|
import { KnownMembership, MatrixError, Room } from "matrix-js-sdk/src/matrix";
|
||||||
import { sleep } from "matrix-js-sdk/src/utils";
|
import { sleep } from "matrix-js-sdk/src/utils";
|
||||||
import {
|
import {
|
||||||
@@ -181,7 +181,7 @@ describe("RoomViewStore", function () {
|
|||||||
jest.clearAllMocks();
|
jest.clearAllMocks();
|
||||||
mockClient.credentials = { userId: userId };
|
mockClient.credentials = { userId: userId };
|
||||||
mockClient.joinRoom.mockResolvedValue(room);
|
mockClient.joinRoom.mockResolvedValue(room);
|
||||||
mockClient.getRoom.mockImplementation((roomId: string): Room | null => {
|
mockClient.getRoom.mockImplementation((roomId?: string): Room | null => {
|
||||||
if (roomId === room.roomId) return room;
|
if (roomId === room.roomId) return room;
|
||||||
if (roomId === room2.roomId) return room2;
|
if (roomId === room2.roomId) return room2;
|
||||||
return null;
|
return null;
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Com
|
|||||||
Please see LICENSE files in the repository root for full details.
|
Please see LICENSE files in the repository root for full details.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { type Mocked, mocked } from "jest-mock";
|
import { type Mocked, mocked } from "jest-mock-vitest-adapter";
|
||||||
import {
|
import {
|
||||||
type HttpApiEvent,
|
type HttpApiEvent,
|
||||||
type HttpApiEventHandlerMap,
|
type HttpApiEventHandlerMap,
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ Please see LICENSE files in the repository root for full details.
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { logger } from "matrix-js-sdk/src/logger";
|
import { logger } from "matrix-js-sdk/src/logger";
|
||||||
import { type Mocked } from "jest-mock";
|
import { type Mocked } from "jest-mock-vitest-adapter";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
type GenericPosition,
|
type GenericPosition,
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Com
|
|||||||
Please see LICENSE files in the repository root for full details.
|
Please see LICENSE files in the repository root for full details.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { type Mocked, mocked } from "jest-mock";
|
import { type Mocked, mocked } from "jest-mock-vitest-adapter";
|
||||||
import { type Device, type MatrixClient } from "matrix-js-sdk/src/matrix";
|
import { type Device, type MatrixClient } from "matrix-js-sdk/src/matrix";
|
||||||
|
|
||||||
import { getDeviceCryptoInfo, getUserDeviceIds } from "../../../../src/utils/crypto/deviceInfo";
|
import { getDeviceCryptoInfo, getUserDeviceIds } from "../../../../src/utils/crypto/deviceInfo";
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Com
|
|||||||
Please see LICENSE files in the repository root for full details.
|
Please see LICENSE files in the repository root for full details.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { mocked, type Mocked } from "jest-mock";
|
import { mocked, type Mocked } from "jest-mock-vitest-adapter";
|
||||||
import { type MatrixClient, type Room } from "matrix-js-sdk/src/matrix";
|
import { type MatrixClient, type Room } from "matrix-js-sdk/src/matrix";
|
||||||
import { sleep } from "matrix-js-sdk/src/utils";
|
import { sleep } from "matrix-js-sdk/src/utils";
|
||||||
|
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ import {
|
|||||||
ReceiptType,
|
ReceiptType,
|
||||||
type AccountDataEvents,
|
type AccountDataEvents,
|
||||||
} from "matrix-js-sdk/src/matrix";
|
} from "matrix-js-sdk/src/matrix";
|
||||||
import { type Mocked, mocked } from "jest-mock";
|
import { type Mocked, mocked } from "jest-mock-vitest-adapter";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
localNotificationsAreSilenced,
|
localNotificationsAreSilenced,
|
||||||
|
|||||||
@@ -382,10 +382,10 @@ describe("Permalinks", function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("should generate a room permalink for room IDs with some candidate servers", function () {
|
it("should generate a room permalink for room IDs with some candidate servers", function () {
|
||||||
mockClient.getRoom.mockImplementation((roomId: Room["roomId"]) => {
|
mockClient.getRoom.mockImplementation((roomId?: string) => {
|
||||||
return mockRoom(roomId, [
|
return mockRoom(roomId!, [
|
||||||
makeMemberWithPL(roomId, "@alice:first", 100),
|
makeMemberWithPL(roomId!, "@alice:first", 100),
|
||||||
makeMemberWithPL(roomId, "@bob:second", 0),
|
makeMemberWithPL(roomId!, "@bob:second", 0),
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
const result = makeRoomPermalink(mockClient, "!somewhere:example.org");
|
const result = makeRoomPermalink(mockClient, "!somewhere:example.org");
|
||||||
@@ -399,10 +399,10 @@ describe("Permalinks", function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("should generate a room permalink for room aliases without candidate servers", function () {
|
it("should generate a room permalink for room aliases without candidate servers", function () {
|
||||||
mockClient.getRoom.mockImplementation((roomId: Room["roomId"]) => {
|
mockClient.getRoom.mockImplementation((roomId?: string) => {
|
||||||
return mockRoom(roomId, [
|
return mockRoom(roomId!, [
|
||||||
makeMemberWithPL(roomId, "@alice:first", 100),
|
makeMemberWithPL(roomId!, "@alice:first", 100),
|
||||||
makeMemberWithPL(roomId, "@bob:second", 0),
|
makeMemberWithPL(roomId!, "@bob:second", 0),
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
const result = makeRoomPermalink(mockClient, "#somewhere:example.org");
|
const result = makeRoomPermalink(mockClient, "#somewhere:example.org");
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
import { MatrixError, type MatrixClient } from "matrix-js-sdk/src/matrix";
|
import { MatrixError, type MatrixClient } from "matrix-js-sdk/src/matrix";
|
||||||
import { waitFor } from "jest-matrix-react";
|
import { waitFor } from "jest-matrix-react";
|
||||||
|
|
||||||
import type { MockedObject } from "jest-mock";
|
import type { MockedObject } from "jest-mock-vitest-adapter";
|
||||||
import { UserMenuViewModel } from "../../../src/viewmodels/menus/UserMenuViewModel";
|
import { UserMenuViewModel } from "../../../src/viewmodels/menus/UserMenuViewModel";
|
||||||
import { getMockClientWithEventEmitter, mockClientMethodsServer, mockClientMethodsUser } from "../../test-utils";
|
import { getMockClientWithEventEmitter, mockClientMethodsServer, mockClientMethodsUser } from "../../test-utils";
|
||||||
import { MatrixDispatcher } from "../../../src/dispatcher/dispatcher";
|
import { MatrixDispatcher } from "../../../src/dispatcher/dispatcher";
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
|
|
||||||
import { expect } from "@jest/globals";
|
import { expect } from "@jest/globals";
|
||||||
|
|
||||||
import type { MockedObject } from "jest-mock";
|
import type { MockedObject } from "jest-mock-vitest-adapter";
|
||||||
import type { MatrixClient, IPreviewUrlResponse } from "matrix-js-sdk/src/matrix";
|
import type { MatrixClient, IPreviewUrlResponse } from "matrix-js-sdk/src/matrix";
|
||||||
import {
|
import {
|
||||||
BUNDLED_LINK_PREVIEWS,
|
BUNDLED_LINK_PREVIEWS,
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ import {
|
|||||||
EventStatus,
|
EventStatus,
|
||||||
} from "matrix-js-sdk/src/matrix";
|
} from "matrix-js-sdk/src/matrix";
|
||||||
import { RoomStatusBarState } from "@element-hq/web-shared-components";
|
import { RoomStatusBarState } from "@element-hq/web-shared-components";
|
||||||
import { type MockedObject } from "jest-mock";
|
import { type MockedObject } from "jest-mock-vitest-adapter";
|
||||||
|
|
||||||
import { mkEvent, mkRoom, stubClient } from "../../test-utils";
|
import { mkEvent, mkRoom, stubClient } from "../../test-utils";
|
||||||
import { RoomStatusBarViewModel } from "../../../src/viewmodels/room/RoomStatusBar";
|
import { RoomStatusBarViewModel } from "../../../src/viewmodels/room/RoomStatusBar";
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { type MatrixClient, type Room, RoomEvent } from "matrix-js-sdk/src/matrix";
|
import { type MatrixClient, type Room, RoomEvent } from "matrix-js-sdk/src/matrix";
|
||||||
import { type MockedObject } from "jest-mock";
|
import { type MockedObject } from "jest-mock-vitest-adapter";
|
||||||
import { createRef } from "react";
|
import { createRef } from "react";
|
||||||
|
|
||||||
import { mkRoom, stubClient } from "../../test-utils";
|
import { mkRoom, stubClient } from "../../test-utils";
|
||||||
|
|||||||
@@ -18,7 +18,9 @@
|
|||||||
"strict": true,
|
"strict": true,
|
||||||
"types": ["node", "modernizr"],
|
"types": ["node", "modernizr"],
|
||||||
"paths": {
|
"paths": {
|
||||||
"jest-matrix-react": ["./test/test-utils/jest-matrix-react"]
|
"jest-matrix-react": ["./test/test-utils/jest-matrix-react"],
|
||||||
|
"test-utils-rtl": ["./test/test-utils/jest-matrix-react"],
|
||||||
|
"jest-mock-vitest-adapter": ["./test/setup/adapter.ts"]
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"include": [
|
"include": [
|
||||||
|
|||||||
@@ -6,8 +6,36 @@ Please see LICENSE files in the repository root for full details.
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { defineProject } from "vitest/config";
|
import { defineProject } from "vitest/config";
|
||||||
|
import { resolve } from "node:path";
|
||||||
|
|
||||||
export default defineProject({
|
export default defineProject({
|
||||||
|
resolve: {
|
||||||
|
alias: [
|
||||||
|
{ find: "test-utils-rtl", replacement: resolve(__dirname, "./test/test-utils/jest-matrix-react") },
|
||||||
|
// Stub out workers as they do not play well under test
|
||||||
|
{
|
||||||
|
find: /.*workers\/(.+)Factory/,
|
||||||
|
replacement: resolve(__dirname, "./__mocks__/workerFactoryMock.js"),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
find: /.*waveWorker\.min\.js$/,
|
||||||
|
replacement: resolve(__dirname, "./__mocks__/empty.js"),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
find: /.*decoderWorker\.min\.js$/,
|
||||||
|
replacement: resolve(__dirname, "./__mocks__/empty.js"),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
find: /.*decoderWorker\.min\.wasm$/,
|
||||||
|
replacement: resolve(__dirname, "./__mocks__/empty.js"),
|
||||||
|
},
|
||||||
|
// Stub this out as we lack AudioWorkletProcessor in the test env
|
||||||
|
{
|
||||||
|
find: "./recorderWorkletFactory",
|
||||||
|
replacement: resolve(__dirname, "./__mocks__/empty.js"),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
test: {
|
test: {
|
||||||
include: ["src/**/*.test.{ts,tsx}"],
|
include: ["src/**/*.test.{ts,tsx}"],
|
||||||
environment: "node",
|
environment: "node",
|
||||||
|
|||||||
Generated
+6
@@ -226,6 +226,9 @@ catalogs:
|
|||||||
'@vitest/coverage-v8':
|
'@vitest/coverage-v8':
|
||||||
specifier: 4.1.9
|
specifier: 4.1.9
|
||||||
version: 4.1.9
|
version: 4.1.9
|
||||||
|
'@vitest/spy':
|
||||||
|
specifier: 4.1.9
|
||||||
|
version: 4.1.9
|
||||||
matrix-web-i18n:
|
matrix-web-i18n:
|
||||||
specifier: 3.6.0
|
specifier: 3.6.0
|
||||||
version: 3.6.0
|
version: 3.6.0
|
||||||
@@ -883,6 +886,9 @@ importers:
|
|||||||
'@typescript-eslint/parser':
|
'@typescript-eslint/parser':
|
||||||
specifier: ^8.19.0
|
specifier: ^8.19.0
|
||||||
version: 8.61.0(eslint@8.57.1)(typescript@6.0.3)
|
version: 8.61.0(eslint@8.57.1)(typescript@6.0.3)
|
||||||
|
'@vitest/spy':
|
||||||
|
specifier: 'catalog:'
|
||||||
|
version: 4.1.9
|
||||||
babel-jest:
|
babel-jest:
|
||||||
specifier: ^30.0.0
|
specifier: ^30.0.0
|
||||||
version: 30.4.1(@babel/core@7.29.7)
|
version: 30.4.1(@babel/core@7.29.7)
|
||||||
|
|||||||
@@ -33,6 +33,7 @@ catalog:
|
|||||||
vite-plugin-node-polyfills: 0.28.0
|
vite-plugin-node-polyfills: 0.28.0
|
||||||
vite-plugin-svgr: 5.2.0
|
vite-plugin-svgr: 5.2.0
|
||||||
vitest: 4.1.9
|
vitest: 4.1.9
|
||||||
|
"@vitest/spy": 4.1.9
|
||||||
"@vitest/coverage-v8": 4.1.9
|
"@vitest/coverage-v8": 4.1.9
|
||||||
"@vitest/browser-playwright": 4.1.9
|
"@vitest/browser-playwright": 4.1.9
|
||||||
"@vitejs/plugin-react": 6.0.2
|
"@vitejs/plugin-react": 6.0.2
|
||||||
|
|||||||
Reference in New Issue
Block a user