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.
*/
import React from "react";
import { render } from "jest-matrix-react";
// @vitest-environment happy-dom
import SdkConfig from "../../../../src/SdkConfig";
import { ErrorView, UnsupportedBrowserView } from "../../../../src/async-components/structures/ErrorView";
import React from "react";
import { describe, it, expect, beforeEach } from "vitest";
import { render } from "test-utils-rtl";
import SdkConfig from "../../SdkConfig";
import { ErrorView, UnsupportedBrowserView } from "./ErrorView";
describe("<ErrorView />", () => {
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>
<div
class="mx_ErrorView cpd-theme-light"
@@ -34,7 +34,7 @@ exports[`<ErrorView /> should match snapshot 1`] = `
</DocumentFragment>
`;
exports[`<UnsupportedBrowserView /> should match snapshot 1`] = `
exports[`<UnsupportedBrowserView /> > should match snapshot 1`] = `
<DocumentFragment>
<div
class="mx_ErrorView cpd-theme-light"
@@ -5,32 +5,35 @@
* Please see LICENSE files in the repository root for full details.
*/
// @vitest-environment happy-dom
import React from "react";
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 userEvent from "@testing-library/user-event";
import { createTestClient } from "test-utils";
import NewRecoveryMethodDialog from "../../../../../src/async-components/views/dialogs/security/NewRecoveryMethodDialog";
import { createTestClient } from "../../../../test-utils";
import MatrixClientContext from "../../../../../src/contexts/MatrixClientContext.tsx";
import dis from "../../../../../src/dispatcher/dispatcher.ts";
import { Action } from "../../../../../src/dispatcher/actions.ts";
import Modal from "../../../../../src/Modal.tsx";
import NewRecoveryMethodDialog from "./NewRecoveryMethodDialog";
import MatrixClientContext from "../../../../contexts/MatrixClientContext.tsx";
import dis from "../../../../dispatcher/dispatcher.ts";
import { Action } from "../../../../dispatcher/actions.ts";
import Modal from "../../../../Modal.tsx";
describe("<NewRecoveryMethodDialog />", () => {
let matrixClient: MatrixClient;
beforeEach(() => {
matrixClient = createTestClient();
jest.spyOn(dis, "fire");
jest.spyOn(Modal, "createDialog");
vi.spyOn(dis, "fire");
vi.spyOn(Modal, "createDialog");
});
afterEach(() => {
jest.restoreAllMocks();
vi.restoreAllMocks();
});
function renderComponent(onFinished: () => void = jest.fn()) {
function renderComponent(onFinished: () => void = vi.fn()) {
return render(
<MatrixClientContext.Provider value={matrixClient}>
<NewRecoveryMethodDialog onFinished={onFinished} />
@@ -39,7 +42,7 @@ describe("<NewRecoveryMethodDialog />", () => {
}
test("when cancel is clicked", async () => {
const onFinished = jest.fn();
const onFinished = vi.fn();
act(() => {
renderComponent(onFinished);
});
@@ -50,9 +53,9 @@ describe("<NewRecoveryMethodDialog />", () => {
});
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);
await waitFor(() =>
@@ -67,7 +70,7 @@ describe("<NewRecoveryMethodDialog />", () => {
});
test("when key backup is disabled", async () => {
const onFinished = jest.fn();
const onFinished = vi.fn();
const { asFragment } = renderComponent(onFinished);
expect(asFragment()).toMatchSnapshot();
@@ -5,22 +5,25 @@
* Please see LICENSE files in the repository root for full details.
*/
import React from "react";
import { render, screen, fireEvent, waitFor } from "jest-matrix-react";
// @vitest-environment happy-dom
import RecoveryMethodRemovedDialog from "../../../../../src/async-components/views/dialogs/security/RecoveryMethodRemovedDialog";
import dispatch from "../../../../../src/dispatcher/dispatcher";
import { Action } from "../../../../../src/dispatcher/actions";
import { UserTab } from "../../../../../src/components/views/dialogs/UserTab";
import React from "react";
import { vi, describe, it, afterEach, expect } from "vitest";
import { render, screen, fireEvent, waitFor } from "test-utils-rtl";
import RecoveryMethodRemovedDialog from "./RecoveryMethodRemovedDialog";
import dispatch from "../../../../dispatcher/dispatcher";
import { Action } from "../../../../dispatcher/actions";
import { UserTab } from "../../../../components/views/dialogs/UserTab";
describe("<RecoveryMethodRemovedDialog />", () => {
afterEach(() => {
jest.restoreAllMocks();
vi.restoreAllMocks();
});
it("should open CreateKeyBackupDialog on primary action click", async () => {
const onFinished = jest.fn();
jest.spyOn(dispatch, "dispatch");
const onFinished = vi.fn();
vi.spyOn(dispatch, "dispatch");
render(<RecoveryMethodRemovedDialog onFinished={onFinished} />);
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>
<div
data-focus-guard="true"
@@ -70,6 +70,7 @@ exports[`<NewRecoveryMethodDialog /> when key backup is disabled 1`] = `
</span>
</div>
<div
aria-describedby="react-use-id-1"
aria-label="Close dialog"
class="mx_AccessibleButton mx_Dialog_cancelButton"
role="button"
@@ -96,7 +97,7 @@ exports[`<NewRecoveryMethodDialog /> when key backup is disabled 1`] = `
</DocumentFragment>
`;
exports[`<NewRecoveryMethodDialog /> when key backup is enabled 1`] = `
exports[`<NewRecoveryMethodDialog /> > when key backup is enabled 1`] = `
<DocumentFragment>
<div
data-focus-guard="true"
@@ -169,6 +170,7 @@ exports[`<NewRecoveryMethodDialog /> when key backup is enabled 1`] = `
</span>
</div>
<div
aria-describedby="react-use-id-1"
aria-label="Close dialog"
class="mx_AccessibleButton mx_Dialog_cancelButton"
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.
*/
import { type MatrixClient, type MatrixEvent } from "matrix-js-sdk/src/matrix";
import { mocked } from "jest-mock";
// @vitest-environment happy-dom
import { IntegrationManagers } from "../../../src/integrations/IntegrationManagers";
import { stubClient } from "../../test-utils";
import { type MatrixClient, type MatrixEvent } from "matrix-js-sdk/src/matrix";
import { vi, describe, it, expect, beforeEach, afterEach } from "vitest";
import { stubClient } from "test-utils";
import { IntegrationManagers } from "./IntegrationManagers";
describe("IntegrationManagers", () => {
let client: MatrixClient;
@@ -18,8 +20,8 @@ describe("IntegrationManagers", () => {
beforeEach(() => {
client = stubClient();
mocked(client).getAccountData.mockReturnValue({
getContent: jest.fn().mockReturnValue({
vi.mocked(client).getAccountData.mockReturnValue({
getContent: vi.fn().mockReturnValue({
foo: {
id: "foo",
content: {
@@ -6,14 +6,14 @@
*/
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 { getCommand } from "../../../src/slash-commands/SlashCommands";
import { stubClient } from "../../test-utils";
import { SDKContextClass } from "../../../src/contexts/SDKContextClass";
import { LocalRoom } from "../../../src/models/LocalRoom";
import DMRoomMap from "../../../src/utils/DMRoomMap.ts";
import { type Command } from "../command";
import { getCommand } from "../SlashCommands";
import { SDKContextClass } from "../../contexts/SDKContextClass";
import { LocalRoom } from "../../models/LocalRoom";
import DMRoomMap from "../../utils/DMRoomMap";
export function setUpCommandTest(
roomId: string,
@@ -25,7 +25,7 @@ export function setUpCommandTest(
client: MatrixClient;
room: Room;
} {
jest.clearAllMocks();
vi.clearAllMocks();
// TODO: if getCommand took a MatrixClient argument, we could use
// createTestClient here instead of stubClient (i.e. avoid setting
@@ -42,9 +42,9 @@ export function setUpCommandTest(
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) {
return room;
} 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",
"msgtype": "m.text",
}
`;
exports[`/lenny should match snapshot with no args 1`] = `
exports[`/lenny > should match snapshot with no args 1`] = `
{
"body": "( ͡° ͜ʖ ͡°)",
"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",
"msgtype": "m.text",
}
`;
exports[`/shrug should match snapshot with no args 1`] = `
exports[`/shrug > should match snapshot with no args 1`] = `
{
"body": "¯\\_(ツ)_/¯",
"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",
"msgtype": "m.text",
}
`;
exports[`/tableflip should match snapshot with no args 1`] = `
exports[`/tableflip > should match snapshot with no args 1`] = `
{
"body": "(╯°□°)╯︵ ┻━┻",
"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",
"msgtype": "m.text",
}
`;
exports[`/unflip should match snapshot with no args 1`] = `
exports[`/unflip > should match snapshot with no args 1`] = `
{
"body": "┬──┬ ノ( ゜-゜ノ)",
"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",
"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",
"format": "org.matrix.custom.html",
@@ -7,18 +7,25 @@
* 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 { setUpCommandTest } from "./utils";
import { WidgetType } from "../../../src/widgets/WidgetType";
import { describe, it, expect, vi } from "vitest";
import { waitFor } from "test-utils-rtl";
import WidgetUtils from "../utils/WidgetUtils";
import { setUpCommandTest } from "./__mocks__";
import { WidgetType } from "../widgets/WidgetType";
describe("/addwidget", () => {
const roomId = "!room:example.com";
it("should parse html iframe snippets", async () => {
jest.spyOn(WidgetUtils, "canUserModifyWidgets").mockReturnValue(true);
const spy = jest.spyOn(WidgetUtils, "setRoomWidget");
vi.spyOn(WidgetUtils, "canUserModifyWidgets").mockReturnValue(true);
// 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`);
@@ -5,7 +5,11 @@
* 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", () => {
const roomId = "!room:example.com";
@@ -7,7 +7,11 @@
* 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", () => {
const roomId = "!room:example.com";
@@ -7,7 +7,11 @@
* 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) => {
const roomId = "!room:example.com";
@@ -5,8 +5,12 @@
* Please see LICENSE files in the repository root for full details.
*/
import Modal, { type ComponentType, type IHandle } from "../../../src/Modal";
import { setUpCommandTest } from "./utils";
// @vitest-environment happy-dom
import { describe, it, expect, vi } from "vitest";
import Modal, { type ComponentType, type IHandle } from "../Modal";
import { setUpCommandTest } from "./__mocks__";
describe("/invite", () => {
const roomId = "!room:example.com";
@@ -17,7 +21,7 @@ describe("/invite", () => {
});
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>);
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 () => {
const spy = jest.spyOn(Modal, "createDialog");
const spy = vi.spyOn(Modal, "createDialog");
spy.mockReturnValue({ close: () => {} } as unknown as IHandle<ComponentType>);
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.
*/
import { setUpCommandTest } from "./utils";
import dispatcher from "../../../src/dispatcher/dispatcher";
// @vitest-environment happy-dom
import { describe, it, expect, vi } from "vitest";
import { setUpCommandTest } from "./__mocks__";
import dispatcher from "../dispatcher/dispatcher";
describe("/join", () => {
const roomId = "!room:example.com";
@@ -20,7 +24,7 @@ describe("/join", () => {
it("should handle matrix.org permalinks", async () => {
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;
@@ -36,7 +40,7 @@ describe("/join", () => {
it("should handle room aliases", async () => {
const { client, command } = setUpCommandTest(roomId, `/join`);
jest.spyOn(dispatcher, "dispatch");
vi.spyOn(dispatcher, "dispatch");
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 () => {
const { client, command } = setUpCommandTest(roomId, `/join`);
jest.spyOn(dispatcher, "dispatch");
vi.spyOn(dispatcher, "dispatch");
await command.run(client, roomId, null, "#test").promise;
@@ -64,7 +68,7 @@ describe("/join", () => {
it("should handle room IDs and via servers", async () => {
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;
@@ -5,9 +5,13 @@
* Please see LICENSE files in the repository root for full details.
*/
import { setUpCommandTest } from "./utils";
import dispatcher from "../../../src/dispatcher/dispatcher";
import DMRoomMap from "../../../src/utils/DMRoomMap";
// @vitest-environment happy-dom
import { describe, it, expect, vi } from "vitest";
import { setUpCommandTest } from "./__mocks__";
import dispatcher from "../dispatcher/dispatcher";
import DMRoomMap from "../utils/DMRoomMap";
describe("/msg", () => {
const roomId = "!room:example.com";
@@ -19,12 +23,13 @@ describe("/msg", () => {
it("should message the user and switch to the relevant DM", async () => {
// Given there is no DM room with the user
jest.spyOn(DMRoomMap, "shared").mockReturnValue({
getDMRoomsForUserId: jest.fn().mockReturnValue([]),
getRoomIds: jest.fn().mockReturnValue([roomId]),
vi.spyOn(DMRoomMap, "shared").mockReturnValue({
getDMRoomsForUserId: vi.fn().mockReturnValue([]),
getRoomIds: vi.fn().mockReturnValue([roomId]),
getUserIdForRoomId: vi.fn().mockReturnValue(undefined),
} as unknown as DMRoomMap);
jest.spyOn(dispatcher, "dispatch");
vi.spyOn(dispatcher, "dispatch");
// When we send a message to that user
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.
*/
// @vitest-environment happy-dom
import { KnownMembership, RoomMember } from "matrix-js-sdk/src/matrix";
import { describe, it, expect, vi } from "vitest";
import { setUpCommandTest } from "./utils";
import { warnSelfDemote } from "../../../src/components/views/right_panel/UserInfo";
import { setUpCommandTest } from "./__mocks__";
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", () => {
const roomId = "!room:example.com";
@@ -5,7 +5,11 @@
* 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", () => {
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.
*/
import { type MatrixClient, PendingEventOrdering, Room } from "matrix-js-sdk/src/matrix";
import { mocked } from "jest-mock";
// @vitest-environment happy-dom
import Modal, { type ComponentType, type IHandle } from "../../../src/Modal";
import { setUpCommandTest } from "./utils";
import { type Command } from "../../../src/slash-commands/command";
import { type MatrixClient, PendingEventOrdering, Room } from "matrix-js-sdk/src/matrix";
import { describe, it, expect, vi } from "vitest";
import Modal, { type ComponentType, type IHandle } from "../Modal";
import { setUpCommandTest } from "./__mocks__";
import { type Command } from "./command";
describe("/part", () => {
const roomId = "!room:example.com";
@@ -24,7 +26,7 @@ describe("/part", () => {
room1: Room;
room2: Room;
} {
const spy = jest.spyOn(Modal, "createDialog");
const spy = vi.spyOn(Modal, "createDialog");
spy.mockReturnValue({ close: () => {} } as unknown as IHandle<ComponentType>);
const { client, command, args } = setUpCommandTest(roomId, "/part #foo:bar");
@@ -36,7 +38,7 @@ describe("/part", () => {
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) {
return room1;
} else if (rId === room2.roomId) {
@@ -45,15 +47,15 @@ describe("/part", () => {
return null;
}
});
mocked(client.getRooms).mockReturnValue([room1, room2]);
vi.mocked(client.getRooms).mockReturnValue([room1, room2]);
return { client, command, args, room1, room2 };
}
it("should part room matching alias if found", async () => {
const { client, command, args, room1, room2 } = setUp();
room1.getCanonicalAlias = jest.fn().mockReturnValue("#foo:bar");
room2.getCanonicalAlias = jest.fn().mockReturnValue("#baz:bar");
room1.getCanonicalAlias = vi.fn().mockReturnValue("#foo:bar");
room2.getCanonicalAlias = vi.fn().mockReturnValue("#baz:bar");
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 () => {
const { client, command, args, room1, room2 } = setUp();
room1.getAltAliases = jest.fn().mockReturnValue(["#foo:bar"]);
room2.getAltAliases = jest.fn().mockReturnValue(["#baz:bar"]);
room1.getAltAliases = vi.fn().mockReturnValue(["#foo:bar"]);
room2.getAltAliases = vi.fn().mockReturnValue(["#baz:bar"]);
await command.run(client, room1.roomId, null, args).promise;
@@ -7,7 +7,11 @@
* 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) => {
const roomId = "!room:example.com";
@@ -5,7 +5,11 @@
* 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", () => {
const roomId = "!room:example.com";
@@ -7,8 +7,12 @@
* Please see LICENSE files in the repository root for full details.
*/
import Modal from "../../../src/Modal";
import { setUpCommandTest } from "./utils";
// @vitest-environment happy-dom
import { describe, it, expect, vi } from "vitest";
import Modal from "../Modal";
import { setUpCommandTest } from "./__mocks__";
describe("/topic", () => {
const roomId = "!room:example.com";
@@ -23,7 +27,7 @@ describe("/topic", () => {
});
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");
await command.run(client, roomId, null).promise;
expect(spy).toHaveBeenCalled();
@@ -7,15 +7,16 @@
* 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, {
type IFinishedOpts,
} from "../../../src/components/views/dialogs/RoomUpgradeWarningDialog";
import { type Command } from "../../../src/slash-commands/SlashCommands";
import { parseUpgradeRoomArgs } from "../../../src/slash-commands/upgraderoom/parseUpgradeRoomArgs";
import Modal from "../../../src/Modal";
import { setUpCommandTest } from "./utils";
import { type MatrixClient } from "matrix-js-sdk/src/matrix";
import { describe, it, expect, vi } from "vitest";
import RoomUpgradeWarningDialog, { type IFinishedOpts } from "../components/views/dialogs/RoomUpgradeWarningDialog";
import { type Command } from "./SlashCommands";
import { parseUpgradeRoomArgs } from "./upgraderoom/parseUpgradeRoomArgs";
import Modal from "../Modal";
import { setUpCommandTest } from "./__mocks__";
describe("/upgraderoom", () => {
const roomId = "!room:example.com";
@@ -33,16 +34,16 @@ describe("/upgraderoom", () => {
createDialog: unknown;
upgradeRoom: unknown;
} {
jest.clearAllMocks();
vi.clearAllMocks();
const { command, client } = setUpCommandTest(roomId, "/upgraderoom");
const createDialog = jest.spyOn(Modal, "createDialog");
const upgradeRoom = jest.fn().mockResolvedValue({ replacement_room: "!newroom" });
const createDialog = vi.spyOn(Modal, "createDialog");
const upgradeRoom = vi.fn().mockResolvedValue({ replacement_room: "!newroom" });
const resp: IFinishedOpts = { continue: continueUpgrade, invite: false };
createDialog.mockReturnValue({
finished: Promise.resolve([resp]),
close: jest.fn(),
close: vi.fn(),
});
client.upgradeRoom = upgradeRoom;
@@ -5,7 +5,11 @@
* 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", () => {
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.
*/
import { act, waitFor } from "jest-matrix-react";
// @vitest-environment happy-dom
import Modal, { type ComponentType, type IHandle } from "../../../src/Modal";
import { setUpCommandTest } from "./utils";
import QuestionDialog from "../../../src/components/views/dialogs/QuestionDialog";
import ErrorDialog from "../../../src/components/views/dialogs/ErrorDialog";
import { describe, it, expect, vi } from "vitest";
import { act, waitFor } from "test-utils-rtl";
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", () => {
const roomId = "!room:example.com";
@@ -24,7 +27,7 @@ describe("/verify", () => {
it("should attempt manual verification after confirmation", async () => {
// 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>);
// When we run the command
@@ -45,7 +48,7 @@ describe("/verify", () => {
it("should not do manual verification if cancelled", async () => {
// 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>);
// 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.
*/
// @vitest-environment happy-dom
import React from "react";
import { render, screen, cleanup, fireEvent, waitFor } from "jest-matrix-react";
import { mocked, type Mocked } from "jest-mock";
import { vi, describe, it, expect, beforeEach, afterEach, type Mocked } from "vitest";
import { render, screen, cleanup, fireEvent, waitFor } from "test-utils-rtl";
import {
Room,
RoomStateEvent,
@@ -35,23 +37,19 @@ import {
resetAsyncStoreWithClient,
mkEvent,
clientAndSDKContextRenderOptions,
} from "../../test-utils";
import defaultDispatcher from "../../../src/dispatcher/dispatcher";
import { Action } from "../../../src/dispatcher/actions";
import { MatrixClientPeg } from "../../../src/MatrixClientPeg";
import { CallStore } from "../../../src/stores/CallStore";
import { WidgetMessagingStore } from "../../../src/stores/widgets/WidgetMessagingStore";
import DMRoomMap from "../../../src/utils/DMRoomMap";
import ToastStore from "../../../src/stores/ToastStore";
import {
getIncomingCallToastKey,
getNotificationEventSendTs,
IncomingCallToast,
} from "../../../src/toasts/IncomingCallToast";
import { AudioID } from "../../../src/LegacyCallHandler";
import { CallEvent } from "../../../src/models/Call";
import { type WidgetMessaging } from "../../../src/stores/widgets/WidgetMessaging";
import { TestSDKContext } from "../TestSDKContext.ts";
TestSDKContext,
} from "test-utils";
import defaultDispatcher from "../dispatcher/dispatcher";
import { Action } from "../dispatcher/actions";
import { MatrixClientPeg } from "../MatrixClientPeg";
import { CallStore } from "../stores/CallStore";
import { WidgetMessagingStore } from "../stores/widgets/WidgetMessagingStore";
import DMRoomMap from "../utils/DMRoomMap";
import ToastStore from "../stores/ToastStore";
import { getIncomingCallToastKey, getNotificationEventSendTs, IncomingCallToast } from "./IncomingCallToast";
import { AudioID } from "../LegacyCallHandler";
import { CallEvent } from "../models/Call";
import { type WidgetMessaging } from "../stores/widgets/WidgetMessaging";
function makeNotificationEvent(room: Room, content: IContent = {}): MatrixEvent {
const ts = Date.now();
@@ -86,15 +84,15 @@ describe("IncomingCallToast", () => {
let call: MockedCall;
let widget: Widget;
const dmRoomMap = {
getUserIdForRoomId: jest.fn(),
getUserIdForRoomId: vi.fn(),
} as unknown as DMRoomMap;
const toastStore = {
dismissToast: jest.fn(),
dismissToast: vi.fn(),
} as unknown as Mocked<ToastStore>;
beforeEach(async () => {
stubClient();
client = mocked(MatrixClientPeg.safeGet());
client = vi.mocked(MatrixClientPeg.safeGet());
sdkContext = new TestSDKContext();
sdkContext._client = client;
@@ -126,8 +124,8 @@ describe("IncomingCallToast", () => {
stop: () => {},
} as unknown as WidgetMessaging);
jest.spyOn(DMRoomMap, "shared").mockReturnValue(dmRoomMap);
jest.spyOn(ToastStore, "sharedInstance").mockReturnValue(toastStore);
vi.spyOn(DMRoomMap, "shared").mockReturnValue(dmRoomMap);
vi.spyOn(ToastStore, "sharedInstance").mockReturnValue(toastStore);
toastStore.dismissToast.mockReset();
});
@@ -136,7 +134,7 @@ describe("IncomingCallToast", () => {
call.destroy();
WidgetMessagingStore.instance.stopMessaging(widget, room.roomId);
await Promise.all([CallStore.instance, WidgetMessagingStore.instance].map(resetAsyncStoreWithClient));
jest.restoreAllMocks();
vi.restoreAllMocks();
});
const renderToast = (notificationEvent: MatrixEvent = makeNotificationEvent(room)): string => {
@@ -166,19 +164,19 @@ describe("IncomingCallToast", () => {
});
renderToast(notificationEvent);
screen.getByText("Group call started");
screen.getByLabelText(callType === "voice" ? "Voice call" : "Video call");
screen.getByLabelText("@alice:example.org");
screen.getByLabelText("@bob:example.org");
screen.getByText("on the call");
expect(screen.getByText("Group call started")).toBeVisible();
expect(screen.getByLabelText(callType === "voice" ? "Voice call" : "Video call")).toBeVisible();
expect(screen.getByLabelText("@alice:example.org")).toBeVisible();
expect(screen.getByLabelText("@bob:example.org")).toBeVisible();
expect(screen.getByText("on the call")).toBeVisible();
screen.getByRole("button", { name: "Join" });
screen.getByRole("button", { name: "Decline" });
screen.getByRole("button", { name: "Expand" });
expect(screen.getByRole("button", { name: "Join" })).toBeVisible();
expect(screen.getByRole("button", { name: "Decline" })).toBeVisible();
expect(screen.getByRole("button", { name: "Expand" })).toBeVisible();
});
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,
);
try {
@@ -188,21 +186,23 @@ describe("IncomingCallToast", () => {
});
renderToast(notificationEvent);
screen.getByText(callType === "voice" ? "Incoming voice call" : "Incoming video call");
screen.getByLabelText(callType === "voice" ? "Voice call" : "Video call");
screen.getByLabelText("@alice:example.org");
expect(
screen.getByText(callType === "voice" ? "Incoming voice call" : "Incoming video call"),
).toBeVisible();
expect(screen.getByLabelText(callType === "voice" ? "Voice call" : "Video call")).toBeVisible();
expect(screen.getByLabelText("@alice:example.org")).toBeVisible();
screen.getByRole("button", { name: "Join" });
screen.getByRole("button", { name: "Decline" });
screen.getByRole("button", { name: "Expand" });
expect(screen.getByRole("button", { name: "Join" })).toBeVisible();
expect(screen.getByRole("button", { name: "Decline" })).toBeVisible();
expect(screen.getByRole("button", { name: "Expand" })).toBeVisible();
} finally {
mocked(dmRoomMap.getUserIdForRoomId).mockReset();
vi.mocked(dmRoomMap.getUserIdForRoomId).mockReset();
}
});
it("start ringing on ring notify event", () => {
const notificationEvent = makeNotificationEvent(room, { notification_type: "ring" });
const playMock = jest.spyOn(sdkContext.legacyCallHandler, "play");
const playMock = vi.spyOn(sdkContext.legacyCallHandler, "play");
render(
<IncomingCallToast notificationEvent={notificationEvent} toastKey="" />,
clientAndSDKContextRenderOptions(client, sdkContext),
@@ -226,7 +226,7 @@ describe("IncomingCallToast", () => {
it("joins with video and closes the toast", async () => {
const callId = renderToast();
const dispatcherSpy = jest.fn();
const dispatcherSpy = vi.fn();
const dispatcherRef = defaultDispatcher.register(dispatcherSpy);
screen.getByRole("switch", { name: "Join with video", checked: true });
@@ -251,7 +251,7 @@ describe("IncomingCallToast", () => {
it("joins without video and closes the toast", async () => {
const callId = renderToast();
const dispatcherSpy = jest.fn();
const dispatcherSpy = vi.fn();
const dispatcherRef = defaultDispatcher.register(dispatcherSpy);
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 () => {
const callId = renderToast();
const dispatcherSpy = jest.fn();
const dispatcherSpy = vi.fn();
const dispatcherRef = defaultDispatcher.register(dispatcherSpy);
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 () => {
const callId = renderToast();
const dispatcherSpy = jest.fn();
const dispatcherSpy = vi.fn();
const dispatcherRef = defaultDispatcher.register(dispatcherSpy);
call.emit(
@@ -319,7 +319,7 @@ describe("IncomingCallToast", () => {
it("expands to show the call lobby", async () => {
const callId = renderToast();
const dispatcherSpy = jest.fn();
const dispatcherSpy = vi.fn();
const dispatcherRef = defaultDispatcher.register(dispatcherSpy);
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
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 { MatrixCall } from "matrix-js-sdk/src/webrtc/call";
import React from "react";
import IncomingLegacyCallToast from "../../../src/toasts/IncomingLegacyCallToast";
import DMRoomMap from "../../../src/utils/DMRoomMap";
import IncomingLegacyCallToast from "./IncomingLegacyCallToast";
import DMRoomMap from "../utils/DMRoomMap";
import {
clientAndSDKContextRenderOptions,
getMockClientWithEventEmitter,
mockClientMethodsServer,
mockClientMethodsUser,
} from "../../test-utils";
import { TestSDKContext } from "../TestSDKContext.ts";
TestSDKContext,
} from "test-utils";
describe("<IncomingLegacyCallToast />", () => {
const userId = "@alice:server.org";
const deviceId = "my-device";
jest.spyOn(DMRoomMap, "shared").mockReturnValue({
getUserIdForRoomId: jest.fn(),
vi.spyOn(DMRoomMap, "shared").mockReturnValue({
getUserIdForRoomId: vi.fn(),
} as unknown as DMRoomMap);
const mockClient = getMockClientWithEventEmitter({
...mockClientMethodsUser(userId),
...mockClientMethodsServer(),
getRoom: jest.fn(),
getRoom: vi.fn(),
});
const sdkContext = new TestSDKContext();
sdkContext._client = mockClient;
@@ -45,7 +49,7 @@ describe("<IncomingLegacyCallToast />", () => {
const getComponent = (props = {}) => <IncomingLegacyCallToast {...defaultProps} {...props} />;
beforeEach(() => {
jest.clearAllMocks();
vi.clearAllMocks();
mockClient.getAccountData.mockReturnValue(undefined);
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.
*/
// @vitest-environment happy-dom
import React from "react";
import { act, render, screen } from "jest-matrix-react";
import { mocked, type Mocked } from "jest-mock";
import { vi, describe, it, expect, beforeEach, type Mocked } from "vitest";
import { act, render, screen } from "test-utils-rtl";
import userEvent from "@testing-library/user-event";
import { type MatrixClient } from "matrix-js-sdk/src/matrix";
import { type CryptoApi, DecryptionKeyDoesNotMatchError } from "matrix-js-sdk/src/crypto-api";
import { type SecretStorageKeyDescriptionAesV1 } from "matrix-js-sdk/src/secret-storage";
import * as SecurityManager from "../../../src/SecurityManager";
import ToastContainer from "../../../src/components/structures/ToastContainer";
import { showToast } from "../../../src/toasts/SetupEncryptionToast";
import dis from "../../../src/dispatcher/dispatcher";
import { DeviceListener } from "../../../src/device-listener";
import Modal from "../../../src/Modal";
import ConfirmKeyStorageOffDialog from "../../../src/components/views/dialogs/ConfirmKeyStorageOffDialog";
import SetupEncryptionDialog from "../../../src/components/views/dialogs/security/SetupEncryptionDialog";
import { stubClient } from "../../test-utils";
import * as SecurityManager from "../SecurityManager";
import ToastContainer from "../components/structures/ToastContainer";
import { showToast } from "./SetupEncryptionToast";
import dis from "../dispatcher/dispatcher";
import { DeviceListener } from "../device-listener";
import Modal from "../Modal";
import ConfirmKeyStorageOffDialog from "../components/views/dialogs/ConfirmKeyStorageOffDialog";
import SetupEncryptionDialog from "../components/views/dialogs/security/SetupEncryptionDialog";
import { stubClient } from "test-utils";
jest.mock("../../../src/dispatcher/dispatcher", () => ({
dispatch: jest.fn(),
register: jest.fn(),
unregister: jest.fn(),
vi.mock("../dispatcher/dispatcher", () => ({
default: {
dispatch: vi.fn(),
register: vi.fn(),
unregister: vi.fn(),
},
}));
describe("SetupEncryptionToast", () => {
beforeEach(() => {
jest.resetAllMocks();
vi.resetAllMocks();
render(<ToastContainer />);
});
@@ -44,8 +48,8 @@ describe("SetupEncryptionToast", () => {
});
it("should dismiss the toast when 'Dismiss' button clicked, and remember it", async () => {
jest.spyOn(DeviceListener.sharedInstance(), "recordRecoveryDisabled");
jest.spyOn(DeviceListener.sharedInstance(), "dismissEncryptionSetup");
vi.spyOn(DeviceListener.sharedInstance(), "recordRecoveryDisabled");
vi.spyOn(DeviceListener.sharedInstance(), "dismissEncryptionSetup");
act(() => showToast("set_up_recovery"));
@@ -61,12 +65,12 @@ describe("SetupEncryptionToast", () => {
let client: Mocked<MatrixClient>;
beforeEach(() => {
client = mocked(stubClient());
mocked(client.getCrypto).mockReturnValue({
getSessionBackupPrivateKey: jest.fn().mockResolvedValue(null),
resetKeyBackup: jest.fn(),
checkKeyBackupAndEnable: jest.fn(),
loadSessionBackupPrivateKeyFromSecretStorage: jest.fn(),
client = vi.mocked(stubClient());
vi.mocked(client.getCrypto).mockReturnValue({
getSessionBackupPrivateKey: vi.fn().mockResolvedValue(null),
resetKeyBackup: vi.fn(),
checkKeyBackupAndEnable: vi.fn(),
loadSessionBackupPrivateKeyFromSecretStorage: vi.fn(),
} as unknown as CryptoApi);
});
@@ -79,13 +83,13 @@ describe("SetupEncryptionToast", () => {
it("should reset key backup if needed", async () => {
showToast("key_storage_out_of_sync");
jest.spyOn(SecurityManager, "accessSecretStorage").mockImplementation(
vi.spyOn(SecurityManager, "accessSecretStorage").mockImplementation(
async (func = async (): Promise<void> => {}) => {
return await func();
},
);
jest.spyOn(DeviceListener.sharedInstance(), "keyStorageOutOfSyncNeedsBackupReset").mockResolvedValue(true);
vi.spyOn(DeviceListener.sharedInstance(), "keyStorageOutOfSyncNeedsBackupReset").mockResolvedValue(true);
const user = userEvent.setup();
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 () => {
showToast("key_storage_out_of_sync");
jest.spyOn(SecurityManager, "accessSecretStorage").mockImplementation(
vi.spyOn(SecurityManager, "accessSecretStorage").mockImplementation(
async (func = async (): Promise<void> => {}) => {
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
client.isKeyBackupKeyStored.mockResolvedValue({});
@@ -120,16 +124,16 @@ describe("SetupEncryptionToast", () => {
const crypto = client.getCrypto()!;
jest.spyOn(SecurityManager, "accessSecretStorage").mockImplementation(
vi.spyOn(SecurityManager, "accessSecretStorage").mockImplementation(
async (func = async (): Promise<void> => {}) => func(),
);
// 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"),
);
jest.spyOn(DeviceListener.sharedInstance(), "keyStorageOutOfSyncNeedsBackupReset").mockResolvedValue(false);
vi.spyOn(DeviceListener.sharedInstance(), "keyStorageOutOfSyncNeedsBackupReset").mockResolvedValue(false);
client.isKeyBackupKeyStored.mockResolvedValue({});
// 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 () => {
act(() => showToast("key_storage_out_of_sync"));
jest.spyOn(DeviceListener.sharedInstance(), "keyStorageOutOfSyncNeedsCrossSigningReset").mockResolvedValue(
vi.spyOn(DeviceListener.sharedInstance(), "keyStorageOutOfSyncNeedsCrossSigningReset").mockResolvedValue(
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 () => {
act(() => showToast("key_storage_out_of_sync"));
jest.spyOn(DeviceListener.sharedInstance(), "keyStorageOutOfSyncNeedsCrossSigningReset").mockResolvedValue(
vi.spyOn(DeviceListener.sharedInstance(), "keyStorageOutOfSyncNeedsCrossSigningReset").mockResolvedValue(
false,
);
@@ -176,11 +180,11 @@ describe("SetupEncryptionToast", () => {
});
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!");
});
jest.spyOn(DeviceListener.sharedInstance(), "keyStorageOutOfSyncNeedsCrossSigningReset").mockResolvedValue(
vi.spyOn(DeviceListener.sharedInstance(), "keyStorageOutOfSyncNeedsCrossSigningReset").mockResolvedValue(
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 () => {
jest.spyOn(SecurityManager, "accessSecretStorage").mockImplementation(async () => {
vi.spyOn(SecurityManager, "accessSecretStorage").mockImplementation(async () => {
throw new Error("Something went wrong while recovering!");
});
jest.spyOn(DeviceListener.sharedInstance(), "keyStorageOutOfSyncNeedsCrossSigningReset").mockResolvedValue(
vi.spyOn(DeviceListener.sharedInstance(), "keyStorageOutOfSyncNeedsCrossSigningReset").mockResolvedValue(
false,
);
@@ -218,18 +222,18 @@ describe("SetupEncryptionToast", () => {
});
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(),
);
jest.spyOn(DeviceListener.sharedInstance(), "keyStorageOutOfSyncNeedsCrossSigningReset").mockResolvedValue(
vi.spyOn(DeviceListener.sharedInstance(), "keyStorageOutOfSyncNeedsCrossSigningReset").mockResolvedValue(
true,
);
jest.spyOn(DeviceListener.sharedInstance(), "keyStorageOutOfSyncNeedsBackupReset").mockResolvedValue(false);
mocked(client.isKeyBackupKeyStored).mockResolvedValue(fakeKeyBackupKey());
vi.spyOn(DeviceListener.sharedInstance(), "keyStorageOutOfSyncNeedsBackupReset").mockResolvedValue(false);
vi.mocked(client.isKeyBackupKeyStored).mockResolvedValue(fakeKeyBackupKey());
// 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"),
);
@@ -252,7 +256,7 @@ describe("SetupEncryptionToast", () => {
});
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"));
@@ -293,7 +297,7 @@ describe("SetupEncryptionToast", () => {
});
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"));
@@ -309,10 +313,10 @@ describe("SetupEncryptionToast", () => {
});
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"
jest.spyOn(Modal, "createDialog").mockImplementation(() => {
vi.spyOn(Modal, "createDialog").mockImplementation(() => {
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 () => {
jest.spyOn(DeviceListener.sharedInstance(), "dismissEncryptionSetup");
vi.spyOn(DeviceListener.sharedInstance(), "dismissEncryptionSetup");
act(() => showToast("verify_this_session"));
@@ -355,7 +359,7 @@ describe("SetupEncryptionToast", () => {
});
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
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.
*/
// @vitest-environment happy-dom
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 { mocked, type Mocked } from "jest-mock";
import { type IMyDevice, type MatrixClient } from "matrix-js-sdk/src/matrix";
import { type CryptoApi, DeviceVerificationStatus } from "matrix-js-sdk/src/crypto-api";
import dis from "../../../src/dispatcher/dispatcher";
import { showToast } from "../../../src/toasts/UnverifiedSessionToast";
import { filterConsole, flushPromises, stubClient } from "../../test-utils";
import ToastContainer from "../../../src/components/structures/ToastContainer";
import { Action } from "../../../src/dispatcher/actions";
import { DeviceListener } from "../../../src/device-listener";
import dis from "../dispatcher/dispatcher";
import { showToast } from "./UnverifiedSessionToast";
import { filterConsole, flushPromises, stubClient } from "test-utils";
import ToastContainer from "../components/structures/ToastContainer";
import { Action } from "../dispatcher/actions";
import { DeviceListener } from "../device-listener";
describe("UnverifiedSessionToast", () => {
const otherDevice: IMyDevice = {
@@ -30,7 +32,7 @@ describe("UnverifiedSessionToast", () => {
filterConsole("Dismissing unverified sessions: ABC123");
beforeAll(() => {
client = mocked(stubClient());
client = vi.mocked(stubClient());
client.getDevice.mockImplementation(async (deviceId: string) => {
if (deviceId === otherDevice.device_id) {
return otherDevice;
@@ -39,12 +41,12 @@ describe("UnverifiedSessionToast", () => {
throw new Error(`Unknown device ${deviceId}`);
});
client.getCrypto.mockReturnValue({
getDeviceVerificationStatus: jest
getDeviceVerificationStatus: vi
.fn()
.mockResolvedValue(new DeviceVerificationStatus({ crossSigningVerified: true })),
} as unknown as CryptoApi);
jest.spyOn(dis, "dispatch");
jest.spyOn(DeviceListener.sharedInstance(), "dismissUnverifiedSessions");
vi.spyOn(dis, "dispatch");
vi.spyOn(DeviceListener.sharedInstance(), "dismissUnverifiedSessions");
});
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
aria-disabled="true"
aria-label="Notifications silenced"
@@ -23,7 +23,7 @@ exports[`<IncomingLegacyCallToast /> renders disabled silenced button when call
</div>
`;
exports[`<IncomingLegacyCallToast /> renders sound on button when call is silenced 1`] = `
exports[`<IncomingLegacyCallToast /> > renders sound on button when call is silenced 1`] = `
<div
aria-label="Sound on"
class="mx_AccessibleButton mx_IncomingLegacyCallToast_iconButton"
@@ -44,7 +44,7 @@ exports[`<IncomingLegacyCallToast /> renders sound on button when call is silenc
</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
aria-label="Silence call"
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>
<div>
<div