Migrate batch of Jest tests to Vitest (#34714)

* Migrate batch of Jest tests to Vitest

* Iterate
This commit is contained in:
Michael Telatynski
2026-08-17 11:41:52 +00:00
committed by GitHub
parent e97358ba3e
commit b819fa58df
31 changed files with 335 additions and 251 deletions
@@ -6,11 +6,14 @@ SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Com
Please see LICENSE files in the repository root for full details. Please see LICENSE files in the repository root for full details.
*/ */
import React from "react"; // @vitest-environment happy-dom
import { render } from "jest-matrix-react";
import SdkConfig from "../../../../src/SdkConfig"; import React from "react";
import { ErrorView, UnsupportedBrowserView } from "../../../../src/async-components/structures/ErrorView"; import { describe, it, expect, beforeEach } from "vitest";
import { render } from "test-utils-rtl";
import SdkConfig from "../../SdkConfig";
import { ErrorView, UnsupportedBrowserView } from "./ErrorView";
describe("<ErrorView />", () => { describe("<ErrorView />", () => {
it("should match snapshot", () => { it("should match snapshot", () => {
@@ -1,6 +1,6 @@
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing // Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`<ErrorView /> should match snapshot 1`] = ` exports[`<ErrorView /> > should match snapshot 1`] = `
<DocumentFragment> <DocumentFragment>
<div <div
class="mx_ErrorView cpd-theme-light" class="mx_ErrorView cpd-theme-light"
@@ -34,7 +34,7 @@ exports[`<ErrorView /> should match snapshot 1`] = `
</DocumentFragment> </DocumentFragment>
`; `;
exports[`<UnsupportedBrowserView /> should match snapshot 1`] = ` exports[`<UnsupportedBrowserView /> > should match snapshot 1`] = `
<DocumentFragment> <DocumentFragment>
<div <div
class="mx_ErrorView cpd-theme-light" class="mx_ErrorView cpd-theme-light"
@@ -5,32 +5,35 @@
* 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 React from "react"; import React from "react";
import { type MatrixClient } from "matrix-js-sdk/src/matrix"; import { type MatrixClient } from "matrix-js-sdk/src/matrix";
import { render, screen, act } from "jest-matrix-react"; import { vi, describe, test, beforeEach, afterEach, expect } from "vitest";
import { render, screen, act } from "test-utils-rtl";
import { waitFor } from "@testing-library/dom"; import { waitFor } from "@testing-library/dom";
import userEvent from "@testing-library/user-event"; import userEvent from "@testing-library/user-event";
import { createTestClient } from "test-utils";
import NewRecoveryMethodDialog from "../../../../../src/async-components/views/dialogs/security/NewRecoveryMethodDialog"; import NewRecoveryMethodDialog from "./NewRecoveryMethodDialog";
import { createTestClient } from "../../../../test-utils"; import MatrixClientContext from "../../../../contexts/MatrixClientContext.tsx";
import MatrixClientContext from "../../../../../src/contexts/MatrixClientContext.tsx"; import dis from "../../../../dispatcher/dispatcher.ts";
import dis from "../../../../../src/dispatcher/dispatcher.ts"; import { Action } from "../../../../dispatcher/actions.ts";
import { Action } from "../../../../../src/dispatcher/actions.ts"; import Modal from "../../../../Modal.tsx";
import Modal from "../../../../../src/Modal.tsx";
describe("<NewRecoveryMethodDialog />", () => { describe("<NewRecoveryMethodDialog />", () => {
let matrixClient: MatrixClient; let matrixClient: MatrixClient;
beforeEach(() => { beforeEach(() => {
matrixClient = createTestClient(); matrixClient = createTestClient();
jest.spyOn(dis, "fire"); vi.spyOn(dis, "fire");
jest.spyOn(Modal, "createDialog"); vi.spyOn(Modal, "createDialog");
}); });
afterEach(() => { afterEach(() => {
jest.restoreAllMocks(); vi.restoreAllMocks();
}); });
function renderComponent(onFinished: () => void = jest.fn()) { function renderComponent(onFinished: () => void = vi.fn()) {
return render( return render(
<MatrixClientContext.Provider value={matrixClient}> <MatrixClientContext.Provider value={matrixClient}>
<NewRecoveryMethodDialog onFinished={onFinished} /> <NewRecoveryMethodDialog onFinished={onFinished} />
@@ -39,7 +42,7 @@ describe("<NewRecoveryMethodDialog />", () => {
} }
test("when cancel is clicked", async () => { test("when cancel is clicked", async () => {
const onFinished = jest.fn(); const onFinished = vi.fn();
act(() => { act(() => {
renderComponent(onFinished); renderComponent(onFinished);
}); });
@@ -50,9 +53,9 @@ describe("<NewRecoveryMethodDialog />", () => {
}); });
test("when key backup is enabled", async () => { test("when key backup is enabled", async () => {
jest.spyOn(matrixClient.getCrypto()!, "getActiveSessionBackupVersion").mockResolvedValue("version"); vi.spyOn(matrixClient.getCrypto()!, "getActiveSessionBackupVersion").mockResolvedValue("version");
const onFinished = jest.fn(); const onFinished = vi.fn();
const { asFragment } = renderComponent(onFinished); const { asFragment } = renderComponent(onFinished);
await waitFor(() => await waitFor(() =>
@@ -67,7 +70,7 @@ describe("<NewRecoveryMethodDialog />", () => {
}); });
test("when key backup is disabled", async () => { test("when key backup is disabled", async () => {
const onFinished = jest.fn(); const onFinished = vi.fn();
const { asFragment } = renderComponent(onFinished); const { asFragment } = renderComponent(onFinished);
expect(asFragment()).toMatchSnapshot(); expect(asFragment()).toMatchSnapshot();
@@ -5,22 +5,25 @@
* Please see LICENSE files in the repository root for full details. * Please see LICENSE files in the repository root for full details.
*/ */
import React from "react"; // @vitest-environment happy-dom
import { render, screen, fireEvent, waitFor } from "jest-matrix-react";
import RecoveryMethodRemovedDialog from "../../../../../src/async-components/views/dialogs/security/RecoveryMethodRemovedDialog"; import React from "react";
import dispatch from "../../../../../src/dispatcher/dispatcher"; import { vi, describe, it, afterEach, expect } from "vitest";
import { Action } from "../../../../../src/dispatcher/actions"; import { render, screen, fireEvent, waitFor } from "test-utils-rtl";
import { UserTab } from "../../../../../src/components/views/dialogs/UserTab";
import RecoveryMethodRemovedDialog from "./RecoveryMethodRemovedDialog";
import dispatch from "../../../../dispatcher/dispatcher";
import { Action } from "../../../../dispatcher/actions";
import { UserTab } from "../../../../components/views/dialogs/UserTab";
describe("<RecoveryMethodRemovedDialog />", () => { describe("<RecoveryMethodRemovedDialog />", () => {
afterEach(() => { afterEach(() => {
jest.restoreAllMocks(); vi.restoreAllMocks();
}); });
it("should open CreateKeyBackupDialog on primary action click", async () => { it("should open CreateKeyBackupDialog on primary action click", async () => {
const onFinished = jest.fn(); const onFinished = vi.fn();
jest.spyOn(dispatch, "dispatch"); vi.spyOn(dispatch, "dispatch");
render(<RecoveryMethodRemovedDialog onFinished={onFinished} />); render(<RecoveryMethodRemovedDialog onFinished={onFinished} />);
fireEvent.click(screen.getByRole("button", { name: "Set up Secure Messages" })); fireEvent.click(screen.getByRole("button", { name: "Set up Secure Messages" }));
@@ -1,6 +1,6 @@
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing // Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`<NewRecoveryMethodDialog /> when key backup is disabled 1`] = ` exports[`<NewRecoveryMethodDialog /> > when key backup is disabled 1`] = `
<DocumentFragment> <DocumentFragment>
<div <div
data-focus-guard="true" data-focus-guard="true"
@@ -70,6 +70,7 @@ exports[`<NewRecoveryMethodDialog /> when key backup is disabled 1`] = `
</span> </span>
</div> </div>
<div <div
aria-describedby="react-use-id-1"
aria-label="Close dialog" aria-label="Close dialog"
class="mx_AccessibleButton mx_Dialog_cancelButton" class="mx_AccessibleButton mx_Dialog_cancelButton"
role="button" role="button"
@@ -96,7 +97,7 @@ exports[`<NewRecoveryMethodDialog /> when key backup is disabled 1`] = `
</DocumentFragment> </DocumentFragment>
`; `;
exports[`<NewRecoveryMethodDialog /> when key backup is enabled 1`] = ` exports[`<NewRecoveryMethodDialog /> > when key backup is enabled 1`] = `
<DocumentFragment> <DocumentFragment>
<div <div
data-focus-guard="true" data-focus-guard="true"
@@ -169,6 +170,7 @@ exports[`<NewRecoveryMethodDialog /> when key backup is enabled 1`] = `
</span> </span>
</div> </div>
<div <div
aria-describedby="react-use-id-1"
aria-label="Close dialog" aria-label="Close dialog"
class="mx_AccessibleButton mx_Dialog_cancelButton" class="mx_AccessibleButton mx_Dialog_cancelButton"
role="button" role="button"
@@ -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 MatrixClient, type MatrixEvent } from "matrix-js-sdk/src/matrix"; // @vitest-environment happy-dom
import { mocked } from "jest-mock";
import { IntegrationManagers } from "../../../src/integrations/IntegrationManagers"; import { type MatrixClient, type MatrixEvent } from "matrix-js-sdk/src/matrix";
import { stubClient } from "../../test-utils"; import { vi, describe, it, expect, beforeEach, afterEach } from "vitest";
import { stubClient } from "test-utils";
import { IntegrationManagers } from "./IntegrationManagers";
describe("IntegrationManagers", () => { describe("IntegrationManagers", () => {
let client: MatrixClient; let client: MatrixClient;
@@ -18,8 +20,8 @@ describe("IntegrationManagers", () => {
beforeEach(() => { beforeEach(() => {
client = stubClient(); client = stubClient();
mocked(client).getAccountData.mockReturnValue({ vi.mocked(client).getAccountData.mockReturnValue({
getContent: jest.fn().mockReturnValue({ getContent: vi.fn().mockReturnValue({
foo: { foo: {
id: "foo", id: "foo",
content: { content: {
@@ -6,14 +6,14 @@
*/ */
import { Room, type MatrixClient } from "matrix-js-sdk/src/matrix"; import { Room, type MatrixClient } from "matrix-js-sdk/src/matrix";
import { mocked } from "jest-mock"; import { vi } from "vitest";
import { stubClient } from "test-utils";
import { type Command } from "../../../src/slash-commands/command"; import { type Command } from "../command";
import { getCommand } from "../../../src/slash-commands/SlashCommands"; import { getCommand } from "../SlashCommands";
import { stubClient } from "../../test-utils"; import { SDKContextClass } from "../../contexts/SDKContextClass";
import { SDKContextClass } from "../../../src/contexts/SDKContextClass"; import { LocalRoom } from "../../models/LocalRoom";
import { LocalRoom } from "../../../src/models/LocalRoom"; import DMRoomMap from "../../utils/DMRoomMap";
import DMRoomMap from "../../../src/utils/DMRoomMap.ts";
export function setUpCommandTest( export function setUpCommandTest(
roomId: string, roomId: string,
@@ -25,7 +25,7 @@ export function setUpCommandTest(
client: MatrixClient; client: MatrixClient;
room: Room; room: Room;
} { } {
jest.clearAllMocks(); vi.clearAllMocks();
// TODO: if getCommand took a MatrixClient argument, we could use // TODO: if getCommand took a MatrixClient argument, we could use
// createTestClient here instead of stubClient (i.e. avoid setting // createTestClient here instead of stubClient (i.e. avoid setting
@@ -42,9 +42,9 @@ export function setUpCommandTest(
room = new Room(roomId, client, client.getSafeUserId()); room = new Room(roomId, client, client.getSafeUserId());
} }
jest.spyOn(SDKContextClass.instance.roomViewStore, "getRoomId").mockReturnValue(roomId); vi.spyOn(SDKContextClass.instance.roomViewStore, "getRoomId").mockReturnValue(roomId);
mocked(client.getRoom).mockImplementation((rId: string): Room | null => { vi.mocked(client.getRoom).mockImplementation((rId: string | undefined): Room | null => {
if (rId === roomId) { if (rId === roomId) {
return room; return room;
} else { } else {
@@ -1,55 +1,55 @@
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing // Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`/lenny should match snapshot with args 1`] = ` exports[`/lenny > should match snapshot with args 1`] = `
{ {
"body": "( ͡° ͜ʖ ͡°) this is a test message", "body": "( ͡° ͜ʖ ͡°) this is a test message",
"msgtype": "m.text", "msgtype": "m.text",
} }
`; `;
exports[`/lenny should match snapshot with no args 1`] = ` exports[`/lenny > should match snapshot with no args 1`] = `
{ {
"body": "( ͡° ͜ʖ ͡°)", "body": "( ͡° ͜ʖ ͡°)",
"msgtype": "m.text", "msgtype": "m.text",
} }
`; `;
exports[`/shrug should match snapshot with args 1`] = ` exports[`/shrug > should match snapshot with args 1`] = `
{ {
"body": "¯\\_(ツ)_/¯ this is a test message", "body": "¯\\_(ツ)_/¯ this is a test message",
"msgtype": "m.text", "msgtype": "m.text",
} }
`; `;
exports[`/shrug should match snapshot with no args 1`] = ` exports[`/shrug > should match snapshot with no args 1`] = `
{ {
"body": "¯\\_(ツ)_/¯", "body": "¯\\_(ツ)_/¯",
"msgtype": "m.text", "msgtype": "m.text",
} }
`; `;
exports[`/tableflip should match snapshot with args 1`] = ` exports[`/tableflip > should match snapshot with args 1`] = `
{ {
"body": "(╯°□°)╯︵ ┻━┻ this is a test message", "body": "(╯°□°)╯︵ ┻━┻ this is a test message",
"msgtype": "m.text", "msgtype": "m.text",
} }
`; `;
exports[`/tableflip should match snapshot with no args 1`] = ` exports[`/tableflip > should match snapshot with no args 1`] = `
{ {
"body": "(╯°□°)╯︵ ┻━┻", "body": "(╯°□°)╯︵ ┻━┻",
"msgtype": "m.text", "msgtype": "m.text",
} }
`; `;
exports[`/unflip should match snapshot with args 1`] = ` exports[`/unflip > should match snapshot with args 1`] = `
{ {
"body": "┬──┬ ノ( ゜-゜ノ) this is a test message", "body": "┬──┬ ノ( ゜-゜ノ) this is a test message",
"msgtype": "m.text", "msgtype": "m.text",
} }
`; `;
exports[`/unflip should match snapshot with no args 1`] = ` exports[`/unflip > should match snapshot with no args 1`] = `
{ {
"body": "┬──┬ ノ( ゜-゜ノ)", "body": "┬──┬ ノ( ゜-゜ノ)",
"msgtype": "m.text", "msgtype": "m.text",
@@ -1,6 +1,6 @@
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing // Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`/rainbow should make things rainbowy 1`] = ` exports[`/rainbow > should make things rainbowy 1`] = `
{ {
"body": "this is a test message", "body": "this is a test message",
"format": "org.matrix.custom.html", "format": "org.matrix.custom.html",
@@ -9,7 +9,7 @@ exports[`/rainbow should make things rainbowy 1`] = `
} }
`; `;
exports[`/rainbowme should make things rainbowy 1`] = ` exports[`/rainbowme > should make things rainbowy 1`] = `
{ {
"body": "this is a test message", "body": "this is a test message",
"format": "org.matrix.custom.html", "format": "org.matrix.custom.html",
@@ -7,18 +7,25 @@
* Please see LICENSE files in the repository root for full details. * Please see LICENSE files in the repository root for full details.
*/ */
import { waitFor } from "jest-matrix-react"; // @vitest-environment happy-dom
// @vitest-environment-options {"settings": {"navigation": {"disableChildFrameNavigation": true }}}
import WidgetUtils from "../../../src/utils/WidgetUtils"; import { describe, it, expect, vi } from "vitest";
import { setUpCommandTest } from "./utils"; import { waitFor } from "test-utils-rtl";
import { WidgetType } from "../../../src/widgets/WidgetType";
import WidgetUtils from "../utils/WidgetUtils";
import { setUpCommandTest } from "./__mocks__";
import { WidgetType } from "../widgets/WidgetType";
describe("/addwidget", () => { describe("/addwidget", () => {
const roomId = "!room:example.com"; const roomId = "!room:example.com";
it("should parse html iframe snippets", async () => { it("should parse html iframe snippets", async () => {
jest.spyOn(WidgetUtils, "canUserModifyWidgets").mockReturnValue(true); vi.spyOn(WidgetUtils, "canUserModifyWidgets").mockReturnValue(true);
const spy = jest.spyOn(WidgetUtils, "setRoomWidget"); // This only asserts the call args below -- block the real implementation so it doesn't
// actually try to set up the widget (which, for a real URL like "https://element.io", ends
// up making a genuine outbound network request under happy-dom).
const spy = vi.spyOn(WidgetUtils, "setRoomWidget").mockResolvedValue(undefined);
const { client, command } = setUpCommandTest(roomId, `/addwidget`); const { client, command } = setUpCommandTest(roomId, `/addwidget`);
@@ -5,7 +5,11 @@
* Please see LICENSE files in the repository root for full details. * Please see LICENSE files in the repository root for full details.
*/ */
import { setUpCommandTest } from "./utils"; // @vitest-environment happy-dom
import { describe, it, expect } from "vitest";
import { setUpCommandTest } from "./__mocks__";
describe("/ban", () => { describe("/ban", () => {
const roomId = "!room:example.com"; const roomId = "!room:example.com";
@@ -7,7 +7,11 @@
* Please see LICENSE files in the repository root for full details. * Please see LICENSE files in the repository root for full details.
*/ */
import { setUpCommandTest } from "./utils"; // @vitest-environment happy-dom
import { describe, it, expect } from "vitest";
import { setUpCommandTest } from "./__mocks__";
describe("SlashCommands", () => { describe("SlashCommands", () => {
const roomId = "!room:example.com"; const roomId = "!room:example.com";
@@ -7,7 +7,11 @@
* Please see LICENSE files in the repository root for full details. * Please see LICENSE files in the repository root for full details.
*/ */
import { setUpCommandTest } from "./utils"; // @vitest-environment happy-dom
import { describe, it, expect } from "vitest";
import { setUpCommandTest } from "./__mocks__";
describe.each(["shrug", "tableflip", "unflip", "lenny"])("/%s", (commandName: string) => { describe.each(["shrug", "tableflip", "unflip", "lenny"])("/%s", (commandName: string) => {
const roomId = "!room:example.com"; const roomId = "!room:example.com";
@@ -5,8 +5,12 @@
* Please see LICENSE files in the repository root for full details. * Please see LICENSE files in the repository root for full details.
*/ */
import Modal, { type ComponentType, type IHandle } from "../../../src/Modal"; // @vitest-environment happy-dom
import { setUpCommandTest } from "./utils";
import { describe, it, expect, vi } from "vitest";
import Modal, { type ComponentType, type IHandle } from "../Modal";
import { setUpCommandTest } from "./__mocks__";
describe("/invite", () => { describe("/invite", () => {
const roomId = "!room:example.com"; const roomId = "!room:example.com";
@@ -17,7 +21,7 @@ describe("/invite", () => {
}); });
it("should invite the user we specify to this room", async () => { it("should invite the user we specify to this room", async () => {
const spy = jest.spyOn(Modal, "createDialog"); const spy = vi.spyOn(Modal, "createDialog");
spy.mockReturnValue({ close: () => {} } as unknown as IHandle<ComponentType>); spy.mockReturnValue({ close: () => {} } as unknown as IHandle<ComponentType>);
const { client, command, args } = setUpCommandTest(roomId, `/invite @u:s.co`); const { client, command, args } = setUpCommandTest(roomId, `/invite @u:s.co`);
@@ -28,7 +32,7 @@ describe("/invite", () => {
}); });
it("should provide the invite reason if we supply it", async () => { it("should provide the invite reason if we supply it", async () => {
const spy = jest.spyOn(Modal, "createDialog"); const spy = vi.spyOn(Modal, "createDialog");
spy.mockReturnValue({ close: () => {} } as unknown as IHandle<ComponentType>); spy.mockReturnValue({ close: () => {} } as unknown as IHandle<ComponentType>);
const { client, command, args } = setUpCommandTest(roomId, `/invite @u:s.co They are a very nice person`); const { client, command, args } = setUpCommandTest(roomId, `/invite @u:s.co They are a very nice person`);
@@ -7,8 +7,12 @@
* Please see LICENSE files in the repository root for full details. * Please see LICENSE files in the repository root for full details.
*/ */
import { setUpCommandTest } from "./utils"; // @vitest-environment happy-dom
import dispatcher from "../../../src/dispatcher/dispatcher";
import { describe, it, expect, vi } from "vitest";
import { setUpCommandTest } from "./__mocks__";
import dispatcher from "../dispatcher/dispatcher";
describe("/join", () => { describe("/join", () => {
const roomId = "!room:example.com"; const roomId = "!room:example.com";
@@ -20,7 +24,7 @@ describe("/join", () => {
it("should handle matrix.org permalinks", async () => { it("should handle matrix.org permalinks", async () => {
const { client, command } = setUpCommandTest(roomId, `/join`); const { client, command } = setUpCommandTest(roomId, `/join`);
jest.spyOn(dispatcher, "dispatch"); vi.spyOn(dispatcher, "dispatch");
await command.run(client, roomId, null, "https://matrix.to/#/!roomId:server/$eventId").promise; await command.run(client, roomId, null, "https://matrix.to/#/!roomId:server/$eventId").promise;
@@ -36,7 +40,7 @@ describe("/join", () => {
it("should handle room aliases", async () => { it("should handle room aliases", async () => {
const { client, command } = setUpCommandTest(roomId, `/join`); const { client, command } = setUpCommandTest(roomId, `/join`);
jest.spyOn(dispatcher, "dispatch"); vi.spyOn(dispatcher, "dispatch");
await command.run(client, roomId, null, "#test:server").promise; await command.run(client, roomId, null, "#test:server").promise;
@@ -50,7 +54,7 @@ describe("/join", () => {
it("should handle room aliases with no server component", async () => { it("should handle room aliases with no server component", async () => {
const { client, command } = setUpCommandTest(roomId, `/join`); const { client, command } = setUpCommandTest(roomId, `/join`);
jest.spyOn(dispatcher, "dispatch"); vi.spyOn(dispatcher, "dispatch");
await command.run(client, roomId, null, "#test").promise; await command.run(client, roomId, null, "#test").promise;
@@ -64,7 +68,7 @@ describe("/join", () => {
it("should handle room IDs and via servers", async () => { it("should handle room IDs and via servers", async () => {
const { client, command } = setUpCommandTest(roomId, `/join`); const { client, command } = setUpCommandTest(roomId, `/join`);
jest.spyOn(dispatcher, "dispatch"); vi.spyOn(dispatcher, "dispatch");
await command.run(client, roomId, null, "!foo:bar serv1.com serv2.com").promise; await command.run(client, roomId, null, "!foo:bar serv1.com serv2.com").promise;
@@ -5,9 +5,13 @@
* Please see LICENSE files in the repository root for full details. * Please see LICENSE files in the repository root for full details.
*/ */
import { setUpCommandTest } from "./utils"; // @vitest-environment happy-dom
import dispatcher from "../../../src/dispatcher/dispatcher";
import DMRoomMap from "../../../src/utils/DMRoomMap"; import { describe, it, expect, vi } from "vitest";
import { setUpCommandTest } from "./__mocks__";
import dispatcher from "../dispatcher/dispatcher";
import DMRoomMap from "../utils/DMRoomMap";
describe("/msg", () => { describe("/msg", () => {
const roomId = "!room:example.com"; const roomId = "!room:example.com";
@@ -19,12 +23,13 @@ describe("/msg", () => {
it("should message the user and switch to the relevant DM", async () => { it("should message the user and switch to the relevant DM", async () => {
// Given there is no DM room with the user // Given there is no DM room with the user
jest.spyOn(DMRoomMap, "shared").mockReturnValue({ vi.spyOn(DMRoomMap, "shared").mockReturnValue({
getDMRoomsForUserId: jest.fn().mockReturnValue([]), getDMRoomsForUserId: vi.fn().mockReturnValue([]),
getRoomIds: jest.fn().mockReturnValue([roomId]), getRoomIds: vi.fn().mockReturnValue([roomId]),
getUserIdForRoomId: vi.fn().mockReturnValue(undefined),
} as unknown as DMRoomMap); } as unknown as DMRoomMap);
jest.spyOn(dispatcher, "dispatch"); vi.spyOn(dispatcher, "dispatch");
// When we send a message to that user // When we send a message to that user
const { client, command, args } = setUpCommandTest(roomId, `/msg @u:s.co Hello there`); const { client, command, args } = setUpCommandTest(roomId, `/msg @u:s.co Hello there`);
@@ -7,12 +7,15 @@
* 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 { KnownMembership, RoomMember } from "matrix-js-sdk/src/matrix"; import { KnownMembership, RoomMember } from "matrix-js-sdk/src/matrix";
import { describe, it, expect, vi } from "vitest";
import { setUpCommandTest } from "./utils"; import { setUpCommandTest } from "./__mocks__";
import { warnSelfDemote } from "../../../src/components/views/right_panel/UserInfo"; import { warnSelfDemote } from "../components/views/right_panel/UserInfo";
jest.mock("../../../src/components/views/right_panel/UserInfo"); vi.mock("../components/views/right_panel/UserInfo");
describe("/op", () => { describe("/op", () => {
const roomId = "!room:example.com"; const roomId = "!room:example.com";
@@ -5,7 +5,11 @@
* Please see LICENSE files in the repository root for full details. * Please see LICENSE files in the repository root for full details.
*/ */
import { parseCommandString } from "../../../src/slash-commands/SlashCommands"; // @vitest-environment happy-dom
import { describe, it, expect } from "vitest";
import { parseCommandString } from "./SlashCommands";
describe("parseCommandString", () => { describe("parseCommandString", () => {
it("should be able to split arguments at the first whitespace", () => { it("should be able to split arguments at the first whitespace", () => {
@@ -7,12 +7,14 @@
* Please see LICENSE files in the repository root for full details. * Please see LICENSE files in the repository root for full details.
*/ */
import { type MatrixClient, PendingEventOrdering, Room } from "matrix-js-sdk/src/matrix"; // @vitest-environment happy-dom
import { mocked } from "jest-mock";
import Modal, { type ComponentType, type IHandle } from "../../../src/Modal"; import { type MatrixClient, PendingEventOrdering, Room } from "matrix-js-sdk/src/matrix";
import { setUpCommandTest } from "./utils"; import { describe, it, expect, vi } from "vitest";
import { type Command } from "../../../src/slash-commands/command";
import Modal, { type ComponentType, type IHandle } from "../Modal";
import { setUpCommandTest } from "./__mocks__";
import { type Command } from "./command";
describe("/part", () => { describe("/part", () => {
const roomId = "!room:example.com"; const roomId = "!room:example.com";
@@ -24,7 +26,7 @@ describe("/part", () => {
room1: Room; room1: Room;
room2: Room; room2: Room;
} { } {
const spy = jest.spyOn(Modal, "createDialog"); const spy = vi.spyOn(Modal, "createDialog");
spy.mockReturnValue({ close: () => {} } as unknown as IHandle<ComponentType>); spy.mockReturnValue({ close: () => {} } as unknown as IHandle<ComponentType>);
const { client, command, args } = setUpCommandTest(roomId, "/part #foo:bar"); const { client, command, args } = setUpCommandTest(roomId, "/part #foo:bar");
@@ -36,7 +38,7 @@ describe("/part", () => {
const room2 = new Room("!other-room", client, client.getSafeUserId()); const room2 = new Room("!other-room", client, client.getSafeUserId());
mocked(client.getRoom).mockImplementation((rId: string): Room | null => { vi.mocked(client.getRoom).mockImplementation((rId: string | undefined): Room | null => {
if (rId === room1.roomId) { if (rId === room1.roomId) {
return room1; return room1;
} else if (rId === room2.roomId) { } else if (rId === room2.roomId) {
@@ -45,15 +47,15 @@ describe("/part", () => {
return null; return null;
} }
}); });
mocked(client.getRooms).mockReturnValue([room1, room2]); vi.mocked(client.getRooms).mockReturnValue([room1, room2]);
return { client, command, args, room1, room2 }; return { client, command, args, room1, room2 };
} }
it("should part room matching alias if found", async () => { it("should part room matching alias if found", async () => {
const { client, command, args, room1, room2 } = setUp(); const { client, command, args, room1, room2 } = setUp();
room1.getCanonicalAlias = jest.fn().mockReturnValue("#foo:bar"); room1.getCanonicalAlias = vi.fn().mockReturnValue("#foo:bar");
room2.getCanonicalAlias = jest.fn().mockReturnValue("#baz:bar"); room2.getCanonicalAlias = vi.fn().mockReturnValue("#baz:bar");
await command.run(client, room1.roomId, null, args).promise; await command.run(client, room1.roomId, null, args).promise;
@@ -62,8 +64,8 @@ describe("/part", () => {
it("should part room matching alt alias if found", async () => { it("should part room matching alt alias if found", async () => {
const { client, command, args, room1, room2 } = setUp(); const { client, command, args, room1, room2 } = setUp();
room1.getAltAliases = jest.fn().mockReturnValue(["#foo:bar"]); room1.getAltAliases = vi.fn().mockReturnValue(["#foo:bar"]);
room2.getAltAliases = jest.fn().mockReturnValue(["#baz:bar"]); room2.getAltAliases = vi.fn().mockReturnValue(["#baz:bar"]);
await command.run(client, room1.roomId, null, args).promise; await command.run(client, room1.roomId, null, args).promise;
@@ -7,7 +7,11 @@
* Please see LICENSE files in the repository root for full details. * Please see LICENSE files in the repository root for full details.
*/ */
import { setUpCommandTest } from "./utils"; // @vitest-environment happy-dom
import { describe, it, expect } from "vitest";
import { setUpCommandTest } from "./__mocks__";
describe.each(["rainbow", "rainbowme"])("/%s", (commandName: string) => { describe.each(["rainbow", "rainbowme"])("/%s", (commandName: string) => {
const roomId = "!room:example.com"; const roomId = "!room:example.com";
@@ -5,7 +5,11 @@
* Please see LICENSE files in the repository root for full details. * Please see LICENSE files in the repository root for full details.
*/ */
import { setUpCommandTest } from "./utils"; // @vitest-environment happy-dom
import { describe, it, expect } from "vitest";
import { setUpCommandTest } from "./__mocks__";
describe("/remove", () => { describe("/remove", () => {
const roomId = "!room:example.com"; const roomId = "!room:example.com";
@@ -7,8 +7,12 @@
* Please see LICENSE files in the repository root for full details. * Please see LICENSE files in the repository root for full details.
*/ */
import Modal from "../../../src/Modal"; // @vitest-environment happy-dom
import { setUpCommandTest } from "./utils";
import { describe, it, expect, vi } from "vitest";
import Modal from "../Modal";
import { setUpCommandTest } from "./__mocks__";
describe("/topic", () => { describe("/topic", () => {
const roomId = "!room:example.com"; const roomId = "!room:example.com";
@@ -23,7 +27,7 @@ describe("/topic", () => {
}); });
it("should show topic modal if no args passed", async () => { it("should show topic modal if no args passed", async () => {
const spy = jest.spyOn(Modal, "createDialog"); const spy = vi.spyOn(Modal, "createDialog");
const { client, command } = setUpCommandTest(roomId, "/topic"); const { client, command } = setUpCommandTest(roomId, "/topic");
await command.run(client, roomId, null).promise; await command.run(client, roomId, null).promise;
expect(spy).toHaveBeenCalled(); expect(spy).toHaveBeenCalled();
@@ -7,15 +7,16 @@
* Please see LICENSE files in the repository root for full details. * Please see LICENSE files in the repository root for full details.
*/ */
import { type MatrixClient } from "matrix-js-sdk/src/matrix"; // @vitest-environment happy-dom
import RoomUpgradeWarningDialog, { import { type MatrixClient } from "matrix-js-sdk/src/matrix";
type IFinishedOpts, import { describe, it, expect, vi } from "vitest";
} from "../../../src/components/views/dialogs/RoomUpgradeWarningDialog";
import { type Command } from "../../../src/slash-commands/SlashCommands"; import RoomUpgradeWarningDialog, { type IFinishedOpts } from "../components/views/dialogs/RoomUpgradeWarningDialog";
import { parseUpgradeRoomArgs } from "../../../src/slash-commands/upgraderoom/parseUpgradeRoomArgs"; import { type Command } from "./SlashCommands";
import Modal from "../../../src/Modal"; import { parseUpgradeRoomArgs } from "./upgraderoom/parseUpgradeRoomArgs";
import { setUpCommandTest } from "./utils"; import Modal from "../Modal";
import { setUpCommandTest } from "./__mocks__";
describe("/upgraderoom", () => { describe("/upgraderoom", () => {
const roomId = "!room:example.com"; const roomId = "!room:example.com";
@@ -33,16 +34,16 @@ describe("/upgraderoom", () => {
createDialog: unknown; createDialog: unknown;
upgradeRoom: unknown; upgradeRoom: unknown;
} { } {
jest.clearAllMocks(); vi.clearAllMocks();
const { command, client } = setUpCommandTest(roomId, "/upgraderoom"); const { command, client } = setUpCommandTest(roomId, "/upgraderoom");
const createDialog = jest.spyOn(Modal, "createDialog"); const createDialog = vi.spyOn(Modal, "createDialog");
const upgradeRoom = jest.fn().mockResolvedValue({ replacement_room: "!newroom" }); const upgradeRoom = vi.fn().mockResolvedValue({ replacement_room: "!newroom" });
const resp: IFinishedOpts = { continue: continueUpgrade, invite: false }; const resp: IFinishedOpts = { continue: continueUpgrade, invite: false };
createDialog.mockReturnValue({ createDialog.mockReturnValue({
finished: Promise.resolve([resp]), finished: Promise.resolve([resp]),
close: jest.fn(), close: vi.fn(),
}); });
client.upgradeRoom = upgradeRoom; client.upgradeRoom = upgradeRoom;
@@ -5,7 +5,11 @@
* Please see LICENSE files in the repository root for full details. * Please see LICENSE files in the repository root for full details.
*/ */
import { splitAtFirstSpace } from "../../../src/slash-commands/utils"; // @vitest-environment happy-dom
import { describe, it, expect } from "vitest";
import { splitAtFirstSpace } from "./utils";
describe("splitAtFirstSpace", () => { describe("splitAtFirstSpace", () => {
it("should be able to split arguments at the first whitespace", () => { it("should be able to split arguments at the first whitespace", () => {
@@ -7,12 +7,15 @@
* Please see LICENSE files in the repository root for full details. * Please see LICENSE files in the repository root for full details.
*/ */
import { act, waitFor } from "jest-matrix-react"; // @vitest-environment happy-dom
import Modal, { type ComponentType, type IHandle } from "../../../src/Modal"; import { describe, it, expect, vi } from "vitest";
import { setUpCommandTest } from "./utils"; import { act, waitFor } from "test-utils-rtl";
import QuestionDialog from "../../../src/components/views/dialogs/QuestionDialog";
import ErrorDialog from "../../../src/components/views/dialogs/ErrorDialog"; import Modal, { type ComponentType, type IHandle } from "../Modal";
import { setUpCommandTest } from "./__mocks__";
import QuestionDialog from "../components/views/dialogs/QuestionDialog";
import ErrorDialog from "../components/views/dialogs/ErrorDialog";
describe("/verify", () => { describe("/verify", () => {
const roomId = "!room:example.com"; const roomId = "!room:example.com";
@@ -24,7 +27,7 @@ describe("/verify", () => {
it("should attempt manual verification after confirmation", async () => { it("should attempt manual verification after confirmation", async () => {
// Given we say yes to prompt // Given we say yes to prompt
const spy = jest.spyOn(Modal, "createDialog"); const spy = vi.spyOn(Modal, "createDialog");
spy.mockReturnValue({ finished: Promise.resolve([true]) } as unknown as IHandle<ComponentType>); spy.mockReturnValue({ finished: Promise.resolve([true]) } as unknown as IHandle<ComponentType>);
// When we run the command // When we run the command
@@ -45,7 +48,7 @@ describe("/verify", () => {
it("should not do manual verification if cancelled", async () => { it("should not do manual verification if cancelled", async () => {
// Given we say no to prompt // Given we say no to prompt
const spy = jest.spyOn(Modal, "createDialog"); const spy = vi.spyOn(Modal, "createDialog");
spy.mockReturnValue({ finished: Promise.resolve([false]) } as unknown as IHandle<ComponentType>); spy.mockReturnValue({ finished: Promise.resolve([false]) } as unknown as IHandle<ComponentType>);
// When we run the command // When we run the command
@@ -6,9 +6,11 @@ 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 React from "react"; import React from "react";
import { render, screen, cleanup, fireEvent, waitFor } from "jest-matrix-react"; import { vi, describe, it, expect, beforeEach, afterEach, type Mocked } from "vitest";
import { mocked, type Mocked } from "jest-mock"; import { render, screen, cleanup, fireEvent, waitFor } from "test-utils-rtl";
import { import {
Room, Room,
RoomStateEvent, RoomStateEvent,
@@ -35,23 +37,19 @@ import {
resetAsyncStoreWithClient, resetAsyncStoreWithClient,
mkEvent, mkEvent,
clientAndSDKContextRenderOptions, clientAndSDKContextRenderOptions,
} from "../../test-utils"; TestSDKContext,
import defaultDispatcher from "../../../src/dispatcher/dispatcher"; } from "test-utils";
import { Action } from "../../../src/dispatcher/actions"; import defaultDispatcher from "../dispatcher/dispatcher";
import { MatrixClientPeg } from "../../../src/MatrixClientPeg"; import { Action } from "../dispatcher/actions";
import { CallStore } from "../../../src/stores/CallStore"; import { MatrixClientPeg } from "../MatrixClientPeg";
import { WidgetMessagingStore } from "../../../src/stores/widgets/WidgetMessagingStore"; import { CallStore } from "../stores/CallStore";
import DMRoomMap from "../../../src/utils/DMRoomMap"; import { WidgetMessagingStore } from "../stores/widgets/WidgetMessagingStore";
import ToastStore from "../../../src/stores/ToastStore"; import DMRoomMap from "../utils/DMRoomMap";
import { import ToastStore from "../stores/ToastStore";
getIncomingCallToastKey, import { getIncomingCallToastKey, getNotificationEventSendTs, IncomingCallToast } from "./IncomingCallToast";
getNotificationEventSendTs, import { AudioID } from "../LegacyCallHandler";
IncomingCallToast, import { CallEvent } from "../models/Call";
} from "../../../src/toasts/IncomingCallToast"; import { type WidgetMessaging } from "../stores/widgets/WidgetMessaging";
import { AudioID } from "../../../src/LegacyCallHandler";
import { CallEvent } from "../../../src/models/Call";
import { type WidgetMessaging } from "../../../src/stores/widgets/WidgetMessaging";
import { TestSDKContext } from "../TestSDKContext.ts";
function makeNotificationEvent(room: Room, content: IContent = {}): MatrixEvent { function makeNotificationEvent(room: Room, content: IContent = {}): MatrixEvent {
const ts = Date.now(); const ts = Date.now();
@@ -86,15 +84,15 @@ describe("IncomingCallToast", () => {
let call: MockedCall; let call: MockedCall;
let widget: Widget; let widget: Widget;
const dmRoomMap = { const dmRoomMap = {
getUserIdForRoomId: jest.fn(), getUserIdForRoomId: vi.fn(),
} as unknown as DMRoomMap; } as unknown as DMRoomMap;
const toastStore = { const toastStore = {
dismissToast: jest.fn(), dismissToast: vi.fn(),
} as unknown as Mocked<ToastStore>; } as unknown as Mocked<ToastStore>;
beforeEach(async () => { beforeEach(async () => {
stubClient(); stubClient();
client = mocked(MatrixClientPeg.safeGet()); client = vi.mocked(MatrixClientPeg.safeGet());
sdkContext = new TestSDKContext(); sdkContext = new TestSDKContext();
sdkContext._client = client; sdkContext._client = client;
@@ -126,8 +124,8 @@ describe("IncomingCallToast", () => {
stop: () => {}, stop: () => {},
} as unknown as WidgetMessaging); } as unknown as WidgetMessaging);
jest.spyOn(DMRoomMap, "shared").mockReturnValue(dmRoomMap); vi.spyOn(DMRoomMap, "shared").mockReturnValue(dmRoomMap);
jest.spyOn(ToastStore, "sharedInstance").mockReturnValue(toastStore); vi.spyOn(ToastStore, "sharedInstance").mockReturnValue(toastStore);
toastStore.dismissToast.mockReset(); toastStore.dismissToast.mockReset();
}); });
@@ -136,7 +134,7 @@ describe("IncomingCallToast", () => {
call.destroy(); call.destroy();
WidgetMessagingStore.instance.stopMessaging(widget, room.roomId); WidgetMessagingStore.instance.stopMessaging(widget, room.roomId);
await Promise.all([CallStore.instance, WidgetMessagingStore.instance].map(resetAsyncStoreWithClient)); await Promise.all([CallStore.instance, WidgetMessagingStore.instance].map(resetAsyncStoreWithClient));
jest.restoreAllMocks(); vi.restoreAllMocks();
}); });
const renderToast = (notificationEvent: MatrixEvent = makeNotificationEvent(room)): string => { const renderToast = (notificationEvent: MatrixEvent = makeNotificationEvent(room)): string => {
@@ -166,19 +164,19 @@ describe("IncomingCallToast", () => {
}); });
renderToast(notificationEvent); renderToast(notificationEvent);
screen.getByText("Group call started"); expect(screen.getByText("Group call started")).toBeVisible();
screen.getByLabelText(callType === "voice" ? "Voice call" : "Video call"); expect(screen.getByLabelText(callType === "voice" ? "Voice call" : "Video call")).toBeVisible();
screen.getByLabelText("@alice:example.org"); expect(screen.getByLabelText("@alice:example.org")).toBeVisible();
screen.getByLabelText("@bob:example.org"); expect(screen.getByLabelText("@bob:example.org")).toBeVisible();
screen.getByText("on the call"); expect(screen.getByText("on the call")).toBeVisible();
screen.getByRole("button", { name: "Join" }); expect(screen.getByRole("button", { name: "Join" })).toBeVisible();
screen.getByRole("button", { name: "Decline" }); expect(screen.getByRole("button", { name: "Decline" })).toBeVisible();
screen.getByRole("button", { name: "Expand" }); expect(screen.getByRole("button", { name: "Expand" })).toBeVisible();
}); });
it.each(["video", "voice"])("shows information for a DM %s call", (callType: string) => { it.each(["video", "voice"])("shows information for a DM %s call", (callType: string) => {
mocked(dmRoomMap.getUserIdForRoomId).mockImplementation((roomId) => vi.mocked(dmRoomMap.getUserIdForRoomId).mockImplementation((roomId) =>
roomId === room.roomId ? alice.userId : undefined, roomId === room.roomId ? alice.userId : undefined,
); );
try { try {
@@ -188,21 +186,23 @@ describe("IncomingCallToast", () => {
}); });
renderToast(notificationEvent); renderToast(notificationEvent);
screen.getByText(callType === "voice" ? "Incoming voice call" : "Incoming video call"); expect(
screen.getByLabelText(callType === "voice" ? "Voice call" : "Video call"); screen.getByText(callType === "voice" ? "Incoming voice call" : "Incoming video call"),
screen.getByLabelText("@alice:example.org"); ).toBeVisible();
expect(screen.getByLabelText(callType === "voice" ? "Voice call" : "Video call")).toBeVisible();
expect(screen.getByLabelText("@alice:example.org")).toBeVisible();
screen.getByRole("button", { name: "Join" }); expect(screen.getByRole("button", { name: "Join" })).toBeVisible();
screen.getByRole("button", { name: "Decline" }); expect(screen.getByRole("button", { name: "Decline" })).toBeVisible();
screen.getByRole("button", { name: "Expand" }); expect(screen.getByRole("button", { name: "Expand" })).toBeVisible();
} finally { } finally {
mocked(dmRoomMap.getUserIdForRoomId).mockReset(); vi.mocked(dmRoomMap.getUserIdForRoomId).mockReset();
} }
}); });
it("start ringing on ring notify event", () => { it("start ringing on ring notify event", () => {
const notificationEvent = makeNotificationEvent(room, { notification_type: "ring" }); const notificationEvent = makeNotificationEvent(room, { notification_type: "ring" });
const playMock = jest.spyOn(sdkContext.legacyCallHandler, "play"); const playMock = vi.spyOn(sdkContext.legacyCallHandler, "play");
render( render(
<IncomingCallToast notificationEvent={notificationEvent} toastKey="" />, <IncomingCallToast notificationEvent={notificationEvent} toastKey="" />,
clientAndSDKContextRenderOptions(client, sdkContext), clientAndSDKContextRenderOptions(client, sdkContext),
@@ -226,7 +226,7 @@ describe("IncomingCallToast", () => {
it("joins with video and closes the toast", async () => { it("joins with video and closes the toast", async () => {
const callId = renderToast(); const callId = renderToast();
const dispatcherSpy = jest.fn(); const dispatcherSpy = vi.fn();
const dispatcherRef = defaultDispatcher.register(dispatcherSpy); const dispatcherRef = defaultDispatcher.register(dispatcherSpy);
screen.getByRole("switch", { name: "Join with video", checked: true }); screen.getByRole("switch", { name: "Join with video", checked: true });
@@ -251,7 +251,7 @@ describe("IncomingCallToast", () => {
it("joins without video and closes the toast", async () => { it("joins without video and closes the toast", async () => {
const callId = renderToast(); const callId = renderToast();
const dispatcherSpy = jest.fn(); const dispatcherSpy = vi.fn();
const dispatcherRef = defaultDispatcher.register(dispatcherSpy); const dispatcherRef = defaultDispatcher.register(dispatcherSpy);
fireEvent.click(screen.getByRole("switch", {})); fireEvent.click(screen.getByRole("switch", {}));
@@ -277,7 +277,7 @@ describe("IncomingCallToast", () => {
it("Dismiss toast if user starts call and skips lobby when using shift key click", async () => { it("Dismiss toast if user starts call and skips lobby when using shift key click", async () => {
const callId = renderToast(); const callId = renderToast();
const dispatcherSpy = jest.fn(); const dispatcherSpy = vi.fn();
const dispatcherRef = defaultDispatcher.register(dispatcherSpy); const dispatcherRef = defaultDispatcher.register(dispatcherSpy);
fireEvent.click(screen.getByRole("button", { name: "Join" }), { shiftKey: true }); fireEvent.click(screen.getByRole("button", { name: "Join" }), { shiftKey: true });
@@ -300,7 +300,7 @@ describe("IncomingCallToast", () => {
it("Dismiss toast if user joins with a remote device", async () => { it("Dismiss toast if user joins with a remote device", async () => {
const callId = renderToast(); const callId = renderToast();
const dispatcherSpy = jest.fn(); const dispatcherSpy = vi.fn();
const dispatcherRef = defaultDispatcher.register(dispatcherSpy); const dispatcherRef = defaultDispatcher.register(dispatcherSpy);
call.emit( call.emit(
@@ -319,7 +319,7 @@ describe("IncomingCallToast", () => {
it("expands to show the call lobby", async () => { it("expands to show the call lobby", async () => {
const callId = renderToast(); const callId = renderToast();
const dispatcherSpy = jest.fn(); const dispatcherSpy = vi.fn();
const dispatcherRef = defaultDispatcher.register(dispatcherSpy); const dispatcherRef = defaultDispatcher.register(dispatcherSpy);
fireEvent.click(screen.getByRole("button", { name: "Expand" })); fireEvent.click(screen.getByRole("button", { name: "Expand" }));
@@ -5,33 +5,37 @@ 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 { render } from "jest-matrix-react";
// @vitest-environment happy-dom
import { vi, describe, it, expect, beforeEach } from "vitest";
import { render } from "test-utils-rtl";
import { LOCAL_NOTIFICATION_SETTINGS_PREFIX, MatrixEvent, Room } from "matrix-js-sdk/src/matrix"; import { LOCAL_NOTIFICATION_SETTINGS_PREFIX, MatrixEvent, Room } from "matrix-js-sdk/src/matrix";
import { MatrixCall } from "matrix-js-sdk/src/webrtc/call"; import { MatrixCall } from "matrix-js-sdk/src/webrtc/call";
import React from "react"; import React from "react";
import IncomingLegacyCallToast from "../../../src/toasts/IncomingLegacyCallToast"; import IncomingLegacyCallToast from "./IncomingLegacyCallToast";
import DMRoomMap from "../../../src/utils/DMRoomMap"; import DMRoomMap from "../utils/DMRoomMap";
import { import {
clientAndSDKContextRenderOptions, clientAndSDKContextRenderOptions,
getMockClientWithEventEmitter, getMockClientWithEventEmitter,
mockClientMethodsServer, mockClientMethodsServer,
mockClientMethodsUser, mockClientMethodsUser,
} from "../../test-utils"; TestSDKContext,
import { TestSDKContext } from "../TestSDKContext.ts"; } from "test-utils";
describe("<IncomingLegacyCallToast />", () => { describe("<IncomingLegacyCallToast />", () => {
const userId = "@alice:server.org"; const userId = "@alice:server.org";
const deviceId = "my-device"; const deviceId = "my-device";
jest.spyOn(DMRoomMap, "shared").mockReturnValue({ vi.spyOn(DMRoomMap, "shared").mockReturnValue({
getUserIdForRoomId: jest.fn(), getUserIdForRoomId: vi.fn(),
} as unknown as DMRoomMap); } as unknown as DMRoomMap);
const mockClient = getMockClientWithEventEmitter({ const mockClient = getMockClientWithEventEmitter({
...mockClientMethodsUser(userId), ...mockClientMethodsUser(userId),
...mockClientMethodsServer(), ...mockClientMethodsServer(),
getRoom: jest.fn(), getRoom: vi.fn(),
}); });
const sdkContext = new TestSDKContext(); const sdkContext = new TestSDKContext();
sdkContext._client = mockClient; sdkContext._client = mockClient;
@@ -45,7 +49,7 @@ describe("<IncomingLegacyCallToast />", () => {
const getComponent = (props = {}) => <IncomingLegacyCallToast {...defaultProps} {...props} />; const getComponent = (props = {}) => <IncomingLegacyCallToast {...defaultProps} {...props} />;
beforeEach(() => { beforeEach(() => {
jest.clearAllMocks(); vi.clearAllMocks();
mockClient.getAccountData.mockReturnValue(undefined); mockClient.getAccountData.mockReturnValue(undefined);
mockClient.getRoom.mockReturnValue(mockRoom); mockClient.getRoom.mockReturnValue(mockRoom);
}); });
@@ -6,33 +6,37 @@ 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 React from "react"; import React from "react";
import { act, render, screen } from "jest-matrix-react"; import { vi, describe, it, expect, beforeEach, type Mocked } from "vitest";
import { mocked, type Mocked } from "jest-mock"; import { act, render, screen } from "test-utils-rtl";
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 CryptoApi, DecryptionKeyDoesNotMatchError } from "matrix-js-sdk/src/crypto-api"; import { type CryptoApi, DecryptionKeyDoesNotMatchError } from "matrix-js-sdk/src/crypto-api";
import { type SecretStorageKeyDescriptionAesV1 } from "matrix-js-sdk/src/secret-storage"; import { type SecretStorageKeyDescriptionAesV1 } from "matrix-js-sdk/src/secret-storage";
import * as SecurityManager from "../../../src/SecurityManager"; import * as SecurityManager from "../SecurityManager";
import ToastContainer from "../../../src/components/structures/ToastContainer"; import ToastContainer from "../components/structures/ToastContainer";
import { showToast } from "../../../src/toasts/SetupEncryptionToast"; import { showToast } from "./SetupEncryptionToast";
import dis from "../../../src/dispatcher/dispatcher"; import dis from "../dispatcher/dispatcher";
import { DeviceListener } from "../../../src/device-listener"; import { DeviceListener } from "../device-listener";
import Modal from "../../../src/Modal"; import Modal from "../Modal";
import ConfirmKeyStorageOffDialog from "../../../src/components/views/dialogs/ConfirmKeyStorageOffDialog"; import ConfirmKeyStorageOffDialog from "../components/views/dialogs/ConfirmKeyStorageOffDialog";
import SetupEncryptionDialog from "../../../src/components/views/dialogs/security/SetupEncryptionDialog"; import SetupEncryptionDialog from "../components/views/dialogs/security/SetupEncryptionDialog";
import { stubClient } from "../../test-utils"; import { stubClient } from "test-utils";
jest.mock("../../../src/dispatcher/dispatcher", () => ({ vi.mock("../dispatcher/dispatcher", () => ({
dispatch: jest.fn(), default: {
register: jest.fn(), dispatch: vi.fn(),
unregister: jest.fn(), register: vi.fn(),
unregister: vi.fn(),
},
})); }));
describe("SetupEncryptionToast", () => { describe("SetupEncryptionToast", () => {
beforeEach(() => { beforeEach(() => {
jest.resetAllMocks(); vi.resetAllMocks();
render(<ToastContainer />); render(<ToastContainer />);
}); });
@@ -44,8 +48,8 @@ describe("SetupEncryptionToast", () => {
}); });
it("should dismiss the toast when 'Dismiss' button clicked, and remember it", async () => { it("should dismiss the toast when 'Dismiss' button clicked, and remember it", async () => {
jest.spyOn(DeviceListener.sharedInstance(), "recordRecoveryDisabled"); vi.spyOn(DeviceListener.sharedInstance(), "recordRecoveryDisabled");
jest.spyOn(DeviceListener.sharedInstance(), "dismissEncryptionSetup"); vi.spyOn(DeviceListener.sharedInstance(), "dismissEncryptionSetup");
act(() => showToast("set_up_recovery")); act(() => showToast("set_up_recovery"));
@@ -61,12 +65,12 @@ describe("SetupEncryptionToast", () => {
let client: Mocked<MatrixClient>; let client: Mocked<MatrixClient>;
beforeEach(() => { beforeEach(() => {
client = mocked(stubClient()); client = vi.mocked(stubClient());
mocked(client.getCrypto).mockReturnValue({ vi.mocked(client.getCrypto).mockReturnValue({
getSessionBackupPrivateKey: jest.fn().mockResolvedValue(null), getSessionBackupPrivateKey: vi.fn().mockResolvedValue(null),
resetKeyBackup: jest.fn(), resetKeyBackup: vi.fn(),
checkKeyBackupAndEnable: jest.fn(), checkKeyBackupAndEnable: vi.fn(),
loadSessionBackupPrivateKeyFromSecretStorage: jest.fn(), loadSessionBackupPrivateKeyFromSecretStorage: vi.fn(),
} as unknown as CryptoApi); } as unknown as CryptoApi);
}); });
@@ -79,13 +83,13 @@ describe("SetupEncryptionToast", () => {
it("should reset key backup if needed", async () => { it("should reset key backup if needed", async () => {
showToast("key_storage_out_of_sync"); showToast("key_storage_out_of_sync");
jest.spyOn(SecurityManager, "accessSecretStorage").mockImplementation( vi.spyOn(SecurityManager, "accessSecretStorage").mockImplementation(
async (func = async (): Promise<void> => {}) => { async (func = async (): Promise<void> => {}) => {
return await func(); return await func();
}, },
); );
jest.spyOn(DeviceListener.sharedInstance(), "keyStorageOutOfSyncNeedsBackupReset").mockResolvedValue(true); vi.spyOn(DeviceListener.sharedInstance(), "keyStorageOutOfSyncNeedsBackupReset").mockResolvedValue(true);
const user = userEvent.setup(); const user = userEvent.setup();
await user.click(await screen.findByText("Enter recovery key")); await user.click(await screen.findByText("Enter recovery key"));
@@ -96,13 +100,13 @@ describe("SetupEncryptionToast", () => {
it("should not reset key backup if not needed", async () => { it("should not reset key backup if not needed", async () => {
showToast("key_storage_out_of_sync"); showToast("key_storage_out_of_sync");
jest.spyOn(SecurityManager, "accessSecretStorage").mockImplementation( vi.spyOn(SecurityManager, "accessSecretStorage").mockImplementation(
async (func = async (): Promise<void> => {}) => { async (func = async (): Promise<void> => {}) => {
return await func(); return await func();
}, },
); );
jest.spyOn(DeviceListener.sharedInstance(), "keyStorageOutOfSyncNeedsBackupReset").mockResolvedValue(false); vi.spyOn(DeviceListener.sharedInstance(), "keyStorageOutOfSyncNeedsBackupReset").mockResolvedValue(false);
// if the backup key is stored in 4S // if the backup key is stored in 4S
client.isKeyBackupKeyStored.mockResolvedValue({}); client.isKeyBackupKeyStored.mockResolvedValue({});
@@ -120,16 +124,16 @@ describe("SetupEncryptionToast", () => {
const crypto = client.getCrypto()!; const crypto = client.getCrypto()!;
jest.spyOn(SecurityManager, "accessSecretStorage").mockImplementation( vi.spyOn(SecurityManager, "accessSecretStorage").mockImplementation(
async (func = async (): Promise<void> => {}) => func(), async (func = async (): Promise<void> => {}) => func(),
); );
// Given we throw when trying to load the backup decrption key // Given we throw when trying to load the backup decrption key
mocked(crypto.loadSessionBackupPrivateKeyFromSecretStorage).mockRejectedValue( vi.mocked(crypto.loadSessionBackupPrivateKeyFromSecretStorage).mockRejectedValue(
new DecryptionKeyDoesNotMatchError("it key no match"), new DecryptionKeyDoesNotMatchError("it key no match"),
); );
jest.spyOn(DeviceListener.sharedInstance(), "keyStorageOutOfSyncNeedsBackupReset").mockResolvedValue(false); vi.spyOn(DeviceListener.sharedInstance(), "keyStorageOutOfSyncNeedsBackupReset").mockResolvedValue(false);
client.isKeyBackupKeyStored.mockResolvedValue({}); client.isKeyBackupKeyStored.mockResolvedValue({});
// When we enter our recovery key // When we enter our recovery key
@@ -144,7 +148,7 @@ describe("SetupEncryptionToast", () => {
it("should open settings to the reset flow when 'forgot recovery key' clicked and identity reset needed", async () => { it("should open settings to the reset flow when 'forgot recovery key' clicked and identity reset needed", async () => {
act(() => showToast("key_storage_out_of_sync")); act(() => showToast("key_storage_out_of_sync"));
jest.spyOn(DeviceListener.sharedInstance(), "keyStorageOutOfSyncNeedsCrossSigningReset").mockResolvedValue( vi.spyOn(DeviceListener.sharedInstance(), "keyStorageOutOfSyncNeedsCrossSigningReset").mockResolvedValue(
true, true,
); );
@@ -161,7 +165,7 @@ describe("SetupEncryptionToast", () => {
it("should open settings to the change recovery key flow when 'forgot recovery key' clicked and identity reset not needed", async () => { it("should open settings to the change recovery key flow when 'forgot recovery key' clicked and identity reset not needed", async () => {
act(() => showToast("key_storage_out_of_sync")); act(() => showToast("key_storage_out_of_sync"));
jest.spyOn(DeviceListener.sharedInstance(), "keyStorageOutOfSyncNeedsCrossSigningReset").mockResolvedValue( vi.spyOn(DeviceListener.sharedInstance(), "keyStorageOutOfSyncNeedsCrossSigningReset").mockResolvedValue(
false, false,
); );
@@ -176,11 +180,11 @@ describe("SetupEncryptionToast", () => {
}); });
it("should open settings to the reset flow when recovering fails and identity reset needed", async () => { it("should open settings to the reset flow when recovering fails and identity reset needed", async () => {
jest.spyOn(SecurityManager, "accessSecretStorage").mockImplementation(async () => { vi.spyOn(SecurityManager, "accessSecretStorage").mockImplementation(async () => {
throw new Error("Something went wrong while recovering!"); throw new Error("Something went wrong while recovering!");
}); });
jest.spyOn(DeviceListener.sharedInstance(), "keyStorageOutOfSyncNeedsCrossSigningReset").mockResolvedValue( vi.spyOn(DeviceListener.sharedInstance(), "keyStorageOutOfSyncNeedsCrossSigningReset").mockResolvedValue(
true, true,
); );
@@ -197,11 +201,11 @@ describe("SetupEncryptionToast", () => {
}); });
it("should open settings to the change recovery key flow when recovering fails and identity reset not needed", async () => { it("should open settings to the change recovery key flow when recovering fails and identity reset not needed", async () => {
jest.spyOn(SecurityManager, "accessSecretStorage").mockImplementation(async () => { vi.spyOn(SecurityManager, "accessSecretStorage").mockImplementation(async () => {
throw new Error("Something went wrong while recovering!"); throw new Error("Something went wrong while recovering!");
}); });
jest.spyOn(DeviceListener.sharedInstance(), "keyStorageOutOfSyncNeedsCrossSigningReset").mockResolvedValue( vi.spyOn(DeviceListener.sharedInstance(), "keyStorageOutOfSyncNeedsCrossSigningReset").mockResolvedValue(
false, false,
); );
@@ -218,18 +222,18 @@ describe("SetupEncryptionToast", () => {
}); });
it("should go to change recovery key when recovering fails inside loadSessionBackup...", async () => { it("should go to change recovery key when recovering fails inside loadSessionBackup...", async () => {
jest.spyOn(SecurityManager, "accessSecretStorage").mockImplementation( vi.spyOn(SecurityManager, "accessSecretStorage").mockImplementation(
async (func = async (): Promise<void> => {}) => func(), async (func = async (): Promise<void> => {}) => func(),
); );
jest.spyOn(DeviceListener.sharedInstance(), "keyStorageOutOfSyncNeedsCrossSigningReset").mockResolvedValue( vi.spyOn(DeviceListener.sharedInstance(), "keyStorageOutOfSyncNeedsCrossSigningReset").mockResolvedValue(
true, true,
); );
jest.spyOn(DeviceListener.sharedInstance(), "keyStorageOutOfSyncNeedsBackupReset").mockResolvedValue(false); vi.spyOn(DeviceListener.sharedInstance(), "keyStorageOutOfSyncNeedsBackupReset").mockResolvedValue(false);
mocked(client.isKeyBackupKeyStored).mockResolvedValue(fakeKeyBackupKey()); vi.mocked(client.isKeyBackupKeyStored).mockResolvedValue(fakeKeyBackupKey());
// Given when we try to load from backup we get an unexpected error // Given when we try to load from backup we get an unexpected error
mocked(client.getCrypto()!.loadSessionBackupPrivateKeyFromSecretStorage).mockRejectedValue( vi.mocked(client.getCrypto()!.loadSessionBackupPrivateKeyFromSecretStorage).mockRejectedValue(
new Error("Unexpected error"), new Error("Unexpected error"),
); );
@@ -252,7 +256,7 @@ describe("SetupEncryptionToast", () => {
}); });
it("should dismiss the toast when the close button is clicked", async () => { it("should dismiss the toast when the close button is clicked", async () => {
jest.spyOn(DeviceListener.sharedInstance(), "dismissEncryptionSetup"); vi.spyOn(DeviceListener.sharedInstance(), "dismissEncryptionSetup");
act(() => showToast("key_storage_out_of_sync")); act(() => showToast("key_storage_out_of_sync"));
@@ -293,7 +297,7 @@ describe("SetupEncryptionToast", () => {
}); });
it("should open settings to the Encryption tab when 'Continue' clicked", async () => { it("should open settings to the Encryption tab when 'Continue' clicked", async () => {
jest.spyOn(DeviceListener.sharedInstance(), "recordKeyBackupDisabled"); vi.spyOn(DeviceListener.sharedInstance(), "recordKeyBackupDisabled");
act(() => showToast("turn_on_key_storage")); act(() => showToast("turn_on_key_storage"));
@@ -309,10 +313,10 @@ describe("SetupEncryptionToast", () => {
}); });
it("should open the confirm key storage off dialog when 'Dismiss' clicked", async () => { it("should open the confirm key storage off dialog when 'Dismiss' clicked", async () => {
jest.spyOn(DeviceListener.sharedInstance(), "recordKeyBackupDisabled"); vi.spyOn(DeviceListener.sharedInstance(), "recordKeyBackupDisabled");
// Given that as soon as the dialog opens, it closes and says "yes they clicked dismiss" // Given that as soon as the dialog opens, it closes and says "yes they clicked dismiss"
jest.spyOn(Modal, "createDialog").mockImplementation(() => { vi.spyOn(Modal, "createDialog").mockImplementation(() => {
return { finished: Promise.resolve([true]) } as any; return { finished: Promise.resolve([true]) } as any;
}); });
@@ -344,7 +348,7 @@ describe("SetupEncryptionToast", () => {
}); });
it("should dismiss the toast when 'Later' button clicked, and remember it", async () => { it("should dismiss the toast when 'Later' button clicked, and remember it", async () => {
jest.spyOn(DeviceListener.sharedInstance(), "dismissEncryptionSetup"); vi.spyOn(DeviceListener.sharedInstance(), "dismissEncryptionSetup");
act(() => showToast("verify_this_session")); act(() => showToast("verify_this_session"));
@@ -355,7 +359,7 @@ describe("SetupEncryptionToast", () => {
}); });
it("should open the verification dialog when 'Continue' clicked", async () => { it("should open the verification dialog when 'Continue' clicked", async () => {
jest.spyOn(Modal, "createDialog"); vi.spyOn(Modal, "createDialog");
// When we show the toast, and click Verify // When we show the toast, and click Verify
act(() => showToast("verify_this_session")); act(() => showToast("verify_this_session"));
@@ -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.
*/ */
// @vitest-environment happy-dom
import React from "react"; import React from "react";
import { render, type RenderResult, screen } from "jest-matrix-react"; import { vi, describe, it, expect, beforeAll, beforeEach, type Mocked } from "vitest";
import { render, type RenderResult, screen } from "test-utils-rtl";
import userEvent from "@testing-library/user-event"; import userEvent from "@testing-library/user-event";
import { mocked, type Mocked } from "jest-mock";
import { type IMyDevice, type MatrixClient } from "matrix-js-sdk/src/matrix"; import { type IMyDevice, type MatrixClient } from "matrix-js-sdk/src/matrix";
import { type CryptoApi, DeviceVerificationStatus } from "matrix-js-sdk/src/crypto-api"; import { type CryptoApi, DeviceVerificationStatus } from "matrix-js-sdk/src/crypto-api";
import dis from "../../../src/dispatcher/dispatcher"; import dis from "../dispatcher/dispatcher";
import { showToast } from "../../../src/toasts/UnverifiedSessionToast"; import { showToast } from "./UnverifiedSessionToast";
import { filterConsole, flushPromises, stubClient } from "../../test-utils"; import { filterConsole, flushPromises, stubClient } from "test-utils";
import ToastContainer from "../../../src/components/structures/ToastContainer"; import ToastContainer from "../components/structures/ToastContainer";
import { Action } from "../../../src/dispatcher/actions"; import { Action } from "../dispatcher/actions";
import { DeviceListener } from "../../../src/device-listener"; import { DeviceListener } from "../device-listener";
describe("UnverifiedSessionToast", () => { describe("UnverifiedSessionToast", () => {
const otherDevice: IMyDevice = { const otherDevice: IMyDevice = {
@@ -30,7 +32,7 @@ describe("UnverifiedSessionToast", () => {
filterConsole("Dismissing unverified sessions: ABC123"); filterConsole("Dismissing unverified sessions: ABC123");
beforeAll(() => { beforeAll(() => {
client = mocked(stubClient()); client = vi.mocked(stubClient());
client.getDevice.mockImplementation(async (deviceId: string) => { client.getDevice.mockImplementation(async (deviceId: string) => {
if (deviceId === otherDevice.device_id) { if (deviceId === otherDevice.device_id) {
return otherDevice; return otherDevice;
@@ -39,12 +41,12 @@ describe("UnverifiedSessionToast", () => {
throw new Error(`Unknown device ${deviceId}`); throw new Error(`Unknown device ${deviceId}`);
}); });
client.getCrypto.mockReturnValue({ client.getCrypto.mockReturnValue({
getDeviceVerificationStatus: jest getDeviceVerificationStatus: vi
.fn() .fn()
.mockResolvedValue(new DeviceVerificationStatus({ crossSigningVerified: true })), .mockResolvedValue(new DeviceVerificationStatus({ crossSigningVerified: true })),
} as unknown as CryptoApi); } as unknown as CryptoApi);
jest.spyOn(dis, "dispatch"); vi.spyOn(dis, "dispatch");
jest.spyOn(DeviceListener.sharedInstance(), "dismissUnverifiedSessions"); vi.spyOn(DeviceListener.sharedInstance(), "dismissUnverifiedSessions");
}); });
beforeEach(() => { beforeEach(() => {
@@ -1,6 +1,6 @@
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing // Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`<IncomingLegacyCallToast /> renders disabled silenced button when call is forced to silent 1`] = ` exports[`<IncomingLegacyCallToast /> > renders disabled silenced button when call is forced to silent 1`] = `
<div <div
aria-disabled="true" aria-disabled="true"
aria-label="Notifications silenced" aria-label="Notifications silenced"
@@ -23,7 +23,7 @@ exports[`<IncomingLegacyCallToast /> renders disabled silenced button when call
</div> </div>
`; `;
exports[`<IncomingLegacyCallToast /> renders sound on button when call is silenced 1`] = ` exports[`<IncomingLegacyCallToast /> > renders sound on button when call is silenced 1`] = `
<div <div
aria-label="Sound on" aria-label="Sound on"
class="mx_AccessibleButton mx_IncomingLegacyCallToast_iconButton" class="mx_AccessibleButton mx_IncomingLegacyCallToast_iconButton"
@@ -44,7 +44,7 @@ exports[`<IncomingLegacyCallToast /> renders sound on button when call is silenc
</div> </div>
`; `;
exports[`<IncomingLegacyCallToast /> renders when silence button when call is not silenced 1`] = ` exports[`<IncomingLegacyCallToast /> > renders when silence button when call is not silenced 1`] = `
<div <div
aria-label="Silence call" aria-label="Silence call"
class="mx_AccessibleButton mx_IncomingLegacyCallToast_iconButton" class="mx_AccessibleButton mx_IncomingLegacyCallToast_iconButton"
@@ -1,6 +1,6 @@
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing // Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`UnverifiedSessionToast when rendering the toast should render as expected 1`] = ` exports[`UnverifiedSessionToast > when rendering the toast > should render as expected 1`] = `
<body> <body>
<div> <div>
<div <div