Files

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

196 lines
7.0 KiB
TypeScript
Raw Permalink Normal View History

2022-03-16 14:11:06 +01:00
/*
2024-09-09 14:57:16 +01:00
Copyright 2024 New Vector Ltd.
2022-03-16 14:11:06 +01:00
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
2024-09-09 14:57:16 +01:00
Please see LICENSE files in the repository root for full details.
2022-03-16 14:11:06 +01:00
*/
2026-08-04 10:15:07 +01:00
import EventEmitter from "node:events";
2026-06-19 16:34:18 +01:00
import { type MockedObject } from "vitest";
import { type MethodLikeKeys, type PropertyLikeKeys } from "jest-mock";
import { type MockedObjectDeep } from "@vitest/spy";
2022-10-13 18:22:25 +01:00
import { Feature, ServerSupport } from "matrix-js-sdk/src/feature";
import { type MatrixClient, type Room, User } from "matrix-js-sdk/src/matrix";
2022-03-16 14:11:06 +01:00
import { MatrixClientPeg } from "../../src/MatrixClientPeg";
2026-06-19 16:34:18 +01:00
import { vi } from "../setup/adapter.ts";
2022-03-16 14:11:06 +01:00
/**
* Mocked generic class with a real EventEmitter.
* Useful for mocks which need event emitters.
*/
export class MockEventEmitter<T> extends EventEmitter {
/**
* Construct a new event emitter with additional properties/functions. The event emitter functions
* like .emit and .on will be real.
* @param mockProperties An object with the mock property or function implementations. 'getters'
* are correctly cloned to this event emitter.
*/
2022-11-04 10:48:08 +00:00
constructor(mockProperties: Partial<Record<MethodLikeKeys<T> | PropertyLikeKeys<T>, unknown>> = {}) {
super();
// We must use defineProperties and not assign as the former clones getters correctly,
// whereas the latter invokes the getter and sets the return value permanently on the
// destination object.
Object.defineProperties(this, Object.getOwnPropertyDescriptors(mockProperties));
}
}
2022-03-16 14:11:06 +01:00
/**
* Mock client with real event emitter
* useful for testing code that listens
* to MatrixClient events
*/
export class MockClientWithEventEmitter extends EventEmitter {
2022-11-04 10:48:08 +00:00
constructor(mockProperties: Partial<Record<MethodLikeKeys<MatrixClient>, unknown>> = {}) {
2022-03-16 14:11:06 +01:00
super();
Object.assign(this, mockProperties);
}
}
/**
* - make a mock client
* - cast the type to mocked(MatrixClient)
* - spy on MatrixClientPeg.get to return the mock
* eg
* ```
* const mockClient = getMockClientWithEventEmitter({
2026-06-19 16:34:18 +01:00
getUserId: vi.fn().mockReturnValue(aliceId),
2022-03-16 14:11:06 +01:00
});
* ```
*
* See also {@link stubClient} which does something similar but uses a more complete mock client.
2022-03-16 14:11:06 +01:00
*/
export const getMockClientWithEventEmitter = (
mockProperties: Partial<Record<keyof MatrixClient, unknown>>,
2022-03-16 14:11:06 +01:00
): MockedObject<MatrixClient> => {
2026-06-19 16:34:18 +01:00
const mock = vi.mocked(new MockClientWithEventEmitter(mockProperties) as unknown as MatrixClient);
2022-03-16 14:11:06 +01:00
2026-06-19 16:34:18 +01:00
vi.spyOn(MatrixClientPeg, "get").mockReturnValue(mock);
vi.spyOn(MatrixClientPeg, "safeGet").mockReturnValue(mock);
2022-10-13 18:22:25 +01:00
2022-11-04 10:48:08 +00:00
// @ts-ignore simplified test stub
2022-10-13 18:22:25 +01:00
mock.canSupport = new Map();
Object.keys(Feature).forEach((feature) => {
mock.canSupport.set(feature as Feature, ServerSupport.Stable);
});
2022-03-16 14:11:06 +01:00
return mock;
};
export const unmockClientPeg = () => {
2026-06-19 16:34:18 +01:00
vi.spyOn(MatrixClientPeg, "get").mockRestore();
vi.spyOn(MatrixClientPeg, "safeGet").mockRestore();
};
/**
* Returns basic mocked client methods related to the current user
* ```
* const mockClient = getMockClientWithEventEmitter({
...mockClientMethodsUser('@mytestuser:domain'),
});
* ```
*/
2026-06-19 16:34:18 +01:00
export const mockClientMethodsUser = (userId = "@alice:domain") =>
({
getUserId: vi.fn().mockReturnValue(userId),
getDomain: vi.fn().mockReturnValue(userId.split(":")[1]),
getSafeUserId: vi.fn().mockReturnValue(userId),
getUser: vi.fn().mockReturnValue(new User(userId)),
isGuest: vi.fn().mockReturnValue(false),
mxcUrlToHttp: vi.fn().mockReturnValue("mock-mxcUrlToHttp"),
credentials: { userId },
getThreePids: vi.fn().mockResolvedValue({ threepids: [] }),
getAccessToken: vi.fn(),
getDeviceId: vi.fn(),
getAccountData: vi.fn(),
}) satisfies MockedObjectDeep<any>;
2022-06-02 10:25:56 +02:00
/**
* Returns basic mocked client methods related to rendering events
* ```
* const mockClient = getMockClientWithEventEmitter({
...mockClientMethodsUser('@mytestuser:domain'),
});
* ```
*/
2026-06-19 16:34:18 +01:00
export const mockClientMethodsEvents = () =>
({
decryptEventIfNeeded: vi.fn(),
getPushActionsForEvent: vi.fn(),
}) satisfies MockedObjectDeep<any>;
2022-08-01 08:47:13 +02:00
/**
* Returns basic mocked pushProcessor
*/
2026-06-19 16:34:18 +01:00
export const mockClientPushProcessor = () =>
({
pushProcessor: {
getPushRuleById: vi.fn(),
ruleMatchesEvent: vi.fn(),
},
}) satisfies MockedObjectDeep<any>;
2022-08-01 08:47:13 +02:00
/**
* Returns basic mocked client methods related to server support
*/
2022-11-04 10:48:08 +00:00
export const mockClientMethodsServer = (): Partial<Record<MethodLikeKeys<MatrixClient>, unknown>> => ({
2026-06-19 16:34:18 +01:00
getIdentityServerUrl: vi.fn(),
getHomeserverUrl: vi.fn(),
getCapabilities: vi.fn().mockResolvedValue({}),
getCachedCapabilities: vi.fn().mockResolvedValue({}),
getClientWellKnown: vi.fn().mockReturnValue({}),
waitForClientWellKnown: vi.fn().mockResolvedValue({}),
doesServerSupportUnstableFeature: vi.fn().mockResolvedValue(false),
isVersionSupported: vi.fn().mockResolvedValue(false),
getVersions: vi.fn().mockResolvedValue({}),
isFallbackICEServerAllowed: vi.fn(),
2022-08-01 08:47:13 +02:00
});
2022-10-11 11:10:55 +02:00
export const mockClientMethodsDevice = (
deviceId = "test-device-id",
2022-11-04 10:48:08 +00:00
): Partial<Record<MethodLikeKeys<MatrixClient>, unknown>> => ({
2026-06-19 16:34:18 +01:00
getDeviceId: vi.fn().mockReturnValue(deviceId),
getDevices: vi.fn().mockResolvedValue({ devices: [] }),
2022-10-11 11:10:55 +02:00
});
export const mockClientMethodsCrypto = (): Partial<
2022-11-04 10:48:08 +00:00
Record<MethodLikeKeys<MatrixClient> & PropertyLikeKeys<MatrixClient>, unknown>
2022-10-11 11:10:55 +02:00
> => ({
2026-06-19 16:34:18 +01:00
isKeyBackupKeyStored: vi.fn(),
getCrossSigningCacheCallbacks: vi.fn().mockReturnValue({ getCrossSigningKeyCache: vi.fn() }),
2025-06-18 12:20:17 -04:00
secretStorage: {
2026-06-19 16:34:18 +01:00
hasKey: vi.fn(),
isStored: vi.fn().mockResolvedValue(null),
getDefaultKeyId: vi.fn().mockResolvedValue(null),
2025-06-18 12:20:17 -04:00
},
2026-06-19 16:34:18 +01:00
getCrypto: vi.fn().mockReturnValue({
getUserDeviceInfo: vi.fn(),
getDeviceVerificationStatus: vi.fn().mockResolvedValue(null),
getCrossSigningStatus: vi.fn().mockResolvedValue({
publicKeysOnDevice: true,
privateKeysInSecretStorage: false,
privateKeysCachedLocally: {
masterKey: true,
selfSigningKey: true,
userSigningKey: true,
},
}),
2026-06-19 16:34:18 +01:00
isCrossSigningReady: vi.fn().mockResolvedValue(true),
isSecretStorageReady: vi.fn(),
getSessionBackupPrivateKey: vi.fn(),
getVersion: vi.fn().mockReturnValue("Version 0"),
getOwnDeviceKeys: vi.fn().mockReturnValue(new Promise(() => {})),
getCrossSigningKeyId: vi.fn(),
isEncryptionEnabledInRoom: vi.fn().mockResolvedValue(false),
getKeyBackupInfo: vi.fn().mockResolvedValue(null),
}),
});
export const mockClientMethodsRooms = (rooms: Room[] = []): Partial<Record<MethodLikeKeys<MatrixClient>, unknown>> => ({
getVisibleRooms: vi.fn().mockReturnValue(rooms),
2026-06-19 16:34:18 +01:00
getRooms: vi.fn().mockReturnValue(rooms),
getRoom: vi.fn((roomId) => rooms.find((r) => r.roomId === roomId) ?? null),
isRoomEncrypted: vi.fn(),
2022-10-11 11:10:55 +02:00
});