Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update Jest to more recent release #11409

Merged
merged 18 commits into from
Aug 16, 2023
Merged
Show file tree
Hide file tree
Changes from 17 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -158,13 +158,14 @@
"@types/fs-extra": "^11.0.0",
"@types/geojson": "^7946.0.8",
"@types/glob-to-regexp": "^0.4.1",
"@types/jest": "29.2.6",
"@types/jest": "29.5.3",
"@types/katex": "^0.16.0",
"@types/lodash": "^4.14.168",
"@types/modernizr": "^3.5.3",
"@types/node": "^16",
"@types/node-fetch": "^2.6.2",
"@types/pako": "^2.0.0",
"@types/prettier": "^2.7.0",
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks like this was previously being pulled in transitively, but is no more.

"@types/qrcode": "^1.3.5",
"@types/react": "17.0.58",
"@types/react-beautiful-dnd": "^13.0.0",
Expand Down Expand Up @@ -202,10 +203,10 @@
"express": "^4.18.2",
"fetch-mock-jest": "^1.5.1",
"fs-extra": "^11.0.0",
"jest": "29.3.1",
"jest-canvas-mock": "2.4.0",
"jest-environment-jsdom": "^29.2.2",
"jest-mock": "^29.2.2",
"jest": "^29.6.2",
"jest-canvas-mock": "^2.5.2",
"jest-environment-jsdom": "^29.6.2",
"jest-mock": "^29.6.2",
"jest-raw-loader": "^1.0.1",
"jsqr": "^1.4.0",
"matrix-mock-request": "^2.5.0",
Expand Down
19 changes: 10 additions & 9 deletions test/DeviceListener-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,17 +61,18 @@ describe("DeviceListener", () => {
let mockClient: Mocked<MatrixClient>;
let mockCrypto: Mocked<CryptoApi>;

// spy on various toasts' hide and show functions
// easier than mocking
jest.spyOn(SetupEncryptionToast, "showToast");
jest.spyOn(SetupEncryptionToast, "hideToast");
jest.spyOn(BulkUnverifiedSessionsToast, "showToast");
jest.spyOn(BulkUnverifiedSessionsToast, "hideToast");
jest.spyOn(UnverifiedSessionToast, "showToast");
jest.spyOn(UnverifiedSessionToast, "hideToast");

beforeEach(() => {
jest.resetAllMocks();

// spy on various toasts' hide and show functions
// easier than mocking
jest.spyOn(SetupEncryptionToast, "showToast").mockReturnValue(undefined);
jest.spyOn(SetupEncryptionToast, "hideToast").mockReturnValue(undefined);
jest.spyOn(BulkUnverifiedSessionsToast, "showToast").mockReturnValue(undefined);
jest.spyOn(BulkUnverifiedSessionsToast, "hideToast").mockReturnValue(undefined);
jest.spyOn(UnverifiedSessionToast, "showToast").mockResolvedValue(undefined);
jest.spyOn(UnverifiedSessionToast, "hideToast").mockReturnValue(undefined);
Comment on lines +67 to +74
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we were previously relying on resetAllMocks to make these return undefined. It doesn't any longer, so we need to do it explicitly.


mockPlatformPeg({
getAppVersion: jest.fn().mockResolvedValue("1.2.3"),
});
Expand Down
2 changes: 2 additions & 0 deletions test/audio/VoiceRecording-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import Recorder from "opus-recorder/dist/recorder.min.js";
import { VoiceRecording, voiceRecorderOptions, highQualityRecorderOptions } from "../../src/audio/VoiceRecording";
import { createAudioContext } from "../..//src/audio/compat";
import MediaDeviceHandler from "../../src/MediaDeviceHandler";
import { useMockMediaDevices } from "../test-utils";

jest.mock("opus-recorder/dist/recorder.min.js");
const RecorderMock = mocked(Recorder);
Expand Down Expand Up @@ -56,6 +57,7 @@ describe("VoiceRecording", () => {
};

beforeEach(() => {
useMockMediaDevices();
recording = new VoiceRecording();
// @ts-ignore
recording.observable = {
Expand Down
2 changes: 1 addition & 1 deletion test/components/structures/MatrixChat-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ describe("<MatrixChat />", () => {
});

afterEach(() => {
jest.restoreAllMocks();
jest.clearAllMocks();
});

it("should render spinner while app is loading", () => {
Expand Down
5 changes: 4 additions & 1 deletion test/components/structures/PipContainer-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import {
mkRoomCreateEvent,
mockPlatformPeg,
flushPromises,
useMockMediaDevices,
} from "../../test-utils";
import { MatrixClientPeg } from "../../../src/MatrixClientPeg";
import { CallStore } from "../../../src/stores/CallStore";
Expand Down Expand Up @@ -84,6 +85,8 @@ describe("PipContainer", () => {
};

beforeEach(async () => {
useMockMediaDevices();

user = userEvent.setup();

stubClient();
Expand Down Expand Up @@ -133,7 +136,7 @@ describe("PipContainer", () => {
cleanup();
await Promise.all([CallStore.instance, WidgetMessagingStore.instance].map(resetAsyncStoreWithClient));
client.reEmitter.stopReEmitting(room, [RoomStateEvent.Events]);
jest.restoreAllMocks();
jest.clearAllMocks();
});

const renderPip = () => {
Expand Down
2 changes: 1 addition & 1 deletion test/components/structures/RoomView-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ describe("RoomView", () => {

afterEach(() => {
unmockPlatformPeg();
jest.restoreAllMocks();
jest.clearAllMocks();
});

const mountRoomView = async (ref?: RefObject<_RoomView>): Promise<RenderResult> => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,15 +50,17 @@ describe("<WidgetContextMenu />", () => {
avatar_url: undefined,
};

const mockClient = {
getUserId: jest.fn().mockReturnValue(userId),
} as unknown as MatrixClient;
let mockClient: MatrixClient;

let onFinished: () => void;

beforeEach(() => {
onFinished = jest.fn();
jest.spyOn(WidgetUtils, "canUserModifyWidgets").mockReturnValue(true);

mockClient = {
getUserId: jest.fn().mockReturnValue(userId),
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

restoreAllMocks now clears the mock return value, so move this in here to set it up before each test.

} as unknown as MatrixClient;
});

afterEach(() => {
Expand Down
8 changes: 5 additions & 3 deletions test/components/views/messages/CallEvent-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import {
setupAsyncStoreWithClient,
resetAsyncStoreWithClient,
wrapInMatrixClientContext,
useMockMediaDevices,
} from "../../../test-utils";
import defaultDispatcher from "../../../../src/dispatcher/dispatcher";
import { Action } from "../../../../src/dispatcher/actions";
Expand All @@ -41,9 +42,6 @@ import { ConnectionState } from "../../../../src/models/Call";
const CallEvent = wrapInMatrixClientContext(UnwrappedCallEvent);

describe("CallEvent", () => {
useMockedCalls();
jest.spyOn(HTMLMediaElement.prototype, "play").mockImplementation(async () => {});

let client: Mocked<MatrixClient>;
let room: Room;
let alice: RoomMember;
Expand All @@ -55,6 +53,10 @@ describe("CallEvent", () => {
jest.useFakeTimers();
jest.setSystemTime(0);

useMockMediaDevices();
useMockedCalls();
jest.spyOn(HTMLMediaElement.prototype, "play").mockImplementation(async () => {});
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

move these in here from the top of the describe block, so they are set up afresh after the restoreAllMocks in afterEach


stubClient();
client = mocked(MatrixClientPeg.safeGet());
client.getUserId.mockReturnValue("@alice:example.org");
Expand Down
14 changes: 9 additions & 5 deletions test/components/views/polls/pollHistory/PollHistory-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ limitations under the License.
*/

import React from "react";
import { fireEvent, render } from "@testing-library/react";
import { Filter, EventTimeline, Room } from "matrix-js-sdk/src/matrix";
import { act, fireEvent, render } from "@testing-library/react";
import { Filter, EventTimeline, Room, MatrixEvent } from "matrix-js-sdk/src/matrix";
import { M_POLL_START } from "matrix-js-sdk/src/@types/polls";

import { PollHistory } from "../../../../../src/components/views/polls/pollHistory/PollHistory";
Expand Down Expand Up @@ -194,7 +194,11 @@ describe("<PollHistory />", () => {
const fourtyDaysAgoTs = now - 60000 * 60 * 24 * 40;
const pollStart = makePollStartEvent("Question?", userId, undefined, { ts: fourtyDaysAgoTs, id: "1" });

jest.spyOn(liveTimeline, "getEvents").mockReset().mockReturnValueOnce([]).mockReturnValueOnce([pollStart]);
jest.spyOn(liveTimeline, "getEvents")
.mockReset()
.mockReturnValueOnce([])
.mockReturnValueOnce([pollStart])
.mockReturnValue(undefined as unknown as MatrixEvent[]);
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is necessary due to a change in the way mockReset works.

https://jestjs.io/docs/29.3/mock-function-api#mockfnmockreset says:

Resetting a mock created with jest.spyOn() will result in a function with no return value.

This no longer appears to be the case as of 29.6 and we now get the original implementation instead.

So, to preserve current behaviour, have it return undefined once we run out of mockReturnValueOnces.


// mock three pages of timeline history
jest.spyOn(liveTimeline, "getPaginationToken")
Expand All @@ -203,7 +207,7 @@ describe("<PollHistory />", () => {
.mockReturnValueOnce("test-pagination-token-3");

const { getByText } = getComponent();
await flushPromises();
await act(flushPromises);
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shoved some things in act while I was debugging this test.


expect(mockClient.paginateEventTimeline).toHaveBeenCalledTimes(1);

Expand All @@ -216,7 +220,7 @@ describe("<PollHistory />", () => {
// load more polls button still in UI, with loader
expect(getByText("Load more polls")).toMatchSnapshot();

await flushPromises();
await act(flushPromises);

// no more spinner
expect(getByText("Load more polls")).toMatchSnapshot();
Expand Down
5 changes: 5 additions & 0 deletions test/components/views/rooms/LegacyRoomHeader-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
import { CallType } from "matrix-js-sdk/src/webrtc/call";
import { ClientWidgetApi, Widget } from "matrix-widget-api";
import EventEmitter from "events";
import { setupJestCanvasMock } from "jest-canvas-mock";

import type { MatrixClient, MatrixEvent, RoomMember } from "matrix-js-sdk/src/matrix";
import type { MatrixCall } from "matrix-js-sdk/src/webrtc/call";
Expand Down Expand Up @@ -73,6 +74,10 @@ describe("LegacyRoomHeader", () => {
let carol: RoomMember;

beforeEach(async () => {
// some of our tests rely on the jest canvas mock, and `afterEach` will have reset the mock, so we need to
// restore it.
setupJestCanvasMock();

mockPlatformPeg({ supportsJitsiScreensharing: () => true });

stubClient();
Expand Down
4 changes: 3 additions & 1 deletion test/components/views/rooms/RoomTile-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import {
filterConsole,
flushPromises,
mkMessage,
useMockMediaDevices,
} from "../../../test-utils";
import { CallStore } from "../../../../src/stores/CallStore";
import RoomTile from "../../../../src/components/views/rooms/RoomTile";
Expand Down Expand Up @@ -134,6 +135,7 @@ describe("RoomTile", () => {
};

beforeEach(() => {
useMockMediaDevices();
sdkContext = new TestSdkContext();

client = mocked(stubClient());
Expand All @@ -152,7 +154,7 @@ describe("RoomTile", () => {
afterEach(() => {
// @ts-ignore
MessagePreviewStore.instance.previews = new Map<string, Map<TagID | TAG_ANY, MessagePreview | null>>();
jest.restoreAllMocks();
jest.clearAllMocks();
});

describe("when message previews are not enabled", () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,10 @@ const classes = {
};

describe("FormattingButtons", () => {
beforeEach(() => {
openLinkModalSpy.mockReturnValue(undefined);
});
Comment on lines +76 to +78
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we were previously relying on resetAllMocks to make this return undefined. It doesn't any longer, so we need to do it explicitly.


afterEach(() => {
jest.resetAllMocks();
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ describe("<SidebarUserSettingsTab />", () => {
beforeEach(() => {
jest.spyOn(PosthogTrackers, "trackInteraction").mockClear();
jest.spyOn(SettingsStore, "getValue").mockRestore();
jest.spyOn(SettingsStore, "setValue").mockReset();
jest.spyOn(SettingsStore, "setValue").mockResolvedValue(undefined);
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

another case of mockReset not working the same way on spyOn

});

it("renders sidebar settings", () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,12 @@ import SdkConfig from "../../../../src/SdkConfig";

jest.mock("../../../../src/components/structures/EmbeddedPage", () => ({
__esModule: true,
default: jest.fn().mockImplementation(({ url }) => <div>{url}</div>),
default: ({ url }: { url: string }) => <div>{url}</div>,
}));

jest.mock("../../../../src/components/structures/HomePage", () => ({
__esModule: true,
default: jest.fn().mockImplementation(() => <div>home page</div>),
default: () => <div>home page</div>,
Comment on lines -27 to +32
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

avoid these being reset by restoreAllMocks by using regular functions instead of mocks.

}));

describe("UserOnboardingPage", () => {
Expand Down
5 changes: 3 additions & 2 deletions test/components/views/voip/CallView-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import {
useMockedCalls,
MockedCall,
setupAsyncStoreWithClient,
useMockMediaDevices,
} from "../../../test-utils";
import { MatrixClientPeg } from "../../../../src/MatrixClientPeg";
import { CallView as _CallView } from "../../../../src/components/views/voip/CallView";
Expand All @@ -41,7 +42,7 @@ import MediaDeviceHandler from "../../../../src/MediaDeviceHandler";

const CallView = wrapInMatrixClientContext(_CallView);

describe("CallLobby", () => {
describe("CallView", () => {
useMockedCalls();
jest.spyOn(HTMLMediaElement.prototype, "play").mockImplementation(async () => {});

Expand All @@ -50,7 +51,7 @@ describe("CallLobby", () => {
let alice: RoomMember;

beforeEach(() => {
mocked(navigator.mediaDevices.enumerateDevices).mockResolvedValue([]);
useMockMediaDevices();

stubClient();
client = mocked(MatrixClientPeg.safeGet());
Expand Down
13 changes: 3 additions & 10 deletions test/setup/setupManualMocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@ class MyClipboardEvent extends Event {}
window.ClipboardEvent = MyClipboardEvent as any;

// matchMedia is not included in jsdom
const mockMatchMedia = jest.fn().mockImplementation((query) => ({
// TODO: Extract this to a function and have tests that need it opt into it.
const mockMatchMedia = (query: string) => ({
Comment on lines +59 to +60
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

avoid this being reset by restoreAllMocks by using a regular function instead of a mock.

matches: false,
media: query,
onchange: null,
Expand All @@ -65,7 +66,7 @@ const mockMatchMedia = jest.fn().mockImplementation((query) => ({
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
}));
});
global.matchMedia = mockMatchMedia;

// maplibre requires a createObjectURL mock
Expand All @@ -91,11 +92,3 @@ window.fetch = fetchMock.sandbox();

// @ts-ignore
window.Response = Response;

// set up mediaDevices mock
Object.defineProperty(navigator, "mediaDevices", {
value: {
enumerateDevices: jest.fn().mockResolvedValue([]),
getUserMedia: jest.fn(),
},
});
9 changes: 8 additions & 1 deletion test/stores/room-list/algorithms/Algorithm-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,13 @@ import { Widget } from "matrix-widget-api";

import type { MatrixClient } from "matrix-js-sdk/src/matrix";
import type { ClientWidgetApi } from "matrix-widget-api";
import { stubClient, setupAsyncStoreWithClient, useMockedCalls, MockedCall } from "../../../test-utils";
import {
stubClient,
setupAsyncStoreWithClient,
useMockedCalls,
MockedCall,
useMockMediaDevices,
} from "../../../test-utils";
import { MatrixClientPeg } from "../../../../src/MatrixClientPeg";
import DMRoomMap from "../../../../src/utils/DMRoomMap";
import { DefaultTagID } from "../../../../src/stores/room-list/models";
Expand All @@ -37,6 +43,7 @@ describe("Algorithm", () => {
let algorithm: Algorithm;

beforeEach(() => {
useMockMediaDevices();
stubClient();
client = mocked(MatrixClientPeg.safeGet());
DMRoomMap.makeShared(client);
Expand Down
9 changes: 9 additions & 0 deletions test/test-utils/utilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -225,3 +225,12 @@ export const clearAllModals = async (): Promise<void> => {
}
}
};

/** Install a stub object at `navigator.mediaDevices` */
export function useMockMediaDevices(): void {
// @ts-ignore
navigator["mediaDevices"] = {
enumerateDevices: jest.fn().mockResolvedValue([]),
getUserMedia: jest.fn(),
};
}
3 changes: 2 additions & 1 deletion test/utils/media/requestMediaPermissions-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import { logger } from "matrix-js-sdk/src/logger";
import { screen } from "@testing-library/react";

import { requestMediaPermissions } from "../../../src/utils/media/requestMediaPermissions";
import { flushPromises } from "../../test-utils";
import { flushPromises, useMockMediaDevices } from "../../test-utils";

describe("requestMediaPermissions", () => {
let error: Error;
Expand All @@ -34,6 +34,7 @@ describe("requestMediaPermissions", () => {
};

beforeEach(() => {
useMockMediaDevices();
error = new Error();
jest.spyOn(logger, "log");
});
Expand Down
Loading