Move more tests over to vitest (#34249)

* Move more tests over to vitest

* Add exception for test_setting
This commit is contained in:
Michael Telatynski
2026-07-15 08:48:51 +00:00
committed by GitHub
parent cb07147d72
commit 0c61944ffd
24 changed files with 292 additions and 233 deletions
@@ -6,17 +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.
*/ */
import PosthogTrackers from "../../../../src/PosthogTrackers"; // @vitest-environment happy-dom
import AnalyticsController from "../../../../src/settings/controllers/AnalyticsController";
import { SettingLevel } from "../../../../src/settings/SettingLevel"; import { vi, describe, it, expect, afterEach } from "vitest";
import PosthogTrackers from "../../PosthogTrackers";
import AnalyticsController from "../controllers/AnalyticsController";
import { SettingLevel } from "../SettingLevel";
describe("AnalyticsController", () => { describe("AnalyticsController", () => {
afterEach(() => { afterEach(() => {
jest.restoreAllMocks(); vi.restoreAllMocks();
}); });
it("Tracks a Posthog interaction on change", () => { it("Tracks a Posthog interaction on change", () => {
const trackInteractionSpy = jest.spyOn(PosthogTrackers, "trackInteraction"); const trackInteractionSpy = vi.spyOn(PosthogTrackers, "trackInteraction");
const controller = new AnalyticsController("WebSettingsNotificationsTACOnlyNotificationsToggle"); const controller = new AnalyticsController("WebSettingsNotificationsTACOnlyNotificationsToggle");
@@ -6,24 +6,26 @@ 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, MatrixEvent } from "matrix-js-sdk/src/matrix"; // @vitest-environment happy-dom
import { mocked } from "jest-mock";
import { SETTINGS } from "../../../../src/settings/Settings"; import { vi, describe, it, expect, beforeEach } from "vitest";
import { stubClient } from "../../../test-utils"; import { type MatrixClient, MatrixEvent } from "matrix-js-sdk/src/matrix";
import MatrixClientBackedController from "../../../../src/settings/controllers/MatrixClientBackedController"; import { stubClient } from "test-utils";
import { SettingLevel } from "../../../../src/settings/SettingLevel.ts";
import { SETTINGS } from "../Settings";
import MatrixClientBackedController from "./MatrixClientBackedController";
import { SettingLevel } from "../SettingLevel.ts";
describe("BlockInvitesConfigController", () => { describe("BlockInvitesConfigController", () => {
describe("When server does not support MSC4380", () => { describe("When server does not support MSC4380", () => {
let cli: MatrixClient; let cli: MatrixClient;
beforeEach(() => { beforeEach(() => {
cli = stubClient(); cli = stubClient();
cli.doesServerSupportUnstableFeature = jest.fn(async () => false); cli.doesServerSupportUnstableFeature = vi.fn(async () => false);
MatrixClientBackedController.matrixClient = cli; MatrixClientBackedController.matrixClient = cli;
}); });
test("settingDisabled() should give a message", () => { it("settingDisabled() should give a message", () => {
const controller = SETTINGS.blockInvites.controller!; const controller = SETTINGS.blockInvites.controller!;
expect(controller.settingDisabled).toEqual("Your server does not implement this feature."); expect(controller.settingDisabled).toEqual("Your server does not implement this feature.");
}); });
@@ -33,13 +35,13 @@ describe("BlockInvitesConfigController", () => {
let cli: MatrixClient; let cli: MatrixClient;
beforeEach(async () => { beforeEach(async () => {
cli = stubClient(); cli = stubClient();
cli.doesServerSupportUnstableFeature = jest.fn(async (feature) => { cli.doesServerSupportUnstableFeature = vi.fn(async (feature) => {
return feature == "org.matrix.msc4380.stable"; return feature == "org.matrix.msc4380.stable";
}); });
MatrixClientBackedController.matrixClient = cli; MatrixClientBackedController.matrixClient = cli;
}); });
test("settingDisabled() should be false", () => { it("settingDisabled() should be false", () => {
const controller = SETTINGS.blockInvites.controller!; const controller = SETTINGS.blockInvites.controller!;
expect(controller.settingDisabled).toEqual(false); expect(controller.settingDisabled).toEqual(false);
}); });
@@ -85,7 +87,7 @@ describe("BlockInvitesConfigController", () => {
* in response to any request for `m.invite_permission_config`. * in response to any request for `m.invite_permission_config`.
*/ */
function mockAccountData(cli: MatrixClient, mockAccountData: object) { function mockAccountData(cli: MatrixClient, mockAccountData: object) {
mocked(cli.getAccountData).mockImplementation((eventType) => { vi.mocked(cli.getAccountData).mockImplementation((eventType) => {
if (eventType == "m.invite_permission_config") { if (eventType == "m.invite_permission_config") {
return new MatrixEvent({ return new MatrixEvent({
type: "m.invite_permission_config", type: "m.invite_permission_config",
@@ -5,15 +5,18 @@ 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 { AllDevicesIsolationMode, OnlySignedDevicesIsolationMode } from "matrix-js-sdk/src/crypto-api"; // @vitest-environment happy-dom
import { stubClient } from "../../../test-utils"; import { vi, describe, it, expect, afterEach } from "vitest";
import DeviceIsolationModeController from "../../../../src/settings/controllers/DeviceIsolationModeController.ts"; import { AllDevicesIsolationMode, OnlySignedDevicesIsolationMode } from "matrix-js-sdk/src/crypto-api";
import { SettingLevel } from "../../../../src/settings/SettingLevel"; import { stubClient } from "test-utils";
import DeviceIsolationModeController from "./DeviceIsolationModeController.ts";
import { SettingLevel } from "../SettingLevel";
describe("DeviceIsolationModeController", () => { describe("DeviceIsolationModeController", () => {
afterEach(() => { afterEach(() => {
jest.resetAllMocks(); vi.resetAllMocks();
}); });
describe("tracks enabling and disabling", () => { describe("tracks enabling and disabling", () => {
@@ -5,13 +5,16 @@ 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 fetchMock from "@fetch-mock/jest"; // @vitest-environment happy-dom
import { vi, describe, it, expect, beforeEach, afterEach } from "vitest";
import fetchMock from "@fetch-mock/vitest";
import { ClientEvent, MatrixClient } from "matrix-js-sdk/src/matrix"; import { ClientEvent, MatrixClient } from "matrix-js-sdk/src/matrix";
import { SettingLevel } from "../../../../src/settings/SettingLevel"; import { SettingLevel } from "../SettingLevel";
import FallbackIceServerController from "../../../../src/settings/controllers/FallbackIceServerController.ts"; import FallbackIceServerController from "./FallbackIceServerController.ts";
import MatrixClientBackedController from "../../../../src/settings/controllers/MatrixClientBackedController.ts"; import MatrixClientBackedController from "./MatrixClientBackedController.ts";
import SettingsStore from "../../../../src/settings/SettingsStore.ts"; import SettingsStore from "../SettingsStore.ts";
describe("FallbackIceServerController", () => { describe("FallbackIceServerController", () => {
beforeEach(() => { beforeEach(() => {
@@ -19,7 +22,7 @@ describe("FallbackIceServerController", () => {
}); });
afterEach(() => { afterEach(() => {
jest.restoreAllMocks(); vi.restoreAllMocks();
}); });
it("should update MatrixClient's state when the setting is updated", async () => { it("should update MatrixClient's state when the setting is updated", async () => {
@@ -6,12 +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 { Action } from "../../../../src/dispatcher/actions"; import { vi, describe, it, expect } from "vitest";
import dis from "../../../../src/dispatcher/dispatcher";
import FontSizeController from "../../../../src/settings/controllers/FontSizeController";
import { SettingLevel } from "../../../../src/settings/SettingLevel";
const dispatchSpy = jest.spyOn(dis, "fire"); import { Action } from "../../dispatcher/actions";
import dis from "../../dispatcher/dispatcher";
import FontSizeController from "./FontSizeController";
import { SettingLevel } from "../SettingLevel";
const dispatchSpy = vi.spyOn(dis, "fire");
describe("FontSizeController", () => { describe("FontSizeController", () => {
it("dispatches a font size action on change", () => { it("dispatches a font size action on change", () => {
@@ -6,18 +6,20 @@ 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 IncompatibleController from "../../../../src/settings/controllers/IncompatibleController"; import { vi, describe, it, expect, beforeEach } from "vitest";
import { SettingLevel } from "../../../../src/settings/SettingLevel";
import SettingsStore from "../../../../src/settings/SettingsStore";
declare module "../../../../src/settings/Settings.tsx" { import IncompatibleController from "./IncompatibleController";
import { SettingLevel } from "../SettingLevel";
import SettingsStore from "../SettingsStore";
declare module "../Settings.tsx" {
interface Settings { interface Settings {
test_setting: IBaseSetting<string>; test_setting: IBaseSetting<string>;
} }
} }
describe("IncompatibleController", () => { describe("IncompatibleController", () => {
const settingsGetValueSpy = jest.spyOn(SettingsStore, "getValue"); const settingsGetValueSpy = vi.spyOn(SettingsStore, "getValue");
beforeEach(() => { beforeEach(() => {
settingsGetValueSpy.mockClear(); settingsGetValueSpy.mockClear();
}); });
@@ -58,7 +60,7 @@ describe("IncompatibleController", () => {
describe("when incompatibleValue is set to a function", () => { describe("when incompatibleValue is set to a function", () => {
it("returns result from incompatibleValue function", () => { it("returns result from incompatibleValue function", () => {
const incompatibleValueFn = jest.fn().mockReturnValue(false); const incompatibleValueFn = vi.fn().mockReturnValue(false);
const controller = new IncompatibleController("test_setting", { key: null }, incompatibleValueFn); const controller = new IncompatibleController("test_setting", { key: null }, incompatibleValueFn);
settingsGetValueSpy.mockReturnValue("test"); settingsGetValueSpy.mockReturnValue("test");
expect(controller.incompatibleSetting).toBe(false); expect(controller.incompatibleSetting).toBe(false);
@@ -5,17 +5,20 @@ 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 { MatrixEvent } from "matrix-js-sdk/src/matrix"; // @vitest-environment happy-dom
import MatrixClientBackedController from "../../../../src/settings/controllers/MatrixClientBackedController"; import { vi, describe, it, expect, afterEach } from "vitest";
import InviteRulesConfigController from "../../../../src/settings/controllers/InviteRulesConfigController"; import { MatrixEvent } from "matrix-js-sdk/src/matrix";
import { SettingLevel } from "../../../../src/settings/SettingLevel"; import { getMockClientWithEventEmitter, mockClientMethodsServer } from "test-utils";
import { getMockClientWithEventEmitter, mockClientMethodsServer } from "../../../test-utils";
import { INVITE_RULES_ACCOUNT_DATA_TYPE, type InviteConfigAccountData } from "../../../../src/@types/invite-rules"; import MatrixClientBackedController from "./MatrixClientBackedController";
import InviteRulesConfigController from "./InviteRulesConfigController";
import { SettingLevel } from "../SettingLevel";
import { INVITE_RULES_ACCOUNT_DATA_TYPE, type InviteConfigAccountData } from "../../@types/invite-rules";
describe("InviteRulesConfigController", () => { describe("InviteRulesConfigController", () => {
afterEach(() => { afterEach(() => {
jest.restoreAllMocks(); vi.restoreAllMocks();
}); });
it("gets the default settings when none are specified.", () => { it("gets the default settings when none are specified.", () => {
@@ -23,7 +26,7 @@ describe("InviteRulesConfigController", () => {
MatrixClientBackedController.matrixClient = getMockClientWithEventEmitter({ MatrixClientBackedController.matrixClient = getMockClientWithEventEmitter({
...mockClientMethodsServer(), ...mockClientMethodsServer(),
getAccountData: jest.fn().mockReturnValue(null), getAccountData: vi.fn().mockReturnValue(null),
}); });
const value = controller.getValueOverride(SettingLevel.ACCOUNT); const value = controller.getValueOverride(SettingLevel.ACCOUNT);
@@ -35,7 +38,7 @@ describe("InviteRulesConfigController", () => {
MatrixClientBackedController.matrixClient = getMockClientWithEventEmitter({ MatrixClientBackedController.matrixClient = getMockClientWithEventEmitter({
...mockClientMethodsServer(), ...mockClientMethodsServer(),
getAccountData: jest getAccountData: vi
.fn() .fn()
.mockReturnValue(new MatrixEvent({ type: INVITE_RULES_ACCOUNT_DATA_TYPE, content: {} })), .mockReturnValue(new MatrixEvent({ type: INVITE_RULES_ACCOUNT_DATA_TYPE, content: {} })),
}); });
@@ -51,7 +54,7 @@ describe("InviteRulesConfigController", () => {
MatrixClientBackedController.matrixClient = getMockClientWithEventEmitter({ MatrixClientBackedController.matrixClient = getMockClientWithEventEmitter({
...mockClientMethodsServer(), ...mockClientMethodsServer(),
getAccountData: jest.fn().mockReturnValue( getAccountData: vi.fn().mockReturnValue(
new MatrixEvent({ new MatrixEvent({
type: INVITE_RULES_ACCOUNT_DATA_TYPE, type: INVITE_RULES_ACCOUNT_DATA_TYPE,
content, content,
@@ -73,7 +76,7 @@ describe("InviteRulesConfigController", () => {
MatrixClientBackedController.matrixClient = getMockClientWithEventEmitter({ MatrixClientBackedController.matrixClient = getMockClientWithEventEmitter({
...mockClientMethodsServer(), ...mockClientMethodsServer(),
getAccountData: jest.fn().mockReturnValue( getAccountData: vi.fn().mockReturnValue(
new MatrixEvent({ new MatrixEvent({
type: INVITE_RULES_ACCOUNT_DATA_TYPE, type: INVITE_RULES_ACCOUNT_DATA_TYPE,
content, content,
@@ -89,7 +92,7 @@ describe("InviteRulesConfigController", () => {
const controller = new InviteRulesConfigController(); const controller = new InviteRulesConfigController();
const client = (MatrixClientBackedController.matrixClient = getMockClientWithEventEmitter({ const client = (MatrixClientBackedController.matrixClient = getMockClientWithEventEmitter({
...mockClientMethodsServer(), ...mockClientMethodsServer(),
getAccountData: jest.fn().mockReturnValue( getAccountData: vi.fn().mockReturnValue(
new MatrixEvent({ new MatrixEvent({
type: INVITE_RULES_ACCOUNT_DATA_TYPE, type: INVITE_RULES_ACCOUNT_DATA_TYPE,
content: { content: {
@@ -98,7 +101,7 @@ describe("InviteRulesConfigController", () => {
}, },
}), }),
), ),
setAccountData: jest.fn(), setAccountData: vi.fn(),
})); }));
expect(await controller.beforeChange(SettingLevel.ACCOUNT, null, { allBlocked: true })).toBe(true); expect(await controller.beforeChange(SettingLevel.ACCOUNT, null, { allBlocked: true })).toBe(true);
@@ -113,7 +116,7 @@ describe("InviteRulesConfigController", () => {
const controller = new InviteRulesConfigController(); const controller = new InviteRulesConfigController();
const client = (MatrixClientBackedController.matrixClient = getMockClientWithEventEmitter({ const client = (MatrixClientBackedController.matrixClient = getMockClientWithEventEmitter({
...mockClientMethodsServer(), ...mockClientMethodsServer(),
getAccountData: jest.fn().mockReturnValue( getAccountData: vi.fn().mockReturnValue(
new MatrixEvent({ new MatrixEvent({
type: INVITE_RULES_ACCOUNT_DATA_TYPE, type: INVITE_RULES_ACCOUNT_DATA_TYPE,
content: { content: {
@@ -123,7 +126,7 @@ describe("InviteRulesConfigController", () => {
}, },
}), }),
), ),
setAccountData: jest.fn(), setAccountData: vi.fn(),
})); }));
expect(await controller.beforeChange(SettingLevel.ACCOUNT, null, { allBlocked: false })).toBe(true); expect(await controller.beforeChange(SettingLevel.ACCOUNT, null, { allBlocked: false })).toBe(true);
@@ -137,7 +140,7 @@ describe("InviteRulesConfigController", () => {
const controller = new InviteRulesConfigController(); const controller = new InviteRulesConfigController();
const client = (MatrixClientBackedController.matrixClient = getMockClientWithEventEmitter({ const client = (MatrixClientBackedController.matrixClient = getMockClientWithEventEmitter({
...mockClientMethodsServer(), ...mockClientMethodsServer(),
getAccountData: jest.fn().mockReturnValue( getAccountData: vi.fn().mockReturnValue(
new MatrixEvent({ new MatrixEvent({
type: INVITE_RULES_ACCOUNT_DATA_TYPE, type: INVITE_RULES_ACCOUNT_DATA_TYPE,
content: { content: {
@@ -147,7 +150,7 @@ describe("InviteRulesConfigController", () => {
}, },
}), }),
), ),
setAccountData: jest.fn(), setAccountData: vi.fn(),
})); }));
expect(await controller.beforeChange(SettingLevel.ACCOUNT, null, { allBlocked })).toBe(false); expect(await controller.beforeChange(SettingLevel.ACCOUNT, null, { allBlocked })).toBe(false);
@@ -5,17 +5,20 @@ 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 { MatrixEvent } from "matrix-js-sdk/src/matrix"; // @vitest-environment happy-dom
import MatrixClientBackedController from "../../../../src/settings/controllers/MatrixClientBackedController"; import { vi, describe, it, expect, afterEach } from "vitest";
import MediaPreviewConfigController from "../../../../src/settings/controllers/MediaPreviewConfigController"; import { MatrixEvent } from "matrix-js-sdk/src/matrix";
import { SettingLevel } from "../../../../src/settings/SettingLevel"; import { getMockClientWithEventEmitter, mockClientMethodsServer } from "test-utils";
import { getMockClientWithEventEmitter, mockClientMethodsServer } from "../../../test-utils";
import { MEDIA_PREVIEW_ACCOUNT_DATA_TYPE, MediaPreviewValue } from "../../../../src/@types/media_preview"; import MatrixClientBackedController from "./MatrixClientBackedController";
import MediaPreviewConfigController from "./MediaPreviewConfigController";
import { SettingLevel } from "../SettingLevel";
import { MEDIA_PREVIEW_ACCOUNT_DATA_TYPE, MediaPreviewValue } from "../../@types/media_preview";
describe("MediaPreviewConfigController", () => { describe("MediaPreviewConfigController", () => {
afterEach(() => { afterEach(() => {
jest.restoreAllMocks(); vi.restoreAllMocks();
}); });
const ROOM_ID = "!room:example.org"; const ROOM_ID = "!room:example.org";
@@ -25,7 +28,7 @@ describe("MediaPreviewConfigController", () => {
MatrixClientBackedController.matrixClient = getMockClientWithEventEmitter({ MatrixClientBackedController.matrixClient = getMockClientWithEventEmitter({
...mockClientMethodsServer(), ...mockClientMethodsServer(),
getAccountData: jest.fn().mockReturnValue(null), getAccountData: vi.fn().mockReturnValue(null),
}); });
const value = controller.getValueOverride(SettingLevel.ACCOUNT, null); const value = controller.getValueOverride(SettingLevel.ACCOUNT, null);
@@ -37,7 +40,7 @@ describe("MediaPreviewConfigController", () => {
MatrixClientBackedController.matrixClient = getMockClientWithEventEmitter({ MatrixClientBackedController.matrixClient = getMockClientWithEventEmitter({
...mockClientMethodsServer(), ...mockClientMethodsServer(),
getAccountData: jest getAccountData: vi
.fn() .fn()
.mockReturnValue(new MatrixEvent({ type: MEDIA_PREVIEW_ACCOUNT_DATA_TYPE, content: {} })), .mockReturnValue(new MatrixEvent({ type: MEDIA_PREVIEW_ACCOUNT_DATA_TYPE, content: {} })),
}); });
@@ -51,7 +54,7 @@ describe("MediaPreviewConfigController", () => {
MatrixClientBackedController.matrixClient = getMockClientWithEventEmitter({ MatrixClientBackedController.matrixClient = getMockClientWithEventEmitter({
...mockClientMethodsServer(), ...mockClientMethodsServer(),
getAccountData: jest.fn().mockReturnValue( getAccountData: vi.fn().mockReturnValue(
new MatrixEvent({ new MatrixEvent({
type: MEDIA_PREVIEW_ACCOUNT_DATA_TYPE, type: MEDIA_PREVIEW_ACCOUNT_DATA_TYPE,
content: { content: {
@@ -59,8 +62,8 @@ describe("MediaPreviewConfigController", () => {
}, },
}), }),
), ),
getRoom: jest.fn().mockReturnValue({ getRoom: vi.fn().mockReturnValue({
getAccountData: jest.fn().mockReturnValue(null), getAccountData: vi.fn().mockReturnValue(null),
}), }),
}); });
@@ -77,9 +80,9 @@ describe("MediaPreviewConfigController", () => {
MatrixClientBackedController.matrixClient = getMockClientWithEventEmitter({ MatrixClientBackedController.matrixClient = getMockClientWithEventEmitter({
...mockClientMethodsServer(), ...mockClientMethodsServer(),
getAccountData: jest.fn().mockReturnValue(null), getAccountData: vi.fn().mockReturnValue(null),
getRoom: jest.fn().mockReturnValue({ getRoom: vi.fn().mockReturnValue({
getAccountData: jest.fn().mockReturnValue( getAccountData: vi.fn().mockReturnValue(
new MatrixEvent({ new MatrixEvent({
type: MEDIA_PREVIEW_ACCOUNT_DATA_TYPE, type: MEDIA_PREVIEW_ACCOUNT_DATA_TYPE,
content: { content: {
@@ -105,7 +108,7 @@ describe("MediaPreviewConfigController", () => {
MatrixClientBackedController.matrixClient = getMockClientWithEventEmitter({ MatrixClientBackedController.matrixClient = getMockClientWithEventEmitter({
...mockClientMethodsServer(), ...mockClientMethodsServer(),
getAccountData: jest.fn().mockReturnValue( getAccountData: vi.fn().mockReturnValue(
new MatrixEvent({ new MatrixEvent({
type: MEDIA_PREVIEW_ACCOUNT_DATA_TYPE, type: MEDIA_PREVIEW_ACCOUNT_DATA_TYPE,
content: { content: {
@@ -113,8 +116,8 @@ describe("MediaPreviewConfigController", () => {
}, },
}), }),
), ),
getRoom: jest.fn().mockReturnValue({ getRoom: vi.fn().mockReturnValue({
getAccountData: jest.fn().mockReturnValue(null), getAccountData: vi.fn().mockReturnValue(null),
}), }),
}); });
@@ -133,7 +136,7 @@ describe("MediaPreviewConfigController", () => {
MatrixClientBackedController.matrixClient = getMockClientWithEventEmitter({ MatrixClientBackedController.matrixClient = getMockClientWithEventEmitter({
...mockClientMethodsServer(), ...mockClientMethodsServer(),
getAccountData: jest.fn().mockReturnValue( getAccountData: vi.fn().mockReturnValue(
new MatrixEvent({ new MatrixEvent({
type: MEDIA_PREVIEW_ACCOUNT_DATA_TYPE, type: MEDIA_PREVIEW_ACCOUNT_DATA_TYPE,
content: { content: {
@@ -141,8 +144,8 @@ describe("MediaPreviewConfigController", () => {
}, },
}), }),
), ),
getRoom: jest.fn().mockReturnValue({ getRoom: vi.fn().mockReturnValue({
getAccountData: jest.fn().mockReturnValue( getAccountData: vi.fn().mockReturnValue(
new MatrixEvent({ new MatrixEvent({
type: MEDIA_PREVIEW_ACCOUNT_DATA_TYPE, type: MEDIA_PREVIEW_ACCOUNT_DATA_TYPE,
content: { content: {
@@ -5,12 +5,16 @@ 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 { Capabilities } from "matrix-js-sdk/src/matrix"; // @vitest-environment happy-dom
import RequiresSettingsController from "../../../../src/settings/controllers/RequiresSettingsController";
import { SettingLevel } from "../../../../src/settings/SettingLevel"; import { vi, describe, it, expect, beforeEach, afterEach } from "vitest";
import SettingsStore from "../../../../src/settings/SettingsStore"; import { type Capabilities } from "matrix-js-sdk/src/matrix";
import MatrixClientBackedController from "../../../../src/settings/controllers/MatrixClientBackedController"; import { getMockClientWithEventEmitter, mockClientMethodsServer } from "test-utils";
import { getMockClientWithEventEmitter, mockClientMethodsServer } from "../../../test-utils";
import RequiresSettingsController from "./RequiresSettingsController";
import { SettingLevel } from "../SettingLevel";
import SettingsStore from "../SettingsStore";
import MatrixClientBackedController from "./MatrixClientBackedController";
describe("RequiresSettingsController", () => { describe("RequiresSettingsController", () => {
afterEach(() => { afterEach(() => {
@@ -39,14 +43,14 @@ describe("RequiresSettingsController", () => {
beforeEach(() => { beforeEach(() => {
client = getMockClientWithEventEmitter({ client = getMockClientWithEventEmitter({
...mockClientMethodsServer(), ...mockClientMethodsServer(),
getCachedCapabilities: jest.fn().mockImplementation(() => {}), getCachedCapabilities: vi.fn().mockImplementation(() => {}),
getCapabilities: jest.fn().mockRejectedValue({}), getCapabilities: vi.fn().mockRejectedValue({}),
}); });
MatrixClientBackedController["_matrixClient"] = client; MatrixClientBackedController["_matrixClient"] = client;
}); });
afterEach(() => { afterEach(() => {
jest.restoreAllMocks(); vi.restoreAllMocks();
}); });
it("will disable setting if capability check is true", async () => { it("will disable setting if capability check is true", async () => {
@@ -6,14 +6,17 @@ 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 } from "matrix-js-sdk/src/matrix"; // @vitest-environment happy-dom
import ServerSupportUnstableFeatureController from "../../../../src/settings/controllers/ServerSupportUnstableFeatureController"; import { vi, describe, it, expect } from "vitest";
import { SettingLevel } from "../../../../src/settings/SettingLevel"; import { type MatrixClient } from "matrix-js-sdk/src/matrix";
import { type FeatureSettingKey, LabGroup, SETTINGS } from "../../../../src/settings/Settings"; import { stubClient } from "test-utils";
import { stubClient } from "../../../test-utils";
import { WatchManager } from "../../../../src/settings/WatchManager"; import ServerSupportUnstableFeatureController from "./ServerSupportUnstableFeatureController";
import MatrixClientBackedController from "../../../../src/settings/controllers/MatrixClientBackedController"; import { SettingLevel } from "../SettingLevel";
import { type FeatureSettingKey, LabGroup, SETTINGS } from "../Settings";
import { WatchManager } from "../WatchManager";
import MatrixClientBackedController from "./MatrixClientBackedController";
describe("ServerSupportUnstableFeatureController", () => { describe("ServerSupportUnstableFeatureController", () => {
const watchers = new WatchManager(); const watchers = new WatchManager();
@@ -41,7 +44,7 @@ describe("ServerSupportUnstableFeatureController", () => {
describe("getValueOverride()", () => { describe("getValueOverride()", () => {
it("should return forced value is setting is disabled", async () => { it("should return forced value is setting is disabled", async () => {
const cli = stubClient(); const cli = stubClient();
cli.doesServerSupportUnstableFeature = jest.fn(async () => false); cli.doesServerSupportUnstableFeature = vi.fn(async () => false);
const controller = new ServerSupportUnstableFeatureController( const controller = new ServerSupportUnstableFeatureController(
setting, setting,
@@ -60,7 +63,7 @@ describe("ServerSupportUnstableFeatureController", () => {
it("should pass through to the handler if setting is not disabled", async () => { it("should pass through to the handler if setting is not disabled", async () => {
const cli = stubClient(); const cli = stubClient();
cli.doesServerSupportUnstableFeature = jest.fn(async () => true); cli.doesServerSupportUnstableFeature = vi.fn(async () => true);
const controller = new ServerSupportUnstableFeatureController( const controller = new ServerSupportUnstableFeatureController(
setting, setting,
@@ -82,7 +85,7 @@ describe("ServerSupportUnstableFeatureController", () => {
it("considered disabled if not all required features in the only feature group are supported", async () => { it("considered disabled if not all required features in the only feature group are supported", async () => {
const cli = stubClient(); const cli = stubClient();
cli.doesServerSupportUnstableFeature = jest.fn(async (featureName) => { cli.doesServerSupportUnstableFeature = vi.fn(async (featureName) => {
return featureName === "org.matrix.msc3827.stable"; return featureName === "org.matrix.msc3827.stable";
}); });
@@ -96,7 +99,7 @@ describe("ServerSupportUnstableFeatureController", () => {
it("considered enabled if all required features in the only feature group are supported", async () => { it("considered enabled if all required features in the only feature group are supported", async () => {
const cli = stubClient(); const cli = stubClient();
cli.doesServerSupportUnstableFeature = jest.fn(async (featureName) => { cli.doesServerSupportUnstableFeature = vi.fn(async (featureName) => {
return featureName === "org.matrix.msc3827.stable" || featureName === "org.matrix.msc3030"; return featureName === "org.matrix.msc3827.stable" || featureName === "org.matrix.msc3030";
}); });
const controller = new ServerSupportUnstableFeatureController(setting, watchers, [ const controller = new ServerSupportUnstableFeatureController(setting, watchers, [
@@ -109,7 +112,7 @@ describe("ServerSupportUnstableFeatureController", () => {
it("considered enabled if all required features in one of the feature groups are supported", async () => { it("considered enabled if all required features in one of the feature groups are supported", async () => {
const cli = stubClient(); const cli = stubClient();
cli.doesServerSupportUnstableFeature = jest.fn(async (featureName) => { cli.doesServerSupportUnstableFeature = vi.fn(async (featureName) => {
return featureName === "org.matrix.msc3827.stable" || featureName === "org.matrix.msc3030"; return featureName === "org.matrix.msc3827.stable" || featureName === "org.matrix.msc3030";
}); });
const controller = new ServerSupportUnstableFeatureController(setting, watchers, [ const controller = new ServerSupportUnstableFeatureController(setting, watchers, [
@@ -123,7 +126,7 @@ describe("ServerSupportUnstableFeatureController", () => {
it("considered disabled if not all required features in one of the feature groups are supported", async () => { it("considered disabled if not all required features in one of the feature groups are supported", async () => {
const cli = stubClient(); const cli = stubClient();
cli.doesServerSupportUnstableFeature = jest.fn(async (featureName) => { cli.doesServerSupportUnstableFeature = vi.fn(async (featureName) => {
return featureName === "org.matrix.msc3827.stable"; return featureName === "org.matrix.msc3827.stable";
}); });
@@ -6,18 +6,20 @@ 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 { Action } from "../../../../src/dispatcher/actions"; import { vi, describe, it, expect } from "vitest";
import dis from "../../../../src/dispatcher/dispatcher";
import SystemFontController from "../../../../src/settings/controllers/SystemFontController";
import SettingsStore from "../../../../src/settings/SettingsStore";
const dispatchSpy = jest.spyOn(dis, "dispatch"); import { Action } from "../../dispatcher/actions";
import dis from "../../dispatcher/dispatcher";
import SystemFontController from "./SystemFontController";
import SettingsStore from "../SettingsStore";
const dispatchSpy = vi.spyOn(dis, "dispatch");
describe("SystemFontController", () => { describe("SystemFontController", () => {
it("dispatches a system font update action on change", () => { it("dispatches a system font update action on change", () => {
const controller = new SystemFontController(); const controller = new SystemFontController();
const getValueSpy = jest.spyOn(SettingsStore, "getValue").mockImplementation((settingName): any => { const getValueSpy = vi.spyOn(SettingsStore, "getValue").mockImplementation((settingName): any => {
if (settingName === "useBundledEmojiFont") return false; if (settingName === "useBundledEmojiFont") return false;
if (settingName === "useSystemFont") return true; if (settingName === "useSystemFont") return true;
if (settingName === "systemFont") return "Comic Sans MS"; if (settingName === "systemFont") return "Comic Sans MS";
@@ -6,10 +6,9 @@ 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 { import { describe, it, expect } from "vitest";
humanReadableNotificationLevel,
NotificationLevel, import { humanReadableNotificationLevel, NotificationLevel } from "./NotificationLevel";
} from "../../../../src/stores/notifications/NotificationLevel";
describe("NotificationLevel", () => { describe("NotificationLevel", () => {
describe("humanReadableNotificationLevel", () => { describe("humanReadableNotificationLevel", () => {
@@ -6,6 +6,9 @@ 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 { vi, describe, it, expect, beforeEach, afterEach } from "vitest";
import { import {
Room, Room,
MatrixEventEvent, MatrixEventEvent,
@@ -17,15 +20,15 @@ import {
RoomEvent, RoomEvent,
} from "matrix-js-sdk/src/matrix"; } from "matrix-js-sdk/src/matrix";
import { KnownMembership } from "matrix-js-sdk/src/types"; import { KnownMembership } from "matrix-js-sdk/src/types";
import { mkEvent, muteRoom, stubClient } from "test-utils";
import { createMessageEventContent } from "test-utils/events";
import type { MatrixClient } from "matrix-js-sdk/src/matrix"; import type { MatrixClient } from "matrix-js-sdk/src/matrix";
import { mkEvent, muteRoom, stubClient } from "../../../test-utils"; import { RoomNotificationState } from "./RoomNotificationState";
import { RoomNotificationState } from "../../../../src/stores/notifications/RoomNotificationState"; import { NotificationStateEvents } from "./NotificationState";
import { NotificationStateEvents } from "../../../../src/stores/notifications/NotificationState"; import { NotificationLevel } from "./NotificationLevel";
import { NotificationLevel } from "../../../../src/stores/notifications/NotificationLevel"; import SettingsStore from "../../settings/SettingsStore";
import { createMessageEventContent } from "../../../test-utils/events"; import * as UnreadModule from "../../Unread";
import SettingsStore from "../../../../src/settings/SettingsStore";
import * as UnreadModule from "../../../../src/Unread";
describe("RoomNotificationState", () => { describe("RoomNotificationState", () => {
let room: Room; let room: Room;
@@ -39,12 +42,12 @@ describe("RoomNotificationState", () => {
}); });
afterEach(() => { afterEach(() => {
jest.resetAllMocks(); vi.resetAllMocks();
}); });
function addThread(room: Room): void { function addThread(room: Room): void {
const threadId = "thread_id"; const threadId = "thread_id";
jest.spyOn(room, "eventShouldLiveIn").mockReturnValue({ vi.spyOn(room, "eventShouldLiveIn").mockReturnValue({
shouldLiveInRoom: true, shouldLiveInRoom: true,
shouldLiveInThread: true, shouldLiveInThread: true,
threadId, threadId,
@@ -82,19 +85,19 @@ describe("RoomNotificationState", () => {
it("updates on event decryption", () => { it("updates on event decryption", () => {
const roomNotifState = new RoomNotificationState(room, true); const roomNotifState = new RoomNotificationState(room, true);
const listener = jest.fn(); const listener = vi.fn();
roomNotifState.addListener(NotificationStateEvents.Update, listener); roomNotifState.addListener(NotificationStateEvents.Update, listener);
const testEvent = { const testEvent = {
getRoomId: () => room.roomId, getRoomId: () => room.roomId,
} as unknown as MatrixEvent; } as unknown as MatrixEvent;
room.getUnreadNotificationCount = jest.fn().mockReturnValue(1); room.getUnreadNotificationCount = vi.fn().mockReturnValue(1);
client.emit(MatrixEventEvent.Decrypted, testEvent); client.emit(MatrixEventEvent.Decrypted, testEvent);
expect(listener).toHaveBeenCalled(); expect(listener).toHaveBeenCalled();
}); });
it("emits an Update event on marked unread room account data", () => { it("emits an Update event on marked unread room account data", () => {
const roomNotifState = new RoomNotificationState(room, true); const roomNotifState = new RoomNotificationState(room, true);
const listener = jest.fn(); const listener = vi.fn();
roomNotifState.addListener(NotificationStateEvents.Update, listener); roomNotifState.addListener(NotificationStateEvents.Update, listener);
const accountDataEvent = { const accountDataEvent = {
getType: () => "m.marked_unread", getType: () => "m.marked_unread",
@@ -102,14 +105,14 @@ describe("RoomNotificationState", () => {
return { unread: true }; return { unread: true };
}, },
} as unknown as MatrixEvent; } as unknown as MatrixEvent;
room.getAccountData = jest.fn().mockReturnValue(accountDataEvent); room.getAccountData = vi.fn().mockReturnValue(accountDataEvent);
room.emit(RoomEvent.AccountData, accountDataEvent, room); room.emit(RoomEvent.AccountData, accountDataEvent, room);
expect(listener).toHaveBeenCalled(); expect(listener).toHaveBeenCalled();
}); });
it("does not update on other account data", () => { it("does not update on other account data", () => {
const roomNotifState = new RoomNotificationState(room, true); const roomNotifState = new RoomNotificationState(room, true);
const listener = jest.fn(); const listener = vi.fn();
roomNotifState.addListener(NotificationStateEvents.Update, listener); roomNotifState.addListener(NotificationStateEvents.Update, listener);
const accountDataEvent = { const accountDataEvent = {
getType: () => "else.something", getType: () => "else.something",
@@ -117,7 +120,7 @@ describe("RoomNotificationState", () => {
return {}; return {};
}, },
} as unknown as MatrixEvent; } as unknown as MatrixEvent;
room.getAccountData = jest.fn().mockReturnValue(accountDataEvent); room.getAccountData = vi.fn().mockReturnValue(accountDataEvent);
room.emit(RoomEvent.AccountData, accountDataEvent, room); room.emit(RoomEvent.AccountData, accountDataEvent, room);
expect(listener).not.toHaveBeenCalled(); expect(listener).not.toHaveBeenCalled();
}); });
@@ -209,8 +212,8 @@ describe("RoomNotificationState", () => {
describe("computed attributes", () => { describe("computed attributes", () => {
beforeEach(() => { beforeEach(() => {
jest.spyOn(room, "getPendingEvents").mockReturnValue([]); vi.spyOn(room, "getPendingEvents").mockReturnValue([]);
jest.spyOn(UnreadModule, "doesRoomHaveUnreadMessages").mockReturnValue(false); vi.spyOn(UnreadModule, "doesRoomHaveUnreadMessages").mockReturnValue(false);
}); });
it("should has invited at true", () => { it("should has invited at true", () => {
@@ -220,7 +223,7 @@ describe("RoomNotificationState", () => {
}); });
it("should has isUnsetMessage at true", () => { it("should has isUnsetMessage at true", () => {
jest.spyOn(room, "getPendingEvents").mockReturnValue([ vi.spyOn(room, "getPendingEvents").mockReturnValue([
mkEvent({ status: EventStatus.NOT_SENT, user: "@foobar:example.org", type: "any.event", content: {} }), mkEvent({ status: EventStatus.NOT_SENT, user: "@foobar:example.org", type: "any.event", content: {} }),
]); ]);
const roomNotifState = new RoomNotificationState(room, false); const roomNotifState = new RoomNotificationState(room, false);
@@ -236,11 +239,11 @@ describe("RoomNotificationState", () => {
room.updateMyMembership(KnownMembership.Invite); room.updateMyMembership(KnownMembership.Invite);
expect(roomNotifState.isMention).toBe(false); expect(roomNotifState.isMention).toBe(false);
jest.spyOn(SettingsStore, "getValue").mockReturnValue(true); vi.spyOn(SettingsStore, "getValue").mockReturnValue(true);
room.updateMyMembership(KnownMembership.Knock); room.updateMyMembership(KnownMembership.Knock);
expect(roomNotifState.isMention).toBe(false); expect(roomNotifState.isMention).toBe(false);
jest.spyOn(room, "getPendingEvents").mockReturnValue([ vi.spyOn(room, "getPendingEvents").mockReturnValue([
mkEvent({ status: EventStatus.NOT_SENT, user: "@foobar:example.org", type: "any.event", content: {} }), mkEvent({ status: EventStatus.NOT_SENT, user: "@foobar:example.org", type: "any.event", content: {} }),
]); ]);
room.updateMyMembership(KnownMembership.Join); room.updateMyMembership(KnownMembership.Join);
@@ -255,7 +258,7 @@ describe("RoomNotificationState", () => {
}); });
it("should has isActivityNotification at true", () => { it("should has isActivityNotification at true", () => {
jest.spyOn(UnreadModule, "doesRoomHaveUnreadMessages").mockReturnValue(true); vi.spyOn(UnreadModule, "doesRoomHaveUnreadMessages").mockReturnValue(true);
const roomNotifState = new RoomNotificationState(room, false); const roomNotifState = new RoomNotificationState(room, false);
expect(roomNotifState.isActivityNotification).toBe(true); expect(roomNotifState.isActivityNotification).toBe(true);
@@ -263,9 +266,9 @@ describe("RoomNotificationState", () => {
it("should has hasAnyNotificationOrActivity at true", () => { it("should has hasAnyNotificationOrActivity at true", () => {
// Hidebold is disabled // Hidebold is disabled
jest.spyOn(SettingsStore, "getValue").mockReturnValue(false); vi.spyOn(SettingsStore, "getValue").mockReturnValue(false);
// Unread message, generate activity notification // Unread message, generate activity notification
jest.spyOn(UnreadModule, "doesRoomHaveUnreadMessages").mockReturnValue(true); vi.spyOn(UnreadModule, "doesRoomHaveUnreadMessages").mockReturnValue(true);
// Highlight notification // Highlight notification
setUnreads(room, 0, 1); setUnreads(room, 0, 1);
@@ -281,12 +284,12 @@ describe("RoomNotificationState", () => {
expect(roomNotifState.hasAnyNotificationOrActivity).toBe(true); expect(roomNotifState.hasAnyNotificationOrActivity).toBe(true);
// hidebold is enabled and we have an activity notification // hidebold is enabled and we have an activity notification
jest.spyOn(SettingsStore, "getValue").mockReturnValue(true); vi.spyOn(SettingsStore, "getValue").mockReturnValue(true);
room.updateMyMembership(KnownMembership.Join); room.updateMyMembership(KnownMembership.Join);
expect(roomNotifState.hasAnyNotificationOrActivity).toBe(false); expect(roomNotifState.hasAnyNotificationOrActivity).toBe(false);
// No unread // No unread
jest.spyOn(UnreadModule, "doesRoomHaveUnreadMessages").mockReturnValue(false); vi.spyOn(UnreadModule, "doesRoomHaveUnreadMessages").mockReturnValue(false);
room.updateMyMembership(KnownMembership.Join); room.updateMyMembership(KnownMembership.Join);
expect(roomNotifState.hasAnyNotificationOrActivity).toBe(false); expect(roomNotifState.hasAnyNotificationOrActivity).toBe(false);
}); });
@@ -6,15 +6,17 @@ 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 { vi, describe, it, expect, afterAll, beforeEach } from "vitest";
import { makeDelegatedAuthMetadata } from "test-utils/auth";
import { AutoDiscovery, AutoDiscoveryAction, type ClientConfig } from "matrix-js-sdk/src/matrix"; import { AutoDiscovery, AutoDiscoveryAction, type ClientConfig } from "matrix-js-sdk/src/matrix";
import { logger } from "matrix-js-sdk/src/logger"; import { logger } from "matrix-js-sdk/src/logger";
import fetchMock from "@fetch-mock/jest"; import fetchMock from "@fetch-mock/vitest";
import AutoDiscoveryUtils from "../../../src/utils/AutoDiscoveryUtils"; import AutoDiscoveryUtils from "./AutoDiscoveryUtils";
import { makeDelegatedAuthMetadata } from "../../test-utils/auth";
describe("AutoDiscoveryUtils", () => { describe("AutoDiscoveryUtils", () => {
beforeEach(() => { beforeEach(() => {
fetchMock.mockReset();
fetchMock.catch({ fetchMock.catch({
status: 404, status: 404,
body: '{"errcode": "M_UNRECOGNIZED", "error": "Unrecognized request"}', body: '{"errcode": "M_UNRECOGNIZED", "error": "Unrecognized request"}',
@@ -27,13 +29,13 @@ describe("AutoDiscoveryUtils", () => {
beforeEach(() => { beforeEach(() => {
// don't litter console with expected errors // don't litter console with expected errors
jest.spyOn(logger, "error") vi.spyOn(logger, "error")
.mockClear() .mockClear()
.mockImplementation(() => {}); .mockImplementation(() => {});
}); });
afterAll(() => { afterAll(() => {
jest.spyOn(logger, "error").mockRestore(); vi.spyOn(logger, "error").mockRestore();
}); });
const validIsConfig = { const validIsConfig = {
@@ -6,7 +6,10 @@ 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 { mocked, type Mocked } from "jest-mock"; // @vitest-environment happy-dom
import { vi, describe, it, expect, beforeEach, type Mocked } from "vitest";
import { logger } from "matrix-js-sdk/src/logger"; import { logger } from "matrix-js-sdk/src/logger";
import { import {
ClientEvent, ClientEvent,
@@ -16,9 +19,10 @@ import {
type MatrixEvent, type MatrixEvent,
type Room, type Room,
} from "matrix-js-sdk/src/matrix"; } from "matrix-js-sdk/src/matrix";
import { mkEvent, stubClient } from "test-utils";
import DMRoomMap from "./DMRoomMap";
import DMRoomMap from "../../../src/utils/DMRoomMap";
import { mkEvent, stubClient } from "../../test-utils";
describe("DMRoomMap", () => { describe("DMRoomMap", () => {
const roomId1 = "!room1:example.com"; const roomId1 = "!room1:example.com";
const roomId2 = "!room2:example.com"; const roomId2 = "!room2:example.com";
@@ -44,8 +48,8 @@ describe("DMRoomMap", () => {
}; };
beforeEach(() => { beforeEach(() => {
client = mocked(stubClient()); client = vi.mocked(stubClient());
jest.spyOn(logger, "warn"); vi.spyOn(logger, "warn");
}); });
describe("when m.direct has valid content", () => { describe("when m.direct has valid content", () => {
@@ -140,19 +144,19 @@ describe("DMRoomMap", () => {
describe("getUniqueRoomsWithIndividuals()", () => { describe("getUniqueRoomsWithIndividuals()", () => {
const bigRoom = { const bigRoom = {
roomId: "!bigRoom:server.org", roomId: "!bigRoom:server.org",
getInvitedAndJoinedMemberCount: jest.fn().mockReturnValue(5000), getInvitedAndJoinedMemberCount: vi.fn().mockReturnValue(5000),
} as unknown as Room; } as unknown as Room;
const dmWithBob = { const dmWithBob = {
roomId: "!dmWithBob:server.org", roomId: "!dmWithBob:server.org",
getInvitedAndJoinedMemberCount: jest.fn().mockReturnValue(2), getInvitedAndJoinedMemberCount: vi.fn().mockReturnValue(2),
} as unknown as Room; } as unknown as Room;
const dmWithCharlie = { const dmWithCharlie = {
roomId: "!dmWithCharlie:server.org", roomId: "!dmWithCharlie:server.org",
getInvitedAndJoinedMemberCount: jest.fn().mockReturnValue(2), getInvitedAndJoinedMemberCount: vi.fn().mockReturnValue(2),
} as unknown as Room; } as unknown as Room;
const smallRoom = { const smallRoom = {
roomId: "!smallRoom:server.org", roomId: "!smallRoom:server.org",
getInvitedAndJoinedMemberCount: jest.fn().mockReturnValue(3), getInvitedAndJoinedMemberCount: vi.fn().mockReturnValue(3),
} as unknown as Room; } as unknown as Room;
const mDirectContent = { const mDirectContent = {
@@ -163,7 +167,7 @@ describe("DMRoomMap", () => {
beforeEach(() => { beforeEach(() => {
client.getAccountData.mockReturnValue(mkMDirectEvent(mDirectContent)); client.getAccountData.mockReturnValue(mkMDirectEvent(mDirectContent));
client.getRoom.mockImplementation( client.getRoom.mockImplementation(
(roomId: string) => (roomId?: string) =>
[bigRoom, smallRoom, dmWithCharlie, dmWithBob].find((room) => room.roomId === roomId) ?? null, [bigRoom, smallRoom, dmWithCharlie, dmWithBob].find((room) => room.roomId === roomId) ?? null,
); );
}); });
@@ -6,18 +6,20 @@ 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 SdkConfig from "../../../src/SdkConfig"; import { vi, describe, it, expect, afterEach } from "vitest";
import { shouldShowFeedback } from "../../../src/utils/Feedback";
import SettingsStore from "../../../src/settings/SettingsStore"; import SdkConfig from "../SdkConfig";
import { UIFeature } from "../../../src/settings/UIFeature"; import { shouldShowFeedback } from "./Feedback";
import { BugReportEndpointURLLocal } from "../../../src/IConfigOptions"; import SettingsStore from "../settings/SettingsStore";
import { UIFeature } from "../settings/UIFeature";
import { BugReportEndpointURLLocal } from "../IConfigOptions";
const realGetValue = SettingsStore.getValue; const realGetValue = SettingsStore.getValue;
describe("shouldShowFeedback", () => { describe("shouldShowFeedback", () => {
afterEach(() => { afterEach(() => {
SdkConfig.reset(); SdkConfig.reset();
jest.restoreAllMocks(); vi.restoreAllMocks();
}); });
it("should return false if bug_report_endpoint_url is falsey", () => { it("should return false if bug_report_endpoint_url is falsey", () => {
@@ -35,7 +37,7 @@ describe("shouldShowFeedback", () => {
}); });
it("should return false if UIFeature.Feedback is disabled", () => { it("should return false if UIFeature.Feedback is disabled", () => {
jest.spyOn(SettingsStore, "getValue").mockImplementation((key, ...params) => { vi.spyOn(SettingsStore, "getValue").mockImplementation((key, ...params) => {
if (key === UIFeature.Feedback) { if (key === UIFeature.Feedback) {
return false; return false;
} }
@@ -48,7 +50,7 @@ describe("shouldShowFeedback", () => {
SdkConfig.put({ SdkConfig.put({
bug_report_endpoint_url: "https://rageshake.server", bug_report_endpoint_url: "https://rageshake.server",
}); });
jest.spyOn(SettingsStore, "getValue").mockImplementation((key, ...params) => { vi.spyOn(SettingsStore, "getValue").mockImplementation((key, ...params) => {
if (key === UIFeature.Feedback) { if (key === UIFeature.Feedback) {
return true; return true;
} }
@@ -5,10 +5,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 { MatrixEvent } from "matrix-js-sdk/src/matrix"; // @vitest-environment happy-dom
import { MediaEventHelper } from "../../../src/utils/MediaEventHelper.ts"; import { describe, it, expect } from "vitest";
import { stubClient } from "../../test-utils";
import { MatrixEvent } from "matrix-js-sdk/src/matrix";
import { stubClient } from "test-utils";
import { MediaEventHelper } from "./MediaEventHelper.ts";
describe("MediaEventHelper", () => { describe("MediaEventHelper", () => {
it("should set the mime type on the blob based on the event metadata", async () => { it("should set the mime type on the blob based on the event metadata", async () => {
@@ -6,17 +6,19 @@ 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 { mocked } from "jest-mock"; // @vitest-environment happy-dom
import { vi, describe, it, expect, beforeEach, type Mocked } from "vitest";
import { EventType, type MatrixClient, MatrixError, MatrixEvent, Room, RoomMember } from "matrix-js-sdk/src/matrix"; import { EventType, type MatrixClient, MatrixError, MatrixEvent, Room, RoomMember } from "matrix-js-sdk/src/matrix";
import { KnownMembership } from "matrix-js-sdk/src/types"; import { KnownMembership } from "matrix-js-sdk/src/types";
import * as TestUtilsMatrix from "test-utils";
import { MatrixClientPeg } from "../../../src/MatrixClientPeg"; import { MatrixClientPeg } from "../MatrixClientPeg";
import Modal, { type ComponentType, type ComponentProps } from "../../../src/Modal"; import Modal, { type ComponentType, type ComponentProps } from "../Modal";
import SettingsStore from "../../../src/settings/SettingsStore"; import SettingsStore from "../settings/SettingsStore";
import MultiInviter, { type CompletionStates } from "../../../src/utils/MultiInviter"; import MultiInviter, { type CompletionStates } from "./MultiInviter";
import * as TestUtilsMatrix from "../../test-utils"; import AskInviteAnywayDialog from "../components/views/dialogs/AskInviteAnywayDialog";
import AskInviteAnywayDialog from "../../../src/components/views/dialogs/AskInviteAnywayDialog"; import ConfirmUserActionDialog from "../components/views/dialogs/ConfirmUserActionDialog";
import ConfirmUserActionDialog from "../../../src/components/views/dialogs/ConfirmUserActionDialog";
const ROOMID = "!room:server"; const ROOMID = "!room:server";
@@ -34,19 +36,23 @@ const MXID_PROFILE_STATES: Record<string, () => {}> = {
}, },
}; };
jest.mock("../../../src/Modal", () => ({ vi.mock("../Modal", () => ({
createDialog: jest.fn(), default: {
createDialog: vi.fn(),
},
})); }));
jest.mock("../../../src/settings/SettingsStore", () => ({ vi.mock("../settings/SettingsStore", () => ({
getValue: jest.fn(), default: {
monitorSetting: jest.fn(), getValue: vi.fn(),
watchSetting: jest.fn(), monitorSetting: vi.fn(),
watchSetting: vi.fn(),
},
})); }));
const mockPromptBeforeInviteUnknownUsers = (value: boolean) => { const mockPromptBeforeInviteUnknownUsers = (value: boolean) => {
mocked(SettingsStore.getValue).mockImplementation( vi.mocked(SettingsStore.getValue).mockImplementation(
(settingName: string, roomId: string, _excludeDefault = false): any => { (settingName: string, roomId?: string | null, _excludeDefault = false): any => {
if (settingName === "promptBeforeInviteUnknownUsers" && roomId === ROOMID) { if (settingName === "promptBeforeInviteUnknownUsers" && roomId === ROOMID) {
return value; return value;
} }
@@ -55,12 +61,14 @@ const mockPromptBeforeInviteUnknownUsers = (value: boolean) => {
}; };
const mockCreateTrackedDialog = (callbackName: "onInviteAnyways" | "onGiveUp") => { const mockCreateTrackedDialog = (callbackName: "onInviteAnyways" | "onGiveUp") => {
mocked(Modal.createDialog).mockImplementation((Element: ComponentType, props?: ComponentProps<ComponentType>) => { vi.mocked(Modal.createDialog).mockImplementation(
if (Element === AskInviteAnywayDialog) { (Element: ComponentType, props?: ComponentProps<ComponentType>) => {
(props as ComponentProps<typeof AskInviteAnywayDialog>)[callbackName](); if (Element === AskInviteAnywayDialog) {
} (props as ComponentProps<typeof AskInviteAnywayDialog>)[callbackName]();
return { close: jest.fn(), finished: new Promise(() => {}) }; }
}); return { close: vi.fn(), finished: new Promise(() => {}) };
},
);
}; };
const expectAllInvitedResult = (result: CompletionStates) => { const expectAllInvitedResult = (result: CompletionStates) => {
@@ -72,34 +80,34 @@ const expectAllInvitedResult = (result: CompletionStates) => {
}; };
describe("MultiInviter", () => { describe("MultiInviter", () => {
let client: jest.Mocked<MatrixClient>; let client: Mocked<MatrixClient>;
let inviter: MultiInviter; let inviter: MultiInviter;
beforeEach(() => { beforeEach(() => {
jest.resetAllMocks(); vi.resetAllMocks();
mocked(Modal.createDialog).mockReturnValue({ close: jest.fn(), finished: new Promise(() => {}) }); vi.mocked(Modal.createDialog).mockReturnValue({ close: vi.fn(), finished: new Promise(() => {}) });
TestUtilsMatrix.stubClient(); TestUtilsMatrix.stubClient();
client = MatrixClientPeg.safeGet() as jest.Mocked<MatrixClient>; client = vi.mocked(MatrixClientPeg.safeGet());
client.invite = jest.fn(); client.invite = vi.fn();
client.invite.mockResolvedValue({}); client.invite.mockResolvedValue({});
client.getProfileInfo = jest.fn(); client.getProfileInfo = vi.fn();
client.getProfileInfo.mockImplementation(async (userId: string) => { client.getProfileInfo.mockImplementation(async (userId: string) => {
const m = MXID_PROFILE_STATES[userId]; const m = MXID_PROFILE_STATES[userId];
if (m) return m(); if (m) return m();
throw new Error(); throw new Error();
}); });
client.unban = jest.fn(); client.unban = vi.fn();
inviter = new MultiInviter(client, ROOMID); inviter = new MultiInviter(client, ROOMID);
}); });
describe("invite", () => { describe("invite", () => {
it("should show a progress dialog while the invite happens", async () => { it("should show a progress dialog while the invite happens", async () => {
const mockModalHandle = { close: jest.fn(), finished: new Promise<[]>(() => {}) }; const mockModalHandle = { close: vi.fn(), finished: new Promise<[]>(() => {}) };
mocked(Modal.createDialog).mockReturnValue(mockModalHandle); vi.mocked(Modal.createDialog).mockReturnValue(mockModalHandle);
const invitePromise = Promise.withResolvers<{}>(); const invitePromise = Promise.withResolvers<{}>();
client.invite.mockReturnValue(invitePromise.promise); client.invite.mockReturnValue(invitePromise.promise);
@@ -163,7 +171,7 @@ describe("MultiInviter", () => {
}); });
it("should show sensible error when attempting 3pid invite with no identity server", async () => { it("should show sensible error when attempting 3pid invite with no identity server", async () => {
client.inviteByEmail = jest.fn().mockRejectedValueOnce( client.inviteByEmail = vi.fn().mockRejectedValueOnce(
new MatrixError({ new MatrixError({
errcode: "ORG.MATRIX.JSSDK_MISSING_PARAM", errcode: "ORG.MATRIX.JSSDK_MISSING_PARAM",
}), }),
@@ -175,7 +183,7 @@ describe("MultiInviter", () => {
}); });
it("should ask if user wants to unban user if they have permission", async () => { it("should ask if user wants to unban user if they have permission", async () => {
mocked(Modal.createDialog).mockImplementation( vi.mocked(Modal.createDialog).mockImplementation(
(Element: ComponentType, props?: ComponentProps<ComponentType>): any => { (Element: ComponentType, props?: ComponentProps<ComponentType>): any => {
// We stub out the modal with an immediate affirmative (proceed) return // We stub out the modal with an immediate affirmative (proceed) return
return { finished: Promise.resolve([true]) }; return { finished: Promise.resolve([true]) };
@@ -183,7 +191,7 @@ describe("MultiInviter", () => {
); );
const room = new Room(ROOMID, client, client.getSafeUserId()); const room = new Room(ROOMID, client, client.getSafeUserId());
mocked(client.getRoom).mockReturnValue(room); vi.mocked(client.getRoom).mockReturnValue(room);
const ourMember = new RoomMember(ROOMID, client.getSafeUserId()); const ourMember = new RoomMember(ROOMID, client.getSafeUserId());
ourMember.membership = KnownMembership.Join; ourMember.membership = KnownMembership.Join;
ourMember.powerLevel = 100; ourMember.powerLevel = 100;
@@ -206,7 +214,7 @@ describe("MultiInviter", () => {
}); });
it("should show sensible error when attempting to invite over federation with m.federate=false", async () => { it("should show sensible error when attempting to invite over federation with m.federate=false", async () => {
mocked(client.invite).mockRejectedValueOnce( vi.mocked(client.invite).mockRejectedValueOnce(
new MatrixError({ new MatrixError({
errcode: "M_FORBIDDEN", errcode: "M_FORBIDDEN",
}), }),
@@ -222,7 +230,7 @@ describe("MultiInviter", () => {
room_id: ROOMID, room_id: ROOMID,
}), }),
]); ]);
mocked(client.getRoom).mockReturnValue(room); vi.mocked(client.getRoom).mockReturnValue(room);
await inviter.invite(["@user:other_server"]); await inviter.invite(["@user:other_server"]);
expect(inviter.getErrorText("@user:other_server")).toMatchInlineSnapshot( expect(inviter.getErrorText("@user:other_server")).toMatchInlineSnapshot(
@@ -231,7 +239,7 @@ describe("MultiInviter", () => {
}); });
it("should show sensible error when attempting to invite over federation with m.federate=false to space", async () => { it("should show sensible error when attempting to invite over federation with m.federate=false to space", async () => {
mocked(client.invite).mockRejectedValueOnce( vi.mocked(client.invite).mockRejectedValueOnce(
new MatrixError({ new MatrixError({
errcode: "M_FORBIDDEN", errcode: "M_FORBIDDEN",
}), }),
@@ -248,7 +256,7 @@ describe("MultiInviter", () => {
room_id: ROOMID, room_id: ROOMID,
}), }),
]); ]);
mocked(client.getRoom).mockReturnValue(room); vi.mocked(client.getRoom).mockReturnValue(room);
await inviter.invite(["@user:other_server"]); await inviter.invite(["@user:other_server"]);
expect(inviter.getErrorText("@user:other_server")).toMatchInlineSnapshot( expect(inviter.getErrorText("@user:other_server")).toMatchInlineSnapshot(
@@ -5,21 +5,22 @@ Copyright 2023 Boluwatife Omosowon <boluomosowon@gmail.com>
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 { mocked } from "jest-mock";
import { parsePermalink } from "../../../src/utils/permalinks/Permalinks"; import { vi, describe, it, expect } from "vitest";
import { transformSearchTerm } from "../../../src/utils/SearchInput";
jest.mock("../../../src/utils/permalinks/Permalinks"); import { parsePermalink } from "./permalinks/Permalinks";
jest.mock("../../../src/stores/WidgetStore"); import { transformSearchTerm } from "./SearchInput";
jest.mock("../../../src/stores/widgets/WidgetLayoutStore");
vi.mock("./permalinks/Permalinks");
vi.mock("../stores/WidgetStore");
vi.mock("../stores/widgets/WidgetLayoutStore");
describe("transforming search term", () => { describe("transforming search term", () => {
it("should return the primaryEntityId if the search term was a permalink", () => { it("should return the primaryEntityId if the search term was a permalink", () => {
const roomLink = "https://matrix.to/#/#element-dev:matrix.org"; const roomLink = "https://matrix.to/#/#element-dev:matrix.org";
const parsedPermalink = "#element-dev:matrix.org"; const parsedPermalink = "#element-dev:matrix.org";
mocked(parsePermalink).mockReturnValue({ vi.mocked(parsePermalink).mockReturnValue({
primaryEntityId: parsedPermalink, primaryEntityId: parsedPermalink,
roomIdOrAlias: parsedPermalink, roomIdOrAlias: parsedPermalink,
eventId: "", eventId: "",
@@ -33,7 +34,7 @@ describe("transforming search term", () => {
it("should return the original search term if the search term is a permalink and the primaryEntityId is null", () => { it("should return the original search term if the search term is a permalink and the primaryEntityId is null", () => {
const searchTerm = "https://matrix.to/#/#random-link:matrix.org"; const searchTerm = "https://matrix.to/#/#random-link:matrix.org";
mocked(parsePermalink).mockReturnValue({ vi.mocked(parsePermalink).mockReturnValue({
primaryEntityId: null, primaryEntityId: null,
roomIdOrAlias: null, roomIdOrAlias: null,
eventId: null, eventId: null,
@@ -46,7 +47,7 @@ describe("transforming search term", () => {
it("should return the original search term if the search term was not a permalink", () => { it("should return the original search term if the search term was not a permalink", () => {
const searchTerm = "search term"; const searchTerm = "search term";
mocked(parsePermalink).mockReturnValue(null); vi.mocked(parsePermalink).mockReturnValue(null);
expect(transformSearchTerm(searchTerm)).toBe(searchTerm); expect(transformSearchTerm(searchTerm)).toBe(searchTerm);
}); });
}); });
@@ -6,11 +6,12 @@ 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 { vi, describe, it, expect, beforeAll, afterAll } from "vitest";
import { type MatrixClient, type Room } from "matrix-js-sdk/src/matrix"; import { type MatrixClient, type Room } from "matrix-js-sdk/src/matrix";
import { UserVerificationStatus } from "matrix-js-sdk/src/crypto-api"; import { UserVerificationStatus } from "matrix-js-sdk/src/crypto-api";
import { shieldStatusForRoom } from "../../../src/utils/ShieldUtils"; import { shieldStatusForRoom } from "./ShieldUtils";
import DMRoomMap from "../../../src/utils/DMRoomMap"; import DMRoomMap from "./DMRoomMap";
function mkClient(selfTrust = false) { function mkClient(selfTrust = false) {
return { return {
@@ -30,13 +31,13 @@ function mkClient(selfTrust = false) {
} }
describe("mkClient self-test", function () { describe("mkClient self-test", function () {
test.each([true, false])("behaves well for self-trust=%s", async (v) => { it.each([true, false])("behaves well for self-trust=%s", async (v) => {
const client = mkClient(v); const client = mkClient(v);
const status = await client.getCrypto()!.getDeviceVerificationStatus("@self:localhost", "DEVICE"); const status = await client.getCrypto()!.getDeviceVerificationStatus("@self:localhost", "DEVICE");
expect(status?.isVerified()).toBe(v); expect(status?.isVerified()).toBe(v);
}); });
test.each([ it.each([
["@TT:h", true], ["@TT:h", true],
["@TF:h", true], ["@TF:h", true],
["@FT:h", false], ["@FT:h", false],
@@ -46,7 +47,7 @@ describe("mkClient self-test", function () {
expect(status!.isCrossSigningVerified()).toBe(trust); expect(status!.isCrossSigningVerified()).toBe(trust);
}); });
test.each([ it.each([
["@TT:h", true], ["@TT:h", true],
["@TF:h", false], ["@TF:h", false],
["@FT:h", true], ["@FT:h", true],
@@ -62,11 +63,11 @@ describe("shieldStatusForMembership self-trust behaviour", function () {
const mockInstance = { const mockInstance = {
getUserIdForRoomId: (roomId: string) => (roomId === "DM" ? "@any:h" : null), getUserIdForRoomId: (roomId: string) => (roomId === "DM" ? "@any:h" : null),
} as unknown as DMRoomMap; } as unknown as DMRoomMap;
jest.spyOn(DMRoomMap, "shared").mockReturnValue(mockInstance); vi.spyOn(DMRoomMap, "shared").mockReturnValue(mockInstance);
}); });
afterAll(() => { afterAll(() => {
jest.spyOn(DMRoomMap, "shared").mockRestore(); vi.spyOn(DMRoomMap, "shared").mockRestore();
}); });
it.each([ it.each([
@@ -165,7 +166,7 @@ describe("shieldStatusForMembership other-trust behaviour", function () {
const mockInstance = { const mockInstance = {
getUserIdForRoomId: (roomId: string) => (roomId === "DM" ? "@any:h" : null), getUserIdForRoomId: (roomId: string) => (roomId === "DM" ? "@any:h" : null),
} as unknown as DMRoomMap; } as unknown as DMRoomMap;
jest.spyOn(DMRoomMap, "shared").mockReturnValue(mockInstance); vi.spyOn(DMRoomMap, "shared").mockReturnValue(mockInstance);
}); });
it.each([ it.each([
@@ -7,8 +7,10 @@ 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 WidgetUtils from "../../../src/utils/WidgetUtils"; import { describe, it, expect, beforeEach } from "vitest";
import { mockPlatformPeg } from "../../test-utils"; import { mockPlatformPeg } from "test-utils/platform";
import WidgetUtils from "./WidgetUtils";
describe("getLocalJitsiWrapperUrl", () => { describe("getLocalJitsiWrapperUrl", () => {
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[`AutoDiscoveryUtils authComponentStateForError should return expected error for the registration page 1`] = ` exports[`AutoDiscoveryUtils > authComponentStateForError > should return expected error for the registration page 1`] = `
{ {
"serverDeadError": <div> "serverDeadError": <div>
<strong> <strong>
@@ -6,6 +6,9 @@ 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 { vi, describe, it, expect, beforeEach, afterEach, type Mocked } from "vitest";
import { import {
type MatrixClient, type MatrixClient,
type MatrixEvent, type MatrixEvent,
@@ -15,18 +18,17 @@ import {
RoomStateEvent, RoomStateEvent,
} from "matrix-js-sdk/src/matrix"; } from "matrix-js-sdk/src/matrix";
import { KnownMembership } from "matrix-js-sdk/src/types"; import { KnownMembership } from "matrix-js-sdk/src/types";
import { mocked } from "jest-mock"; import { createTestClient, mkRoomMember, stubClient } from "test-utils";
import { isKnockDenied, waitForMember } from "../../../src/utils/membership"; import { isKnockDenied, waitForMember } from "./membership";
import { createTestClient, mkRoomMember, stubClient } from "../../test-utils";
describe("isKnockDenied", () => { describe("isKnockDenied", () => {
const userId = "alice"; const userId = "alice";
let client: jest.Mocked<MatrixClient>; let client: Mocked<MatrixClient>;
let room: Room; let room: Room;
beforeEach(() => { beforeEach(() => {
client = stubClient() as jest.Mocked<MatrixClient>; client = vi.mocked(stubClient());
room = new Room("!room-id:example.com", client, "@user:example.com"); room = new Room("!room-id:example.com", client, "@user:example.com");
}); });
@@ -34,7 +36,7 @@ describe("isKnockDenied", () => {
const roomMember = mkRoomMember(room.roomId, userId, KnownMembership.Leave, true, { const roomMember = mkRoomMember(room.roomId, userId, KnownMembership.Leave, true, {
membership: KnownMembership.Knock, membership: KnownMembership.Knock,
}); });
jest.spyOn(room, "getMember").mockReturnValue(roomMember); vi.spyOn(room, "getMember").mockReturnValue(roomMember);
expect(isKnockDenied(room)).toBe(true); expect(isKnockDenied(room)).toBe(true);
}); });
@@ -45,7 +47,7 @@ describe("isKnockDenied", () => {
{ membership: KnownMembership.Leave, isKicked: true, prevMembership: KnownMembership.Join }, { membership: KnownMembership.Leave, isKicked: true, prevMembership: KnownMembership.Join },
])("checks that the user knock has been not denied", ({ membership, isKicked, prevMembership }) => { ])("checks that the user knock has been not denied", ({ membership, isKicked, prevMembership }) => {
const roomMember = mkRoomMember(room.roomId, userId, membership, isKicked, { membership: prevMembership }); const roomMember = mkRoomMember(room.roomId, userId, membership, isKicked, { membership: prevMembership });
jest.spyOn(room, "getMember").mockReturnValue(roomMember); vi.spyOn(room, "getMember").mockReturnValue(roomMember);
expect(isKnockDenied(room)).toBe(false); expect(isKnockDenied(room)).toBe(false);
}); });
}); });
@@ -64,17 +66,17 @@ describe("waitForMember", () => {
// getRoom() only knows about !stub_room, which has only one member // getRoom() only knows about !stub_room, which has only one member
const stubRoom = { const stubRoom = {
getMember: jest.fn().mockImplementation((userId) => { getMember: vi.fn().mockImplementation((userId) => {
return userId === STUB_MEMBER_ID ? ({} as RoomMember) : null; return userId === STUB_MEMBER_ID ? ({} as RoomMember) : null;
}), }),
}; };
mocked(client.getRoom).mockImplementation((roomId) => { vi.mocked(client.getRoom).mockImplementation((roomId) => {
return roomId === STUB_ROOM_ID ? (stubRoom as unknown as Room) : null; return roomId === STUB_ROOM_ID ? (stubRoom as unknown as Room) : null;
}); });
}); });
afterEach(() => { afterEach(() => {
jest.useRealTimers(); vi.useRealTimers();
}); });
it("resolves with false if the timeout is reached", async () => { it("resolves with false if the timeout is reached", async () => {
@@ -83,11 +85,11 @@ describe("waitForMember", () => {
}); });
it("resolves with false if the timeout is reached, even if other RoomState.newMember events fire", async () => { it("resolves with false if the timeout is reached, even if other RoomState.newMember events fire", async () => {
jest.useFakeTimers(); vi.useFakeTimers();
const roomId = "!roomId:domain"; const roomId = "!roomId:domain";
const userId = "@clientId:domain"; const userId = "@clientId:domain";
const resultProm = waitForMember(client, roomId, userId, { timeout }); const resultProm = waitForMember(client, roomId, userId, { timeout });
jest.advanceTimersByTime(50); vi.advanceTimersByTime(50);
expect(await resultProm).toBe(false); expect(await resultProm).toBe(false);
client.emit( client.emit(
RoomStateEvent.NewMember, RoomStateEvent.NewMember,
@@ -98,7 +100,7 @@ describe("waitForMember", () => {
userId: "@anotherClient:domain", userId: "@anotherClient:domain",
} as RoomMember, } as RoomMember,
); );
jest.useRealTimers(); vi.useRealTimers();
}); });
it("resolves with true if RoomState.newMember fires", async () => { it("resolves with true if RoomState.newMember fires", async () => {
@@ -115,7 +117,7 @@ describe("waitForMember", () => {
}); });
it("resolves immediately if the user is already a member", async () => { it("resolves immediately if the user is already a member", async () => {
jest.useFakeTimers(); vi.useFakeTimers();
const resultProm = waitForMember(client, STUB_ROOM_ID, STUB_MEMBER_ID, { timeout }); const resultProm = waitForMember(client, STUB_ROOM_ID, STUB_MEMBER_ID, { timeout });
expect(await resultProm).toBe(true); expect(await resultProm).toBe(true);
}); });
+1 -1
View File
@@ -36,7 +36,7 @@ const SETTINGS_FILE_RELATIVE = path.relative(ROOT, SETTINGS_FILE);
// search terms, but keep this list as a manual escape hatch for cases the heuristic can't // search terms, but keep this list as a manual escape hatch for cases the heuristic can't
// see (e.g. usage mediated through a helper function rather than a literal reference). // see (e.g. usage mediated through a helper function rather than a literal reference).
const KNOWN_USED_OVERRIDES = new Set<string>([ const KNOWN_USED_OVERRIDES = new Set<string>([
// e.g. "someSettingName", "test_setting", // only used in tests
]); ]);
interface DeclaredSetting { interface DeclaredSetting {