From 2ab8b46ba3fcac15f66b0c040d7a822aa9ae882e Mon Sep 17 00:00:00 2001 From: Kerry Date: Wed, 9 Mar 2022 14:23:58 +0100 Subject: [PATCH] include test/test-utils in tsconfig (#8000) * move js utils into directory Signed-off-by: Kerry Archibald * typescripterize js test-utils Signed-off-by: Kerry Archibald * move test utils to directory Signed-off-by: Kerry Archibald * move remaining mock functions to directory Signed-off-by: Kerry Archibald * update imports Signed-off-by: Kerry Archibald * missed copyright Signed-off-by: Kerry Archibald * type wait for update Signed-off-by: Kerry Archibald * add tests/test-utils to tsconfig * lint Signed-off-by: Kerry Archibald * fix wrapper type Signed-off-by: Kerry Archibald --- test/test-utils/test-utils.ts | 60 +++++++++++++++++++---------------- test/test-utils/wrappers.tsx | 8 +++-- tsconfig.json | 4 ++- 3 files changed, 41 insertions(+), 31 deletions(-) diff --git a/test/test-utils/test-utils.ts b/test/test-utils/test-utils.ts index 6eb65aa5f5..289fb8e5d7 100644 --- a/test/test-utils/test-utils.ts +++ b/test/test-utils/test-utils.ts @@ -21,6 +21,7 @@ import dis from '../../src/dispatcher/dispatcher'; import { makeType } from "../../src/utils/TypeUtils"; import { ValidatedServerConfig } from "../../src/utils/AutoDiscoveryUtils"; import { EnhancedMap } from "../../src/utils/maps"; +import { AsyncStoreWithClient } from "../../src/stores/AsyncStoreWithClient"; import MatrixClientBackedSettingsHandler from "../../src/settings/handlers/MatrixClientBackedSettingsHandler"; /** @@ -38,11 +39,9 @@ export function stubClient() { // // 'sandbox.restore()' doesn't work correctly on inherited methods, // so we do this for each method - const methods = ['get', 'unset', 'replaceUsingCreds']; - for (let i = 0; i < methods.length; i++) { - const methodName = methods[i]; - peg[methods[i]] = jest.spyOn(peg, methodName); - } + jest.spyOn(peg, 'get'); + jest.spyOn(peg, 'unset'); + jest.spyOn(peg, 'replaceUsingCreds'); // MatrixClientPeg.get() is called a /lot/, so implement it with our own // fast stub function rather than a sinon stub peg.get = function() { return client; }; @@ -54,7 +53,7 @@ export function stubClient() { * * @returns {object} MatrixClient stub */ -export function createTestClient() { +export function createTestClient(): MatrixClient { const eventEmitter = new EventEmitter(); return { @@ -76,7 +75,7 @@ export function createTestClient() { removeListener: eventEmitter.removeListener.bind(eventEmitter), emit: eventEmitter.emit.bind(eventEmitter), isRoomEncrypted: jest.fn().mockReturnValue(false), - peekInRoom: jest.fn().mockResolvedValue(mkStubRoom()), + peekInRoom: jest.fn().mockResolvedValue(mkStubRoom(undefined, undefined, undefined)), paginateEventTimeline: jest.fn().mockResolvedValue(undefined), sendReadReceipt: jest.fn().mockResolvedValue(undefined), @@ -86,10 +85,12 @@ export function createTestClient() { getThirdpartyProtocols: jest.fn().mockResolvedValue({}), getClientWellKnown: jest.fn().mockReturnValue(null), supportsVoip: jest.fn().mockReturnValue(true), - getTurnServersExpiry: jest.fn().mockReturnValue(2^32), + getTurnServersExpiry: jest.fn().mockReturnValue(2 ^ 32), getThirdpartyUser: jest.fn().mockResolvedValue([]), getAccountData: (type) => { return mkEvent({ + user: undefined, + room: undefined, type, event: true, content: {}, @@ -100,11 +101,10 @@ export function createTestClient() { setRoomAccountData: jest.fn(), sendTyping: jest.fn().mockResolvedValue({}), sendMessage: () => jest.fn().mockResolvedValue({}), - sendStateEvent: jest.fn().mockResolvedValue(), + sendStateEvent: jest.fn().mockResolvedValue(undefined), getSyncState: () => "SYNCING", generateClientSecret: () => "t35tcl1Ent5ECr3T", isGuest: jest.fn().mockReturnValue(false), - isCryptoEnabled: () => false, getRoomHierarchy: jest.fn().mockReturnValue({ rooms: [], }), @@ -122,23 +122,24 @@ export function createTestClient() { getCapabilities: jest.fn().mockResolvedValue({}), supportsExperimentalThreads: () => false, getRoomUpgradeHistory: jest.fn().mockReturnValue([]), - getOpenIdToken: jest.fn().mockResolvedValue(), + getOpenIdToken: jest.fn().mockResolvedValue(undefined), registerWithIdentityServer: jest.fn().mockResolvedValue({}), getIdentityAccount: jest.fn().mockResolvedValue({}), - getTerms: jest.fn().mockResolvedValueOnce(), - doesServerSupportUnstableFeature: jest.fn().mockResolvedValue(), - getPushRules: jest.fn().mockResolvedValue(), + getTerms: jest.fn().mockResolvedValueOnce(undefined), + doesServerSupportUnstableFeature: jest.fn().mockResolvedValue(undefined), + getPushRules: jest.fn().mockResolvedValue(undefined), getPushers: jest.fn().mockResolvedValue({ pushers: [] }), getThreePids: jest.fn().mockResolvedValue({ threepids: [] }), - setPusher: jest.fn().mockResolvedValue(), - setPushRuleEnabled: jest.fn().mockResolvedValue(), - setPushRuleActions: jest.fn().mockResolvedValue(), + setPusher: jest.fn().mockResolvedValue(undefined), + setPushRuleEnabled: jest.fn().mockResolvedValue(undefined), + setPushRuleActions: jest.fn().mockResolvedValue(undefined), isCryptoEnabled: jest.fn().mockReturnValue(false), - }; + } as unknown as MatrixClient; } type MakeEventPassThruProps = { user: User["userId"]; + relatesTo?: IEventRelation; event?: boolean; ts?: number; skey?: string; @@ -282,9 +283,10 @@ export type MessageEventProps = MakeEventPassThruProps & { * @param {string=} opts.msg Optional. The content.body for the event. * @return {Object|MatrixEvent} The event */ -export function mkMessage({ - msg, relatesTo, ...opts -}: MessageEventProps): MatrixEvent { +export function mkMessage({ msg, relatesTo, ...opts }: MakeEventPassThruProps & { + room: Room["roomId"]; + msg?: string; +}): MatrixEvent { if (!opts.room || !opts.user) { throw new Error("Missing .room or .user from options"); } @@ -302,7 +304,7 @@ export function mkMessage({ return mkEvent(event); } -export function mkStubRoom(roomId = null, name: string, client: MatrixClient): Room { +export function mkStubRoom(roomId: string = null, name: string, client: MatrixClient): Room { const stubTimeline = { getEvents: () => [] } as unknown as EventTimeline; return { roomId, @@ -385,30 +387,34 @@ export function getDispatchForStore(store) { // These methods make some use of some private methods on the AsyncStoreWithClient to simplify getting into a consistent // ready state without needing to wire up a dispatcher and pretend to be a js-sdk client. -export const setupAsyncStoreWithClient = async (store: AsyncStoreWithClient, client: MatrixClient) => { +export const setupAsyncStoreWithClient = async (store: AsyncStoreWithClient, client: MatrixClient) => { // @ts-ignore store.readyStore.useUnitTestClient(client); // @ts-ignore await store.onReady(); }; -export const resetAsyncStoreWithClient = async (store: AsyncStoreWithClient) => { +export const resetAsyncStoreWithClient = async (store: AsyncStoreWithClient) => { // @ts-ignore await store.onNotReady(); }; -export const mockStateEventImplementation = (events: MatrixEvent[]): typeof RoomState['getStateEvents'] => { +export const mockStateEventImplementation = (events: MatrixEvent[]) => { const stateMap = new EnhancedMap>(); events.forEach(event => { stateMap.getOrCreate(event.getType(), new Map()).set(event.getStateKey(), event); }); - return (eventType: string, stateKey?: string) => { + // recreate the overloading in RoomState + function getStateEvents(eventType: EventType | string): MatrixEvent[]; + function getStateEvents(eventType: EventType | string, stateKey: string): MatrixEvent; + function getStateEvents(eventType: EventType | string, stateKey?: string) { if (stateKey || stateKey === "") { return stateMap.get(eventType)?.get(stateKey) || null; } return Array.from(stateMap.get(eventType)?.values() || []); - }; + } + return getStateEvents; }; export const mkRoom = (client: MatrixClient, roomId: string, rooms?: ReturnType[]) => { diff --git a/test/test-utils/wrappers.tsx b/test/test-utils/wrappers.tsx index 070e2313ef..24205cfa73 100644 --- a/test/test-utils/wrappers.tsx +++ b/test/test-utils/wrappers.tsx @@ -20,8 +20,10 @@ import { MatrixClient } from "matrix-js-sdk/src/matrix"; import { MatrixClientPeg as peg } from '../../src/MatrixClientPeg'; import MatrixClientContext from "../../src/contexts/MatrixClientContext"; -export function wrapInMatrixClientContext(WrappedComponent) { - class Wrapper extends React.Component<{ wrappedRef?: RefCallback }> { +type WrapperType = React.Component<{ wrappedRef?: RefCallback }>; + +export function wrapInMatrixClientContext(WrappedComponent): WrapperType { + class Wrapper extends React.Component<{ wrappedRef?: RefCallback }> { _matrixClient: MatrixClient; constructor(props) { super(props); @@ -35,5 +37,5 @@ export function wrapInMatrixClientContext(WrappedComponent) { ; } } - return Wrapper; + return Wrapper as unknown as WrapperType; } diff --git a/tsconfig.json b/tsconfig.json index 40fcbe4364..1412a95fe0 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -21,6 +21,8 @@ }, "include": [ "./src/**/*.ts", - "./src/**/*.tsx" + "./src/**/*.tsx" , + "./test/test-utils/**/*.ts", + "./test/test-utils/**/*.tsx", ], }