diff --git a/apps/web/test/viewmodels/menus/UserMenuViewModel-test.ts b/apps/web/src/viewmodels/menus/UserMenuViewModel.test.ts similarity index 83% rename from apps/web/test/viewmodels/menus/UserMenuViewModel-test.ts rename to apps/web/src/viewmodels/menus/UserMenuViewModel.test.ts index 8bcc763651..2dd2db97ab 100644 --- a/apps/web/test/viewmodels/menus/UserMenuViewModel-test.ts +++ b/apps/web/src/viewmodels/menus/UserMenuViewModel.test.ts @@ -4,21 +4,24 @@ * 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 { MatrixError, type MatrixClient } from "matrix-js-sdk/src/matrix"; -import { waitFor } from "jest-matrix-react"; -import type { MockedObject } from "jest-mock-vitest-adapter"; -import { UserMenuViewModel } from "../../../src/viewmodels/menus/UserMenuViewModel"; -import { getMockClientWithEventEmitter, mockClientMethodsServer, mockClientMethodsUser } from "../../test-utils"; -import { MatrixDispatcher } from "../../../src/dispatcher/dispatcher"; -import { SDKContextClass } from "../../../src/contexts/SDKContextClass"; -import SdkConfig from "../../../src/SdkConfig"; -import { Action } from "../../../src/dispatcher/actions"; -import { UserTab } from "../../../src/components/views/dialogs/UserTab"; -import Modal from "../../../src/Modal"; -import FeedbackDialog from "../../../src/components/views/dialogs/FeedbackDialog"; -import { type OwnProfileStore } from "../../../src/stores/OwnProfileStore"; -import { TestSDKContext } from "../../unit-tests/TestSDKContext.ts"; +// @vitest-environment happy-dom + +import { MatrixError, type MatrixClient } from "matrix-js-sdk/src/matrix"; +import { vi, describe, it, expect, beforeEach, afterEach, type MockedObject } from "vitest"; +import { waitFor } from "test-utils-rtl"; +import { getMockClientWithEventEmitter, mockClientMethodsServer, mockClientMethodsUser } from "test-utils"; + +import { UserMenuViewModel } from "./UserMenuViewModel"; +import { MatrixDispatcher } from "../../dispatcher/dispatcher"; +import { SDKContextClass } from "../../contexts/SDKContextClass"; +import SdkConfig from "../../SdkConfig"; +import { Action } from "../../dispatcher/actions"; +import { UserTab } from "../../components/views/dialogs/UserTab"; +import Modal from "../../Modal"; +import FeedbackDialog from "../../components/views/dialogs/FeedbackDialog"; +import { type OwnProfileStore } from "../../stores/OwnProfileStore"; +import { TestSDKContext } from "../../../test/unit-tests/TestSDKContext.ts"; describe("UserMenuViewModel", () => { let dispatcher: MatrixDispatcher; @@ -31,9 +34,9 @@ describe("UserMenuViewModel", () => { client = getMockClientWithEventEmitter({ ...mockClientMethodsUser(), ...mockClientMethodsServer(), - getAuthMetadata: jest.fn().mockRejectedValue(new MatrixError({ errcode: "M_UNRECOGNIZED" }, 404)), - getExtendedProfileProperty: jest.fn().mockResolvedValue(undefined), - setExtendedProfileProperty: jest.fn().mockResolvedValue(undefined), + getAuthMetadata: vi.fn().mockRejectedValue(new MatrixError({ errcode: "M_UNRECOGNIZED" }, 404)), + getExtendedProfileProperty: vi.fn().mockResolvedValue(undefined), + setExtendedProfileProperty: vi.fn().mockResolvedValue(undefined), }); sdkContext = new TestSDKContext(); // @ts-ignore UserMenuViewModel uses SDKContext in the constructor @@ -43,12 +46,12 @@ describe("UserMenuViewModel", () => { mockOwnProfileStore = { displayName: "Sally Sanderson", userStatus: undefined, - getHttpAvatarUrl: jest.fn().mockReturnValue("https://foo.dummy/avatar.png"), - on: jest.fn(), + getHttpAvatarUrl: vi.fn().mockReturnValue("https://foo.dummy/avatar.png"), + on: vi.fn(), } as unknown as OwnProfileStore; }); afterEach(() => { - jest.resetAllMocks(); + vi.resetAllMocks(); SdkConfig.reset(); SDKContextClass.instance.onLoggedOut(); }); @@ -114,7 +117,7 @@ describe("UserMenuViewModel", () => { it("can open the home menu", async () => { SdkConfig.put({ embedded_pages: { home_url: "https://example.org" } }); const vm = new UserMenuViewModel({ ownProfileStore: mockOwnProfileStore }, dispatcher, client, true); - const dispatcherSpy = jest.fn(); + const dispatcherSpy = vi.fn(); dispatcher.register(dispatcherSpy); vm.setOpen(true); vm.openHomePage(); @@ -127,7 +130,7 @@ describe("UserMenuViewModel", () => { it("can open the 'link new device' settings menu", async () => { const vm = new UserMenuViewModel({ ownProfileStore: mockOwnProfileStore }, dispatcher, client, true); - const dispatcherSpy = jest.fn(); + const dispatcherSpy = vi.fn(); dispatcher.register(dispatcherSpy); vm.setOpen(true); vm.linkNewDevice(); @@ -142,7 +145,7 @@ describe("UserMenuViewModel", () => { it("can open the 'security' settings menu", async () => { const vm = new UserMenuViewModel({ ownProfileStore: mockOwnProfileStore }, dispatcher, client, true); - const dispatcherSpy = jest.fn(); + const dispatcherSpy = vi.fn(); dispatcher.register(dispatcherSpy); vm.setOpen(true); vm.openSecurity(); @@ -155,10 +158,10 @@ describe("UserMenuViewModel", () => { }); it("can open the 'feedback' settings menu", async () => { - jest.spyOn(Modal, "createDialog"); + vi.spyOn(Modal, "createDialog"); SdkConfig.put({ bug_report_endpoint_url: "https://example.org" }); const vm = new UserMenuViewModel({ ownProfileStore: mockOwnProfileStore }, dispatcher, client, true); - const dispatcherSpy = jest.fn(); + const dispatcherSpy = vi.fn(); dispatcher.register(dispatcherSpy); vm.setOpen(true); vm.openFeedback(); @@ -167,7 +170,7 @@ describe("UserMenuViewModel", () => { it("can open the settings menu", async () => { const vm = new UserMenuViewModel({ ownProfileStore: mockOwnProfileStore }, dispatcher, client, true); - const dispatcherSpy = jest.fn(); + const dispatcherSpy = vi.fn(); dispatcher.register(dispatcherSpy); vm.setOpen(true); vm.openSettings(); @@ -190,7 +193,7 @@ describe("UserMenuViewModel", () => { it("should be able to open the createAccount screen as a guest", async () => { client.isGuest.mockReturnValue(true); - const dispatcherSpy = jest.fn(); + const dispatcherSpy = vi.fn(); dispatcher.register(dispatcherSpy); const vm = new UserMenuViewModel({ ownProfileStore: mockOwnProfileStore }, dispatcher, client, true); vm.setOpen(true); @@ -204,7 +207,7 @@ describe("UserMenuViewModel", () => { it("should be able to open the onSignIn screen as a guest", async () => { client.isGuest.mockReturnValue(true); - const dispatcherSpy = jest.fn(); + const dispatcherSpy = vi.fn(); dispatcher.register(dispatcherSpy); const vm = new UserMenuViewModel({ ownProfileStore: mockOwnProfileStore }, dispatcher, client, true); vm.setOpen(true); diff --git a/apps/web/test/viewmodels/message-body/EditHistoryActionBarViewModel-test.ts b/apps/web/src/viewmodels/message-body/EditHistoryActionBarViewModel.test.ts similarity index 90% rename from apps/web/test/viewmodels/message-body/EditHistoryActionBarViewModel-test.ts rename to apps/web/src/viewmodels/message-body/EditHistoryActionBarViewModel.test.ts index 388e27635a..da38e53cae 100644 --- a/apps/web/test/viewmodels/message-body/EditHistoryActionBarViewModel-test.ts +++ b/apps/web/src/viewmodels/message-body/EditHistoryActionBarViewModel.test.ts @@ -5,9 +5,12 @@ * Please see LICENSE files in the repository root for full details. */ -import { ActionBarAction } from "@element-hq/web-shared-components"; +// @vitest-environment happy-dom -import { EditHistoryActionBarViewModel } from "../../../src/viewmodels/message-body/EditHistoryActionBarViewModel"; +import { ActionBarAction } from "@element-hq/web-shared-components"; +import { vi, describe, it, expect } from "vitest"; + +import { EditHistoryActionBarViewModel } from "./EditHistoryActionBarViewModel"; describe("EditHistoryActionBarViewModel", () => { it("builds a label snapshot with remove and view source actions", () => { @@ -53,7 +56,7 @@ describe("EditHistoryActionBarViewModel", () => { }); it("forwards remove clicks to props", () => { - const onRemoveClick = jest.fn(); + const onRemoveClick = vi.fn(); const vm = new EditHistoryActionBarViewModel({ canRemove: true, showViewSource: false, @@ -67,7 +70,7 @@ describe("EditHistoryActionBarViewModel", () => { }); it("forwards view source clicks to props", () => { - const onViewSourceClick = jest.fn(); + const onViewSourceClick = vi.fn(); const vm = new EditHistoryActionBarViewModel({ canRemove: false, showViewSource: true, diff --git a/apps/web/test/viewmodels/message-body/EventContentBodyViewModel-test.ts b/apps/web/src/viewmodels/message-body/EventContentBodyViewModel.test.ts similarity index 83% rename from apps/web/test/viewmodels/message-body/EventContentBodyViewModel-test.ts rename to apps/web/src/viewmodels/message-body/EventContentBodyViewModel.test.ts index af03d7d1bc..454f06d7f9 100644 --- a/apps/web/test/viewmodels/message-body/EventContentBodyViewModel-test.ts +++ b/apps/web/src/viewmodels/message-body/EventContentBodyViewModel.test.ts @@ -5,15 +5,15 @@ * Please see LICENSE files in the repository root for full details. */ +// @vitest-environment happy-dom + import { MsgType, PushRuleKind, type MatrixEvent, type Room } from "matrix-js-sdk/src/matrix"; import { type JSX } from "react"; +import { vi, describe, it, expect, beforeEach } from "vitest"; +import { stubClient, mkStubRoom, mkEvent } from "test-utils"; -import { - EventContentBodyViewModel, - type EventContentBodyViewModelProps, -} from "../../../src/viewmodels/message-body/EventContentBodyViewModel"; -import { stubClient, mkStubRoom, mkEvent } from "../../test-utils"; -import { bodyToNode } from "../../../src/HtmlUtils"; +import { EventContentBodyViewModel, type EventContentBodyViewModelProps } from "./EventContentBodyViewModel"; +import { bodyToNode } from "../../HtmlUtils"; import { combineRenderers, mentionPillRenderer, @@ -21,35 +21,37 @@ import { ambiguousLinkTooltipRenderer, spoilerRenderer, codeBlockRenderer, -} from "../../../src/renderer"; -import PlatformPeg from "../../../src/PlatformPeg"; -import type BasePlatform from "../../../src/BasePlatform"; -import SettingsStore from "../../../src/settings/SettingsStore"; +} from "../../renderer"; +import PlatformPeg from "../../PlatformPeg"; +import type BasePlatform from "../../BasePlatform"; +import SettingsStore from "../../settings/SettingsStore"; -jest.mock("../../../src/HtmlUtils", () => ({ - ...jest.requireActual("../../../src/HtmlUtils"), - bodyToNode: jest.fn(), +vi.mock("../../HtmlUtils", async () => ({ + ...(await vi.importActual("../../HtmlUtils")), + bodyToNode: vi.fn(), })); -jest.mock("../../../src/renderer", () => ({ - combineRenderers: jest.fn(), - mentionPillRenderer: jest.fn(), - keywordPillRenderer: jest.fn(), - ambiguousLinkTooltipRenderer: jest.fn(), - codeBlockRenderer: jest.fn(), - spoilerRenderer: jest.fn(), +vi.mock("../../renderer", () => ({ + combineRenderers: vi.fn(), + mentionPillRenderer: vi.fn(), + keywordPillRenderer: vi.fn(), + ambiguousLinkTooltipRenderer: vi.fn(), + codeBlockRenderer: vi.fn(), + spoilerRenderer: vi.fn(), })); -jest.mock("../../../src/PlatformPeg", () => ({ +vi.mock("../../PlatformPeg", () => ({ __esModule: true, default: { - get: jest.fn(), + get: vi.fn(), + // Never resolves, matching the real PlatformPeg's behaviour when no platform has been `set()`. + platformPromise: new Promise(() => {}), }, })); -const mockedBodyToNode = jest.mocked(bodyToNode); -const mockedCombineRenderers = jest.mocked(combineRenderers); -const mockedPlatformPeg = jest.mocked(PlatformPeg); +const mockedBodyToNode = vi.mocked(bodyToNode); +const mockedCombineRenderers = vi.mocked(combineRenderers); +const mockedPlatformPeg = vi.mocked(PlatformPeg); describe("EventContentBodyViewModel", () => { const defaultContent = { @@ -73,7 +75,7 @@ describe("EventContentBodyViewModel", () => { }); it("passes render options to bodyToNode", () => { - const replacer = jest.fn(); + const replacer = vi.fn(); mockedCombineRenderers.mockReturnValue(() => replacer); mockedBodyToNode.mockReturnValue({ strippedBody: "Hello world", @@ -104,8 +106,8 @@ describe("EventContentBodyViewModel", () => { }); it("initializes setting-backed options from SettingsStore when omitted", () => { - const replacer = jest.fn(); - const createReplacerFromOptions = jest.fn().mockReturnValue(replacer); + const replacer = vi.fn(); + const createReplacerFromOptions = vi.fn().mockReturnValue(replacer); mockedCombineRenderers.mockReturnValue(createReplacerFromOptions); mockedBodyToNode.mockReturnValue({ strippedBody: "Hello world", @@ -113,7 +115,7 @@ describe("EventContentBodyViewModel", () => { emojiBodyElements: undefined, className: "mx_EventTile_body", }); - const getValueSpy = jest.spyOn(SettingsStore, "getValue").mockImplementation((settingName) => { + const getValueSpy = vi.spyOn(SettingsStore, "getValue").mockImplementation((settingName) => { if (settingName === "TextualBody.enableBigEmoji") return false; if (settingName === "Pill.shouldShowPillAvatar") return false; return true; @@ -136,8 +138,8 @@ describe("EventContentBodyViewModel", () => { }); it("uses the injected client to resolve the room for renderer context", () => { - const replacer = jest.fn(); - const createReplacerFromOptions = jest.fn().mockReturnValue(replacer); + const replacer = vi.fn(); + const createReplacerFromOptions = vi.fn().mockReturnValue(replacer); mockedCombineRenderers.mockReturnValue(createReplacerFromOptions); mockedBodyToNode.mockReturnValue({ strippedBody: "Hello world", @@ -154,7 +156,7 @@ describe("EventContentBodyViewModel", () => { event: true, }); const room = mkStubRoom("!room:example.org", "Room", client) as Room; - const getRoomSpy = jest.spyOn(client, "getRoom").mockReturnValue(room); + const getRoomSpy = vi.spyOn(client, "getRoom").mockReturnValue(room); new EventContentBodyViewModel(defaultProps({ mxEvent, client })); @@ -163,7 +165,7 @@ describe("EventContentBodyViewModel", () => { }); it("forces disableBigEmoji for emote events", () => { - const replacer = jest.fn(); + const replacer = vi.fn(); mockedCombineRenderers.mockReturnValue(() => replacer); mockedBodyToNode.mockReturnValue({ strippedBody: "Emote", @@ -190,7 +192,7 @@ describe("EventContentBodyViewModel", () => { }); it("uses parse when formattedBody is provided", () => { - const replacer = jest.fn(); + const replacer = vi.fn(); mockedCombineRenderers.mockReturnValue(() => replacer); mockedBodyToNode.mockReturnValue({ strippedBody: "Hello world", @@ -209,7 +211,7 @@ describe("EventContentBodyViewModel", () => { }); it("uses emojiBodyElements when provided", () => { - const replacer = jest.fn(); + const replacer = vi.fn(); mockedCombineRenderers.mockReturnValue(() => replacer); const emojiElements = ["emoji"] as unknown as JSX.Element[]; mockedBodyToNode.mockReturnValue({ @@ -226,7 +228,7 @@ describe("EventContentBodyViewModel", () => { }); it("sets dir to auto for div elements even when includeDir is false", () => { - const replacer = jest.fn(); + const replacer = vi.fn(); mockedCombineRenderers.mockReturnValue(() => replacer); mockedBodyToNode.mockReturnValue({ strippedBody: "Hello world", @@ -241,7 +243,7 @@ describe("EventContentBodyViewModel", () => { }); it("omits dir when includeDir is false on span elements", () => { - const replacer = jest.fn(); + const replacer = vi.fn(); mockedCombineRenderers.mockReturnValue(() => replacer); mockedBodyToNode.mockReturnValue({ strippedBody: "Hello world", @@ -256,7 +258,7 @@ describe("EventContentBodyViewModel", () => { }); it("updates snapshot when setEventContent changes content", () => { - const replacer = jest.fn(); + const replacer = vi.fn(); mockedCombineRenderers.mockReturnValue(() => replacer); mockedBodyToNode.mockReturnValue({ strippedBody: "Initial", @@ -281,7 +283,7 @@ describe("EventContentBodyViewModel", () => { }); it("doesn't emit updates when setters are called with unchanged values", () => { - const replacer = jest.fn(); + const replacer = vi.fn(); mockedCombineRenderers.mockReturnValue(() => replacer); mockedBodyToNode.mockReturnValue({ strippedBody: "Initial", @@ -292,7 +294,7 @@ describe("EventContentBodyViewModel", () => { const vm = new EventContentBodyViewModel(defaultProps()); const previousSnapshot = vm.getSnapshot(); - const subscriber = jest.fn(); + const subscriber = vi.fn(); vm.subscribe(subscriber); vm.setEventContent(undefined, defaultContent); @@ -303,7 +305,7 @@ describe("EventContentBodyViewModel", () => { }); it("includes renderers based on options and platform capabilities", () => { - const replacer = jest.fn(); + const replacer = vi.fn(); mockedCombineRenderers.mockReturnValue(() => replacer); mockedBodyToNode.mockReturnValue({ strippedBody: "Hello world", @@ -321,14 +323,14 @@ describe("EventContentBodyViewModel", () => { content: defaultContent, event: true, }); - jest.spyOn(mxEvent, "getPushDetails").mockReturnValue({ + vi.spyOn(mxEvent, "getPushDetails").mockReturnValue({ rule: { enabled: true, kind: PushRuleKind.ContentSpecific, pattern: "Hello", }, } as unknown as ReturnType); - jest.spyOn(client, "getRoom").mockReturnValue(mkStubRoom("!room:example.org", "Room", client) as Room); + vi.spyOn(client, "getRoom").mockReturnValue(mkStubRoom("!room:example.org", "Room", client) as Room); new EventContentBodyViewModel( defaultProps({ @@ -351,7 +353,7 @@ describe("EventContentBodyViewModel", () => { }); it("skips tooltip renderer when platform does not need URL tooltips", () => { - const replacer = jest.fn(); + const replacer = vi.fn(); mockedCombineRenderers.mockReturnValue(() => replacer); mockedBodyToNode.mockReturnValue({ strippedBody: "Hello world", diff --git a/apps/web/test/viewmodels/message-body/FileBodyViewModel-test.ts b/apps/web/src/viewmodels/message-body/FileBodyViewModel.test.ts similarity index 89% rename from apps/web/test/viewmodels/message-body/FileBodyViewModel-test.ts rename to apps/web/src/viewmodels/message-body/FileBodyViewModel.test.ts index bf702b6a8e..792f2b6601 100644 --- a/apps/web/test/viewmodels/message-body/FileBodyViewModel-test.ts +++ b/apps/web/src/viewmodels/message-body/FileBodyViewModel.test.ts @@ -5,27 +5,32 @@ * Please see LICENSE files in the repository root for full details. */ +// @vitest-environment happy-dom + import { EventType, MatrixEvent } from "matrix-js-sdk/src/matrix"; import { logger } from "matrix-js-sdk/src/logger"; import { createRef, type RefObject } from "react"; import { FileBodyViewInfoIcon, FileBodyViewState } from "@element-hq/web-shared-components"; +import { vi, describe, it, expect, beforeEach } from "vitest"; -import Modal from "../../../src/Modal"; -import { TimelineRenderingType } from "../../../src/contexts/RoomContext"; -import { type MediaEventHelper } from "../../../src/utils/MediaEventHelper"; -import { FileBodyViewModel } from "../../../src/viewmodels/message-body/FileBodyViewModel"; -import ErrorDialog from "../../../src/components/views/dialogs/ErrorDialog"; +import Modal from "../../Modal"; +import { TimelineRenderingType } from "../../contexts/RoomContext"; +import { type MediaEventHelper } from "../../utils/MediaEventHelper"; +import { FileBodyViewModel } from "./FileBodyViewModel"; +import ErrorDialog from "../../components/views/dialogs/ErrorDialog"; -const mockDownload = jest.fn(); +const mockDownload = vi.fn(); -jest.mock("../../../src/utils/FileDownloader", () => ({ - FileDownloader: jest.fn().mockImplementation(() => ({ - download: mockDownload, - })), +vi.mock("../../utils/FileDownloader", () => ({ + FileDownloader: vi.fn().mockImplementation(function () { + return { + download: mockDownload, + }; + }), })); -jest.mock("../../../src/customisations/Media", () => ({ - mediaFromContent: jest.fn((content: { file?: unknown; url?: string }) => ({ +vi.mock("../../customisations/Media", () => ({ + mediaFromContent: vi.fn((content: { file?: unknown; url?: string }) => ({ isEncrypted: !!content.file, srcHttp: content.url ?? null, })), @@ -75,7 +80,7 @@ describe("FileBodyViewModel", () => { }); beforeEach(() => { - jest.clearAllMocks(); + vi.clearAllMocks(); }); it("shows unencrypted download snapshot in file rendering type", () => { @@ -169,10 +174,11 @@ describe("FileBodyViewModel", () => { mxEvent: mkMediaEvent({ msgtype: "m.file", url: "https://server/direct.txt" }), }); - const click = jest.spyOn(HTMLAnchorElement.prototype, "click"); + const click = vi.spyOn(HTMLAnchorElement.prototype, "click"); + vi.spyOn(URL, "createObjectURL"); const event = { - preventDefault: jest.fn(), - stopPropagation: jest.fn(), + preventDefault: vi.fn(), + stopPropagation: vi.fn(), } as any; vm.onDownloadLinkClick(event); @@ -193,8 +199,8 @@ describe("FileBodyViewModel", () => { } as unknown as MediaEventHelper, mxEvent: mkMediaEvent({ file: { url: "mxc://server/file" } }), }); - const warnSpy = jest.spyOn(logger, "warn").mockImplementation(() => {}); - const dialogSpy = jest.spyOn(Modal, "createDialog").mockReturnValue({ close: jest.fn() } as any); + const warnSpy = vi.spyOn(logger, "warn").mockImplementation(() => {}); + const dialogSpy = vi.spyOn(Modal, "createDialog").mockReturnValue({ close: vi.fn() } as any); await vm.onDownloadClick(); diff --git a/apps/web/test/viewmodels/message-body/ImageBodyViewModel-test.ts b/apps/web/src/viewmodels/message-body/ImageBodyViewModel.test.ts similarity index 89% rename from apps/web/test/viewmodels/message-body/ImageBodyViewModel-test.ts rename to apps/web/src/viewmodels/message-body/ImageBodyViewModel.test.ts index 787b119f8f..7c562d7b5e 100644 --- a/apps/web/test/viewmodels/message-body/ImageBodyViewModel-test.ts +++ b/apps/web/src/viewmodels/message-body/ImageBodyViewModel.test.ts @@ -5,41 +5,44 @@ * Please see LICENSE files in the repository root for full details. */ +// @vitest-environment happy-dom + import { createRef, type RefObject } from "react"; import { ClientEvent, EventType, MatrixEvent, SyncState } from "matrix-js-sdk/src/matrix"; import { type Media } from "@element-hq/element-web-module-api"; import { ImageBodyViewPlaceholder, ImageBodyViewState } from "@element-hq/web-shared-components"; +import { vi, describe, it, expect, beforeEach, afterEach } from "vitest"; -import SettingsStore from "../../../src/settings/SettingsStore"; -import { ImageSize } from "../../../src/settings/enums/ImageSize"; -import { mediaFromContent } from "../../../src/customisations/Media"; -import { TimelineRenderingType } from "../../../src/contexts/RoomContext"; -import { DecryptError, DownloadError } from "../../../src/utils/DecryptFile"; -import { type MediaEventHelper } from "../../../src/utils/MediaEventHelper"; -import { ImageBodyViewModel } from "../../../src/viewmodels/message-body/ImageBodyViewModel"; -import Modal from "../../../src/Modal"; -import { MatrixClientPeg } from "../../../src/MatrixClientPeg"; -import { blobIsAnimated } from "../../../src/utils/Image"; -import { BLURHASH_FIELD, createThumbnail } from "../../../src/utils/image-media"; +import SettingsStore from "../../settings/SettingsStore"; +import { ImageSize } from "../../settings/enums/ImageSize"; +import { mediaFromContent } from "../../customisations/Media"; +import { TimelineRenderingType } from "../../contexts/RoomContext"; +import { DecryptError, DownloadError } from "../../utils/DecryptFile"; +import { type MediaEventHelper } from "../../utils/MediaEventHelper"; +import { ImageBodyViewModel } from "./ImageBodyViewModel"; +import Modal from "../../Modal"; +import { MatrixClientPeg } from "../../MatrixClientPeg"; +import { blobIsAnimated } from "../../utils/Image"; +import { BLURHASH_FIELD, createThumbnail } from "../../utils/image-media"; -jest.mock("../../../src/customisations/Media", () => ({ - mediaFromContent: jest.fn(), +vi.mock("../../customisations/Media", () => ({ + mediaFromContent: vi.fn(), })); -jest.mock("../../../src/utils/Image", () => ({ - ...jest.requireActual("../../../src/utils/Image"), - blobIsAnimated: jest.fn(), +vi.mock("../../utils/Image", async () => ({ + ...(await vi.importActual("../../utils/Image")), + blobIsAnimated: vi.fn(), })); -jest.mock("../../../src/utils/image-media", () => ({ - ...jest.requireActual("../../../src/utils/image-media"), - createThumbnail: jest.fn(), +vi.mock("../../utils/image-media", async () => ({ + ...(await vi.importActual("../../utils/image-media")), + createThumbnail: vi.fn(), })); describe("ImageBodyViewModel", () => { - const mockedMediaFromContent = jest.mocked(mediaFromContent); - const mockedBlobIsAnimated = jest.mocked(blobIsAnimated); - const mockedCreateThumbnail = jest.mocked(createThumbnail); + const mockedMediaFromContent = vi.mocked(mediaFromContent); + const mockedBlobIsAnimated = vi.mocked(blobIsAnimated); + const mockedCreateThumbnail = vi.mocked(createThumbnail); const imageRef = createRef() as RefObject; let imageSizeWatcher: ((...args: [unknown, unknown, unknown, unknown, ImageSize]) => void) | undefined; @@ -113,10 +116,10 @@ describe("ImageBodyViewModel", () => { thumbnailMxc: content.info?.thumbnail_url ?? "mxc://server/thumb", thumbnailHttp: "https://server/thumb.png", hasThumbnail: content.info?.thumbnail_url !== null, - getThumbnailHttp: jest.fn().mockReturnValue("https://server/thumb.png"), - getThumbnailOfSourceHttp: jest.fn().mockReturnValue("https://server/thumb.png"), - getSquareThumbnailHttp: jest.fn(), - downloadSource: jest.fn(), + getThumbnailHttp: vi.fn().mockReturnValue("https://server/thumb.png"), + getThumbnailOfSourceHttp: vi.fn().mockReturnValue("https://server/thumb.png"), + getSquareThumbnailHttp: vi.fn(), + downloadSource: vi.fn(), }) as unknown as Media; const createVm = ( @@ -131,15 +134,18 @@ describe("ImageBodyViewModel", () => { }); beforeEach(() => { - jest.clearAllMocks(); + vi.clearAllMocks(); Object.defineProperty(window, "devicePixelRatio", { configurable: true, value: 1, }); + vi.spyOn(URL, "createObjectURL").mockReturnValue("blob"); + vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {}); + const originalGetValue = SettingsStore.getValue; - jest.spyOn(SettingsStore, "getValue").mockImplementation((setting, ...args) => { + vi.spyOn(SettingsStore, "getValue").mockImplementation((setting, ...args) => { if (setting === "Images.size") { return ImageSize.Normal; } @@ -148,11 +154,11 @@ describe("ImageBodyViewModel", () => { } return originalGetValue(setting, ...args); }); - jest.spyOn(SettingsStore, "watchSetting").mockImplementation((_name, _roomId, callback) => { + vi.spyOn(SettingsStore, "watchSetting").mockImplementation((_name, _roomId, callback) => { imageSizeWatcher = callback as (...args: [unknown, unknown, unknown, unknown, ImageSize]) => void; return "image-body-test-watch"; }); - jest.spyOn(SettingsStore, "unwatchSetting").mockImplementation(jest.fn()); + vi.spyOn(SettingsStore, "unwatchSetting").mockImplementation(vi.fn()); mockedMediaFromContent.mockImplementation((content: Record) => createMockMedia(content)); mockedBlobIsAnimated.mockResolvedValue(true); @@ -160,13 +166,13 @@ describe("ImageBodyViewModel", () => { }); afterEach(() => { - jest.restoreAllMocks(); + vi.restoreAllMocks(); imageSizeWatcher = undefined; }); it("starts hidden and skips emitting when setMediaVisible is unchanged", () => { const vm = createVm(); - const listener = jest.fn(); + const listener = vi.fn(); vm.subscribe(listener); expect(vm.getSnapshot()).toMatchObject({ @@ -275,7 +281,7 @@ describe("ImageBodyViewModel", () => { }); it("switches from blurhash placeholder after the delay", () => { - jest.useFakeTimers(); + vi.useFakeTimers(); const vm = createVm({ mediaVisible: true, mxEvent: createEvent({ @@ -290,10 +296,10 @@ describe("ImageBodyViewModel", () => { vm.loadInitialMediaIfVisible(); expect(vm.getSnapshot().placeholder).toBe(ImageBodyViewPlaceholder.NONE); - jest.advanceTimersByTime(150); + vi.advanceTimersByTime(150); expect(vm.getSnapshot().placeholder).toBe(ImageBodyViewPlaceholder.BLURHASH); - jest.useRealTimers(); + vi.useRealTimers(); }); it("renders the ready snapshot with thumbnail data once visible", async () => { @@ -328,7 +334,7 @@ describe("ImageBodyViewModel", () => { }); it("reveals hidden media through the supplied setter", () => { - const setMediaVisible = jest.fn(); + const setMediaVisible = vi.fn(); const vm = createVm({ setMediaVisible }); vm.onHiddenButtonClick(); @@ -450,8 +456,8 @@ describe("ImageBodyViewModel", () => { }); it("uses the generic error label when image loading fails", () => { - const client = { on: jest.fn() }; - jest.spyOn(MatrixClientPeg, "safeGet").mockReturnValue(client as any); + const client = { on: vi.fn() }; + vi.spyOn(MatrixClientPeg, "safeGet").mockReturnValue(client as any); const vm = createVm({ mediaVisible: true }); vm.onImageError(); @@ -464,9 +470,9 @@ describe("ImageBodyViewModel", () => { }); it("clears image errors after reconnecting", () => { - const client = { on: jest.fn(), off: jest.fn() }; - jest.spyOn(MatrixClientPeg, "safeGet").mockReturnValue(client as any); - jest.spyOn(MatrixClientPeg, "get").mockReturnValue(client as any); + const client = { on: vi.fn(), off: vi.fn() }; + vi.spyOn(MatrixClientPeg, "safeGet").mockReturnValue(client as any); + vi.spyOn(MatrixClientPeg, "get").mockReturnValue(client as any); const vm = createVm({ mediaVisible: true }); vm.onImageError(); @@ -480,8 +486,8 @@ describe("ImageBodyViewModel", () => { }); it("ignores repeated image errors once already in the error state", () => { - const client = { on: jest.fn() }; - jest.spyOn(MatrixClientPeg, "safeGet").mockReturnValue(client as any); + const client = { on: vi.fn() }; + vi.spyOn(MatrixClientPeg, "safeGet").mockReturnValue(client as any); const vm = createVm({ mediaVisible: true }); vm.onImageError(); @@ -563,7 +569,7 @@ describe("ImageBodyViewModel", () => { it("generates a static thumbnail for animated images without a safe thumbnail", async () => { let createdImage: any; const originalCreateElement = document.createElement.bind(document); - jest.spyOn(document, "createElement").mockImplementation(((tagName: string) => { + vi.spyOn(document, "createElement").mockImplementation(((tagName: string) => { if (tagName !== "img") { return originalCreateElement(tagName); } @@ -615,7 +621,7 @@ describe("ImageBodyViewModel", () => { mockedBlobIsAnimated.mockResolvedValue(false); let createdImage: any; const originalCreateElement = document.createElement.bind(document); - jest.spyOn(document, "createElement").mockImplementation(((tagName: string) => { + vi.spyOn(document, "createElement").mockImplementation(((tagName: string) => { if (tagName !== "img") { return originalCreateElement(tagName); } @@ -663,7 +669,7 @@ describe("ImageBodyViewModel", () => { it("shows an error when animated image loading fails", async () => { let createdImage: any; const originalCreateElement = document.createElement.bind(document); - jest.spyOn(document, "createElement").mockImplementation(((tagName: string) => { + vi.spyOn(document, "createElement").mockImplementation(((tagName: string) => { if (tagName !== "img") { return originalCreateElement(tagName); } @@ -709,7 +715,7 @@ describe("ImageBodyViewModel", () => { mockedCreateThumbnail.mockRejectedValue(new Error("thumbnail failed")); let createdImage: any; const originalCreateElement = document.createElement.bind(document); - jest.spyOn(document, "createElement").mockImplementation(((tagName: string) => { + vi.spyOn(document, "createElement").mockImplementation(((tagName: string) => { if (tagName !== "img") { return originalCreateElement(tagName); } @@ -755,7 +761,7 @@ describe("ImageBodyViewModel", () => { it("revokes a generated thumbnail if disposed before download completes", async () => { let createdImage: any; const originalCreateElement = document.createElement.bind(document); - jest.spyOn(document, "createElement").mockImplementation(((tagName: string) => { + vi.spyOn(document, "createElement").mockImplementation(((tagName: string) => { if (tagName !== "img") { return originalCreateElement(tagName); } @@ -811,8 +817,8 @@ describe("ImageBodyViewModel", () => { permalinkCreator: {} as any, }); vm.loadInitialMediaIfVisible(); - const preventDefault = jest.fn(); - jest.spyOn(Modal, "createDialog").mockReturnValue({} as any); + const preventDefault = vi.fn(); + vi.spyOn(Modal, "createDialog").mockReturnValue({} as any); vm.onLinkClick({ button: 0, metaKey: false, preventDefault } as any); @@ -857,10 +863,10 @@ describe("ImageBodyViewModel", () => { }), mediaVisible: true, }); - jest.spyOn(Modal, "createDialog").mockReturnValue({} as any); + vi.spyOn(Modal, "createDialog").mockReturnValue({} as any); await downloadImageForTest(vm); - vm.onLinkClick({ button: 0, metaKey: false, preventDefault: jest.fn() } as any); + vm.onLinkClick({ button: 0, metaKey: false, preventDefault: vi.fn() } as any); expect(Modal.createDialog).toHaveBeenCalledWith( expect.any(Function), @@ -876,8 +882,8 @@ describe("ImageBodyViewModel", () => { it("does not open the image viewer for modified clicks or missing URLs", () => { const vm = createVm({ mediaVisible: true }); - const preventDefault = jest.fn(); - jest.spyOn(Modal, "createDialog").mockReturnValue({} as any); + const preventDefault = vi.fn(); + vi.spyOn(Modal, "createDialog").mockReturnValue({} as any); vm.onLinkClick({ button: 0, metaKey: true, preventDefault } as any); vm.onLinkClick({ button: 1, metaKey: false, preventDefault } as any); @@ -888,10 +894,10 @@ describe("ImageBodyViewModel", () => { }); it("reveals hidden media instead of opening the viewer", () => { - const setMediaVisible = jest.fn(); - const preventDefault = jest.fn(); + const setMediaVisible = vi.fn(); + const preventDefault = vi.fn(); const vm = createVm({ setMediaVisible }); - jest.spyOn(Modal, "createDialog").mockReturnValue({} as any); + vi.spyOn(Modal, "createDialog").mockReturnValue({} as any); vm.onLinkClick({ button: 0, metaKey: false, preventDefault } as any); @@ -902,8 +908,8 @@ describe("ImageBodyViewModel", () => { it("updates granular props and skips unchanged updates", async () => { const vm = createVm({ mediaVisible: true, maxImageHeight: 100 }); - const listener = jest.fn(); - const setMediaVisible = jest.fn(); + const listener = vi.fn(); + const setMediaVisible = vi.fn(); vm.subscribe(listener); vm.setForExport(undefined); @@ -932,8 +938,8 @@ describe("ImageBodyViewModel", () => { }); it("resets state and reloads when the event changes while visible", async () => { - const client = { off: jest.fn() }; - jest.spyOn(MatrixClientPeg, "get").mockReturnValue(client as any); + const client = { off: vi.fn() }; + vi.spyOn(MatrixClientPeg, "get").mockReturnValue(client as any); const vm = createVm({ mediaVisible: true }); vm.loadInitialMediaIfVisible(); expect(vm.getSnapshot().src).toBe("https://server/full.png"); @@ -964,10 +970,10 @@ describe("ImageBodyViewModel", () => { it("cleans up watchers, reconnect listeners and generated thumbnails on dispose", async () => { let createdImage: any; - const client = { off: jest.fn() }; - jest.spyOn(MatrixClientPeg, "get").mockReturnValue(client as any); + const client = { off: vi.fn() }; + vi.spyOn(MatrixClientPeg, "get").mockReturnValue(client as any); const originalCreateElement = document.createElement.bind(document); - jest.spyOn(document, "createElement").mockImplementation(((tagName: string) => { + vi.spyOn(document, "createElement").mockImplementation(((tagName: string) => { if (tagName !== "img") { return originalCreateElement(tagName); } diff --git a/apps/web/test/viewmodels/message-body/TileErrorViewModel-test.ts b/apps/web/src/viewmodels/message-body/TileErrorViewModel.test.ts similarity index 84% rename from apps/web/test/viewmodels/message-body/TileErrorViewModel-test.ts rename to apps/web/src/viewmodels/message-body/TileErrorViewModel.test.ts index d805e4d8f3..41e2a55313 100644 --- a/apps/web/test/viewmodels/message-body/TileErrorViewModel-test.ts +++ b/apps/web/src/viewmodels/message-body/TileErrorViewModel.test.ts @@ -5,15 +5,17 @@ * Please see LICENSE files in the repository root for full details. */ -import { mocked } from "jest-mock"; -import { MatrixEvent } from "matrix-js-sdk/src/matrix"; +// @vitest-environment happy-dom -import Modal from "../../../src/Modal"; -import SdkConfig from "../../../src/SdkConfig"; -import { BugReportEndpointURLLocal } from "../../../src/IConfigOptions"; -import ViewSource from "../../../src/components/structures/ViewSource"; -import BugReportDialog from "../../../src/components/views/dialogs/BugReportDialog"; -import { TileErrorViewModel } from "../../../src/viewmodels/message-body/TileErrorViewModel"; +import { MatrixEvent } from "matrix-js-sdk/src/matrix"; +import { vi, describe, it, expect, beforeEach, afterEach } from "vitest"; + +import Modal from "../../Modal"; +import SdkConfig from "../../SdkConfig"; +import { BugReportEndpointURLLocal } from "../../IConfigOptions"; +import ViewSource from "../../components/structures/ViewSource"; +import BugReportDialog from "../../components/views/dialogs/BugReportDialog"; +import { TileErrorViewModel } from "./TileErrorViewModel"; describe("TileErrorViewModel", () => { const createEvent = (type = "m.room.message"): MatrixEvent => @@ -42,12 +44,12 @@ describe("TileErrorViewModel", () => { beforeEach(() => { SdkConfig.reset(); - jest.spyOn(Modal, "createDialog").mockImplementation(() => ({ close: jest.fn() }) as any); + vi.spyOn(Modal, "createDialog").mockImplementation(() => ({ close: vi.fn() }) as any); }); afterEach(() => { SdkConfig.reset(); - jest.restoreAllMocks(); + vi.restoreAllMocks(); }); it("computes the initial snapshot from app state", () => { @@ -80,7 +82,7 @@ describe("TileErrorViewModel", () => { const error = new Error("Boom"); const mxEvent = createEvent(); const vm = createVm({ developerMode: true, error, mxEvent }); - const listener = jest.fn(); + const listener = vi.fn(); vm.subscribe(listener); vm.setDeveloperMode(true); @@ -124,6 +126,6 @@ describe("TileErrorViewModel", () => { vm.onViewSourceClick({} as any); - expect(mocked(Modal.createDialog)).not.toHaveBeenCalled(); + expect(vi.mocked(Modal.createDialog)).not.toHaveBeenCalled(); }); }); diff --git a/apps/web/test/viewmodels/message-body/UrlPreviewGroupViewModel-test.ts b/apps/web/src/viewmodels/message-body/UrlPreviewGroupViewModel.test.ts similarity index 96% rename from apps/web/test/viewmodels/message-body/UrlPreviewGroupViewModel-test.ts rename to apps/web/src/viewmodels/message-body/UrlPreviewGroupViewModel.test.ts index e3a1e502be..96be0f4616 100644 --- a/apps/web/test/viewmodels/message-body/UrlPreviewGroupViewModel-test.ts +++ b/apps/web/src/viewmodels/message-body/UrlPreviewGroupViewModel.test.ts @@ -5,17 +5,14 @@ * Please see LICENSE files in the repository root for full details. */ -import { expect } from "@jest/globals"; +// @vitest-environment happy-dom -import type { MockedObject } from "jest-mock-vitest-adapter"; import { MsgType, type MatrixClient } from "matrix-js-sdk/src/matrix"; -import { - BUNDLED_LINK_PREVIEWS, - MAX_PREVIEWS_WHEN_LIMITED, - UrlPreviewGroupViewModel, -} from "../../../src/viewmodels/message-body/UrlPreviewGroupViewModel"; +import { vi, describe, it, expect, type Mock, type MockedObject } from "vitest"; + +import { BUNDLED_LINK_PREVIEWS, MAX_PREVIEWS_WHEN_LIMITED, UrlPreviewGroupViewModel } from "./UrlPreviewGroupViewModel"; import type { UrlPreview } from "@element-hq/web-shared-components"; -import { getMockClientWithEventEmitter, mkEvent } from "../../test-utils"; +import { getMockClientWithEventEmitter, mkEvent } from "test-utils"; const IMAGE_MXC = "mxc://example.org/abc"; const BASIC_PREVIEW_OGDATA = { @@ -68,13 +65,13 @@ function getViewModel({ } = {}): { vm: UrlPreviewGroupViewModel; client: MockedObject; - onImageClicked: jest.Mock; + onImageClicked: Mock<(preview: UrlPreview) => void>; } { const client = getMockClientWithEventEmitter({ - getUrlPreview: jest.fn(), - mxcUrlToHttp: jest.fn(), + getUrlPreview: vi.fn(), + mxcUrlToHttp: vi.fn(), }); - const onImageClicked = jest.fn(); + const onImageClicked = vi.fn<(preview: UrlPreview) => void>(); const vm = new UrlPreviewGroupViewModel({ client, mediaVisible, diff --git a/apps/web/test/viewmodels/message-body/VideoBodyViewModel-test.ts b/apps/web/src/viewmodels/message-body/VideoBodyViewModel.test.ts similarity index 88% rename from apps/web/test/viewmodels/message-body/VideoBodyViewModel-test.ts rename to apps/web/src/viewmodels/message-body/VideoBodyViewModel.test.ts index cdba239c94..9811a57036 100644 --- a/apps/web/test/viewmodels/message-body/VideoBodyViewModel-test.ts +++ b/apps/web/src/viewmodels/message-body/VideoBodyViewModel.test.ts @@ -5,29 +5,32 @@ * Please see LICENSE files in the repository root for full details. */ +// @vitest-environment happy-dom + import { EventType, MatrixEvent } from "matrix-js-sdk/src/matrix"; import { logger } from "matrix-js-sdk/src/logger"; import { VideoBodyViewState } from "@element-hq/web-shared-components"; import { decode } from "blurhash"; import { type Media } from "@element-hq/element-web-module-api"; +import { vi, describe, it, expect, beforeEach, afterEach } from "vitest"; -import SettingsStore from "../../../src/settings/SettingsStore"; -import { ImageSize } from "../../../src/settings/enums/ImageSize"; -import { mediaFromContent } from "../../../src/customisations/Media"; -import { BLURHASH_FIELD } from "../../../src/utils/image-media"; -import { type MediaEventHelper } from "../../../src/utils/MediaEventHelper"; -import { VideoBodyViewModel } from "../../../src/viewmodels/message-body/VideoBodyViewModel"; +import SettingsStore from "../../settings/SettingsStore"; +import { ImageSize } from "../../settings/enums/ImageSize"; +import { mediaFromContent } from "../../customisations/Media"; +import { BLURHASH_FIELD } from "../../utils/image-media"; +import { type MediaEventHelper } from "../../utils/MediaEventHelper"; +import { VideoBodyViewModel } from "./VideoBodyViewModel"; -jest.mock("../../../src/customisations/Media", () => ({ - mediaFromContent: jest.fn(), +vi.mock("../../customisations/Media", () => ({ + mediaFromContent: vi.fn(), })); -jest.mock("blurhash", () => ({ - decode: jest.fn(), +vi.mock("blurhash", () => ({ + decode: vi.fn(), })); describe("VideoBodyViewModel", () => { - const mockedMediaFromContent = jest.mocked(mediaFromContent); - const mockedDecode = jest.mocked(decode); + const mockedMediaFromContent = vi.mocked(mediaFromContent); + const mockedDecode = vi.mocked(decode); const videoRef = { current: null }; let imageSizeWatcher: ((...args: [unknown, unknown, unknown, unknown, ImageSize]) => void) | undefined; @@ -103,15 +106,15 @@ describe("VideoBodyViewModel", () => { ? null : (content.info?.thumbnail_url ?? "https://server/poster.jpg"), hasThumbnail: content.info?.thumbnail_url !== null, - getThumbnailHttp: jest.fn(), - getThumbnailOfSourceHttp: jest.fn(), - getSquareThumbnailHttp: jest.fn(), - downloadSource: jest.fn(), + getThumbnailHttp: vi.fn(), + getThumbnailOfSourceHttp: vi.fn(), + getSquareThumbnailHttp: vi.fn(), + downloadSource: vi.fn(), }) as unknown as Media; beforeEach(() => { const originalGetValue = SettingsStore.getValue; - jest.spyOn(SettingsStore, "getValue").mockImplementation((setting, ...args) => { + vi.spyOn(SettingsStore, "getValue").mockImplementation((setting, ...args) => { if (setting === "Images.size") { return ImageSize.Normal; } @@ -120,18 +123,18 @@ describe("VideoBodyViewModel", () => { } return originalGetValue(setting, ...args); }); - jest.spyOn(SettingsStore, "watchSetting").mockImplementation((_name, _roomId, callback) => { + vi.spyOn(SettingsStore, "watchSetting").mockImplementation((_name, _roomId, callback) => { imageSizeWatcher = callback as (...args: [unknown, unknown, unknown, unknown, ImageSize]) => void; return "video-body-test-watch"; }); - jest.spyOn(SettingsStore, "unwatchSetting").mockImplementation(jest.fn()); + vi.spyOn(SettingsStore, "unwatchSetting").mockImplementation(vi.fn()); mockedMediaFromContent.mockImplementation((content) => createMockMedia(content)); mockedDecode.mockReturnValue(new Uint8ClampedArray(320 * 180 * 4)); }); afterEach(() => { - jest.restoreAllMocks(); + vi.restoreAllMocks(); imageSizeWatcher = undefined; }); @@ -188,7 +191,7 @@ describe("VideoBodyViewModel", () => { }); it("forwards preview clicks", () => { - const onPreviewClick = jest.fn(); + const onPreviewClick = vi.fn(); const vm = createVm({ onPreviewClick }); vm.onPreviewClick(); @@ -198,7 +201,7 @@ describe("VideoBodyViewModel", () => { it("preloads encrypted video when autoplay is enabled", async () => { const originalGetValue = SettingsStore.getValue; - jest.spyOn(SettingsStore, "getValue").mockImplementation((setting, ...args) => { + vi.spyOn(SettingsStore, "getValue").mockImplementation((setting, ...args) => { if (setting === "Images.size") return ImageSize.Normal; if (setting === "autoplayVideo") return true; return originalGetValue(setting, ...args); @@ -262,7 +265,7 @@ describe("VideoBodyViewModel", () => { }); it("switches to the error state when encrypted preload fails", async () => { - jest.spyOn(logger, "warn").mockImplementation(jest.fn()); + vi.spyOn(logger, "warn").mockImplementation(vi.fn()); const vm = createVm({ mxEvent: createEvent({ content: { @@ -284,7 +287,7 @@ describe("VideoBodyViewModel", () => { }); it("loads the encrypted source on play when only a placeholder url is present", async () => { - const play = jest.fn(); + const play = vi.fn(); const vm = createVm({ mxEvent: createEvent({ content: { @@ -352,19 +355,19 @@ describe("VideoBodyViewModel", () => { let imageOnLoad: (() => void) | undefined; const context = { - createImageData: jest.fn((width: number, height: number) => ({ + createImageData: vi.fn((width: number, height: number) => ({ data: new Uint8ClampedArray(width * height * 4), })), - putImageData: jest.fn(), + putImageData: vi.fn(), }; const canvas = { width: 0, height: 0, - getContext: jest.fn(() => context), - toDataURL: jest.fn(() => "data:image/png;base64,blurhash"), + getContext: vi.fn(() => context), + toDataURL: vi.fn(() => "data:image/png;base64,blurhash"), }; - jest.spyOn(document, "createElement").mockImplementation(((tagName: string) => { + vi.spyOn(document, "createElement").mockImplementation(((tagName: string) => { if (tagName === "canvas") { return canvas as any; } @@ -444,13 +447,13 @@ describe("VideoBodyViewModel", () => { it("does not emit for unchanged targeted setters", () => { const event = createEvent(); - const onPreviewClick = jest.fn(); + const onPreviewClick = vi.fn(); const vm = createVm({ mxEvent: event, mediaVisible: false, onPreviewClick, }); - const listener = jest.fn(); + const listener = vi.fn(); vm.subscribe(listener); vm.setEvent(event, undefined); diff --git a/apps/web/test/viewmodels/message-body/__snapshots__/UrlPreviewGroupViewModel-test.ts.snap b/apps/web/src/viewmodels/message-body/__snapshots__/UrlPreviewGroupViewModel.test.ts.snap similarity index 74% rename from apps/web/test/viewmodels/message-body/__snapshots__/UrlPreviewGroupViewModel-test.ts.snap rename to apps/web/src/viewmodels/message-body/__snapshots__/UrlPreviewGroupViewModel.test.ts.snap index bc9123407e..e7265a76a1 100644 --- a/apps/web/test/viewmodels/message-body/__snapshots__/UrlPreviewGroupViewModel-test.ts.snap +++ b/apps/web/src/viewmodels/message-body/__snapshots__/UrlPreviewGroupViewModel.test.ts.snap @@ -1,6 +1,6 @@ -// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html -exports[`UrlPreviewGroupViewModel should deduplicate multiple versions of the same URL 1`] = ` +exports[`UrlPreviewGroupViewModel > should deduplicate multiple versions of the same URL 1`] = ` { "overPreviewLimit": false, "previews": [ @@ -21,7 +21,7 @@ exports[`UrlPreviewGroupViewModel should deduplicate multiple versions of the sa } `; -exports[`UrlPreviewGroupViewModel should handle being hidden and shown by the user 1`] = ` +exports[`UrlPreviewGroupViewModel > should handle being hidden and shown by the user 1`] = ` { "overPreviewLimit": false, "previews": [], @@ -30,7 +30,7 @@ exports[`UrlPreviewGroupViewModel should handle being hidden and shown by the us } `; -exports[`UrlPreviewGroupViewModel should handle being hidden and shown by the user 2`] = ` +exports[`UrlPreviewGroupViewModel > should handle being hidden and shown by the user 2`] = ` { "overPreviewLimit": false, "previews": [ @@ -51,7 +51,7 @@ exports[`UrlPreviewGroupViewModel should handle being hidden and shown by the us } `; -exports[`UrlPreviewGroupViewModel should hide preview when invisible 1`] = ` +exports[`UrlPreviewGroupViewModel > should hide preview when invisible 1`] = ` { "overPreviewLimit": false, "previews": [], @@ -60,7 +60,7 @@ exports[`UrlPreviewGroupViewModel should hide preview when invisible 1`] = ` } `; -exports[`UrlPreviewGroupViewModel should ignore failed previews 1`] = ` +exports[`UrlPreviewGroupViewModel > should ignore failed previews 1`] = ` { "overPreviewLimit": false, "previews": [], @@ -69,7 +69,7 @@ exports[`UrlPreviewGroupViewModel should ignore failed previews 1`] = ` } `; -exports[`UrlPreviewGroupViewModel should ignore media when mediaVisible is false 1`] = ` +exports[`UrlPreviewGroupViewModel > should ignore media when mediaVisible is false 1`] = ` { "overPreviewLimit": false, "previews": [ @@ -90,7 +90,7 @@ exports[`UrlPreviewGroupViewModel should ignore media when mediaVisible is false } `; -exports[`UrlPreviewGroupViewModel should preview a single valid URL 1`] = ` +exports[`UrlPreviewGroupViewModel > should preview a single valid URL 1`] = ` { "overPreviewLimit": false, "previews": [ @@ -111,7 +111,7 @@ exports[`UrlPreviewGroupViewModel should preview a single valid URL 1`] = ` } `; -exports[`UrlPreviewGroupViewModel should return no previews by default 1`] = ` +exports[`UrlPreviewGroupViewModel > should return no previews by default 1`] = ` { "overPreviewLimit": false, "previews": [], diff --git a/apps/web/test/viewmodels/room-list/RoomListHeaderViewModel-test.ts b/apps/web/src/viewmodels/room-list/RoomListHeaderViewModel.test.ts similarity index 73% rename from apps/web/test/viewmodels/room-list/RoomListHeaderViewModel-test.ts rename to apps/web/src/viewmodels/room-list/RoomListHeaderViewModel.test.ts index 3f9415debf..c1e966ed32 100644 --- a/apps/web/test/viewmodels/room-list/RoomListHeaderViewModel-test.ts +++ b/apps/web/src/viewmodels/room-list/RoomListHeaderViewModel.test.ts @@ -5,46 +5,49 @@ * Please see LICENSE files in the repository root for full details. */ -import { mocked } from "jest-mock"; -import { JoinRule, type MatrixClient, type Room, RoomEvent, RoomType } from "matrix-js-sdk/src/matrix"; +// @vitest-environment happy-dom -import { RoomListHeaderViewModel } from "../../../src/viewmodels/room-list/RoomListHeaderViewModel"; -import { MetaSpace, UPDATE_HOME_BEHAVIOUR, UPDATE_SELECTED_SPACE } from "../../../src/stores/spaces"; -import defaultDispatcher from "../../../src/dispatcher/dispatcher"; -import { Action } from "../../../src/dispatcher/actions"; -import SettingsStore from "../../../src/settings/SettingsStore"; -import { SortingAlgorithm } from "../../../src/stores/room-list-v3/skip-list/sorters"; -import RoomListStoreV3 from "../../../src/stores/room-list-v3/RoomListStoreV3"; +import { vi, describe, it, expect, beforeEach, afterEach } from "vitest"; +import { JoinRule, type MatrixClient, type Room, RoomEvent, RoomType } from "matrix-js-sdk/src/matrix"; +import { createTestClient, mkSpace, TestSDKContext } from "test-utils"; + +import { RoomListHeaderViewModel } from "./RoomListHeaderViewModel"; +import { MetaSpace, UPDATE_HOME_BEHAVIOUR, UPDATE_SELECTED_SPACE } from "../../stores/spaces"; +import defaultDispatcher from "../../dispatcher/dispatcher"; +import { Action } from "../../dispatcher/actions"; +import SettingsStore from "../../settings/SettingsStore"; +import { SortingAlgorithm } from "../../stores/room-list-v3/skip-list/sorters"; +import RoomListStoreV3 from "../../stores/room-list-v3/RoomListStoreV3"; import { shouldShowSpaceSettings, showCreateNewRoom, showSpaceInvite, showSpacePreferences, showSpaceSettings, -} from "../../../src/utils/space"; -import { createTestClient, mkSpace } from "../../test-utils"; -import { createRoom, hasCreateRoomRights } from "../../../src/viewmodels/room-list/utils"; -import PosthogTrackers from "../../../src/PosthogTrackers"; -import { ReleaseAnnouncementStore } from "../../../src/stores/ReleaseAnnouncementStore"; -import { TestSDKContext } from "../../unit-tests/TestSDKContext.ts"; +} from "../../utils/space"; +import { createRoom, hasCreateRoomRights } from "./utils"; +import PosthogTrackers from "../../PosthogTrackers"; +import { ReleaseAnnouncementStore } from "../../stores/ReleaseAnnouncementStore"; -jest.mock("../../../src/PosthogTrackers", () => ({ - trackInteraction: jest.fn(), - trackSectionCreation: jest.fn(), - trackCollapseOrExpandSection: jest.fn(), +vi.mock("../../PosthogTrackers", () => ({ + default: { + trackInteraction: vi.fn(), + trackSectionCreation: vi.fn(), + trackCollapseOrExpandSection: vi.fn(), + }, })); -jest.mock("../../../src/utils/space", () => ({ - shouldShowSpaceSettings: jest.fn(), - showCreateNewRoom: jest.fn(), - showSpaceInvite: jest.fn(), - showSpacePreferences: jest.fn(), - showSpaceSettings: jest.fn(), +vi.mock("../../utils/space", () => ({ + shouldShowSpaceSettings: vi.fn(), + showCreateNewRoom: vi.fn(), + showSpaceInvite: vi.fn(), + showSpacePreferences: vi.fn(), + showSpaceSettings: vi.fn(), })); -jest.mock("../../../src/viewmodels/room-list/utils", () => ({ - createRoom: jest.fn(), - hasCreateRoomRights: jest.fn(), +vi.mock("./utils", () => ({ + createRoom: vi.fn(), + hasCreateRoomRights: vi.fn(), })); describe("RoomListHeaderViewModel", () => { @@ -60,13 +63,13 @@ describe("RoomListHeaderViewModel", () => { mockSpace = mkSpace(matrixClient, "!space:server"); - mocked(hasCreateRoomRights).mockReturnValue(true); - mocked(shouldShowSpaceSettings).mockReturnValue(true); + vi.mocked(hasCreateRoomRights).mockReturnValue(true); + vi.mocked(shouldShowSpaceSettings).mockReturnValue(true); - jest.spyOn(ReleaseAnnouncementStore.instance, "getReleaseAnnouncement").mockReturnValue(null); - jest.spyOn(ReleaseAnnouncementStore.instance, "nextReleaseAnnouncement").mockResolvedValue(undefined); + vi.spyOn(ReleaseAnnouncementStore.instance, "getReleaseAnnouncement").mockReturnValue(null); + vi.spyOn(ReleaseAnnouncementStore.instance, "nextReleaseAnnouncement").mockResolvedValue(undefined); - jest.spyOn(SettingsStore, "getValue").mockImplementation((settingName: string) => { + vi.spyOn(SettingsStore, "getValue").mockImplementation((settingName: string) => { if (settingName === "RoomList.preferredSorting") return SortingAlgorithm.Recency; if (settingName === "feature_video_rooms") return true; if (settingName === "feature_element_call_video_rooms") return true; @@ -76,14 +79,14 @@ describe("RoomListHeaderViewModel", () => { }); afterEach(() => { - jest.restoreAllMocks(); + vi.restoreAllMocks(); vm.dispose(); }); describe("snapshot", () => { it("should compute snapshot for Home space", () => { - jest.spyOn(sdkContext.spaceStore, "activeSpace", "get").mockReturnValue(MetaSpace.Home); - jest.spyOn(sdkContext.spaceStore, "activeSpaceRoom", "get").mockReturnValue(null); + vi.spyOn(sdkContext.spaceStore, "activeSpace", "get").mockReturnValue(MetaSpace.Home); + vi.spyOn(sdkContext.spaceStore, "activeSpaceRoom", "get").mockReturnValue(null); vm = new RoomListHeaderViewModel({ matrixClient, spaceStore: sdkContext.spaceStore }); @@ -96,8 +99,8 @@ describe("RoomListHeaderViewModel", () => { }); it("should compute snapshot for active space", () => { - jest.spyOn(sdkContext.spaceStore, "activeSpace", "get").mockReturnValue(mockSpace.roomId); - jest.spyOn(sdkContext.spaceStore, "activeSpaceRoom", "get").mockReturnValue(mockSpace); + vi.spyOn(sdkContext.spaceStore, "activeSpace", "get").mockReturnValue(mockSpace.roomId); + vi.spyOn(sdkContext.spaceStore, "activeSpaceRoom", "get").mockReturnValue(mockSpace); vm = new RoomListHeaderViewModel({ matrixClient, spaceStore: sdkContext.spaceStore }); @@ -106,7 +109,7 @@ describe("RoomListHeaderViewModel", () => { }); it("should hide video room option when feature is disabled", () => { - jest.spyOn(SettingsStore, "getValue").mockImplementation((settingName: string) => { + vi.spyOn(SettingsStore, "getValue").mockImplementation((settingName: string) => { if (settingName === "feature_video_rooms") return false; return false; }); @@ -116,7 +119,7 @@ describe("RoomListHeaderViewModel", () => { }); it("should show alphabetical sort option when RoomList.preferredSorting is Alphabetic", () => { - jest.spyOn(SettingsStore, "getValue").mockImplementation((settingName: string) => { + vi.spyOn(SettingsStore, "getValue").mockImplementation((settingName: string) => { if (settingName === "RoomList.preferredSorting") return SortingAlgorithm.Alphabetic; return false; }); @@ -126,31 +129,31 @@ describe("RoomListHeaderViewModel", () => { }); it("should show invite option when space is public", () => { - jest.spyOn(sdkContext.spaceStore, "activeSpace", "get").mockReturnValue(mockSpace.roomId); - jest.spyOn(sdkContext.spaceStore, "activeSpaceRoom", "get").mockReturnValue(mockSpace); - jest.spyOn(mockSpace, "getJoinRule").mockReturnValue(JoinRule.Public); + vi.spyOn(sdkContext.spaceStore, "activeSpace", "get").mockReturnValue(mockSpace.roomId); + vi.spyOn(sdkContext.spaceStore, "activeSpaceRoom", "get").mockReturnValue(mockSpace); + vi.spyOn(mockSpace, "getJoinRule").mockReturnValue(JoinRule.Public); vm = new RoomListHeaderViewModel({ matrixClient, spaceStore: sdkContext.spaceStore }); expect(vm.getSnapshot().canInviteInSpace).toBe(true); }); it("should hide invite option when user cannot invite", () => { - mocked(mockSpace.canInvite).mockReturnValue(false); + vi.mocked(mockSpace.canInvite).mockReturnValue(false); vm = new RoomListHeaderViewModel({ matrixClient, spaceStore: sdkContext.spaceStore }); expect(vm.getSnapshot().canInviteInSpace).toBe(false); }); it("should hide space settings when user cannot access them", () => { - jest.spyOn(sdkContext.spaceStore, "activeSpace", "get").mockReturnValue(mockSpace.roomId); - mocked(shouldShowSpaceSettings).mockReturnValue(false); + vi.spyOn(sdkContext.spaceStore, "activeSpace", "get").mockReturnValue(mockSpace.roomId); + vi.mocked(shouldShowSpaceSettings).mockReturnValue(false); vm = new RoomListHeaderViewModel({ matrixClient, spaceStore: sdkContext.spaceStore }); expect(vm.getSnapshot().canAccessSpaceSettings).toBe(false); }); it("should show message preview when RoomList.showMessagePreview is enabled", () => { - jest.spyOn(SettingsStore, "getValue").mockImplementation((settingName: string) => { + vi.spyOn(SettingsStore, "getValue").mockImplementation((settingName: string) => { if (settingName === "RoomList.showMessagePreview") return true; return false; }); @@ -160,7 +163,7 @@ describe("RoomListHeaderViewModel", () => { }); it("should set areSectionsEnabled to true when RoomList.showSections is enabled", () => { - jest.spyOn(SettingsStore, "getValue").mockImplementation((settingName: string) => { + vi.spyOn(SettingsStore, "getValue").mockImplementation((settingName: string) => { if (settingName === "RoomList.showSections") return true; return false; }); @@ -171,7 +174,7 @@ describe("RoomListHeaderViewModel", () => { it("should update areSectionsEnabled when RoomList.showSections setting changes", () => { let watchCallback: () => void = () => {}; - jest.spyOn(SettingsStore, "watchSetting").mockImplementation((settingName, _roomId, callback) => { + vi.spyOn(SettingsStore, "watchSetting").mockImplementation((settingName, _roomId, callback) => { if (settingName === "RoomList.showSections") watchCallback = callback as () => void; return "watcher-id"; }); @@ -180,7 +183,7 @@ describe("RoomListHeaderViewModel", () => { expect(vm.getSnapshot().areSectionsEnabled).toBe(false); // Enable sections - jest.spyOn(SettingsStore, "getValue").mockImplementation((settingName: string) => { + vi.spyOn(SettingsStore, "getValue").mockImplementation((settingName: string) => { if (settingName === "RoomList.showSections") return true; return false; }); @@ -190,9 +193,7 @@ describe("RoomListHeaderViewModel", () => { }); it("should set displaySectionReleaseAnnouncement to true when sections feature is enabled and announcement is active", () => { - jest.spyOn(ReleaseAnnouncementStore.instance, "getReleaseAnnouncement").mockReturnValue( - "room_list_section", - ); + vi.spyOn(ReleaseAnnouncementStore.instance, "getReleaseAnnouncement").mockReturnValue("room_list_section"); vm = new RoomListHeaderViewModel({ matrixClient, spaceStore: sdkContext.spaceStore }); expect(vm.getSnapshot().displaySectionReleaseAnnouncement).toBe(true); @@ -203,13 +204,13 @@ describe("RoomListHeaderViewModel", () => { it.each([UPDATE_SELECTED_SPACE, UPDATE_HOME_BEHAVIOUR])( "should update snapshot when %s event is emitted", (event) => { - jest.spyOn(sdkContext.spaceStore, "activeSpace", "get").mockReturnValue(MetaSpace.Home); - jest.spyOn(sdkContext.spaceStore, "activeSpaceRoom", "get").mockReturnValue(null); + vi.spyOn(sdkContext.spaceStore, "activeSpace", "get").mockReturnValue(MetaSpace.Home); + vi.spyOn(sdkContext.spaceStore, "activeSpaceRoom", "get").mockReturnValue(null); vm = new RoomListHeaderViewModel({ matrixClient, spaceStore: sdkContext.spaceStore }); - jest.spyOn(sdkContext.spaceStore, "activeSpace", "get").mockReturnValue(mockSpace.roomId); - jest.spyOn(sdkContext.spaceStore, "activeSpaceRoom", "get").mockReturnValue(mockSpace); + vi.spyOn(sdkContext.spaceStore, "activeSpace", "get").mockReturnValue(mockSpace.roomId); + vi.spyOn(sdkContext.spaceStore, "activeSpaceRoom", "get").mockReturnValue(mockSpace); sdkContext.spaceStore.emit(event); expect(vm.getSnapshot().title).toBe(mockSpace.roomId); @@ -217,8 +218,8 @@ describe("RoomListHeaderViewModel", () => { ); it("should update snapshot when space name changes", () => { - jest.spyOn(sdkContext.spaceStore, "activeSpace", "get").mockReturnValue(mockSpace.roomId); - jest.spyOn(sdkContext.spaceStore, "activeSpaceRoom", "get").mockReturnValue(mockSpace); + vi.spyOn(sdkContext.spaceStore, "activeSpace", "get").mockReturnValue(mockSpace.roomId); + vi.spyOn(sdkContext.spaceStore, "activeSpaceRoom", "get").mockReturnValue(mockSpace); vm = new RoomListHeaderViewModel({ matrixClient, spaceStore: sdkContext.spaceStore }); @@ -231,12 +232,12 @@ describe("RoomListHeaderViewModel", () => { describe("actions", () => { beforeEach(() => { - jest.spyOn(sdkContext.spaceStore, "activeSpace", "get").mockReturnValue(mockSpace.roomId); - jest.spyOn(sdkContext.spaceStore, "activeSpaceRoom", "get").mockReturnValue(mockSpace); + vi.spyOn(sdkContext.spaceStore, "activeSpace", "get").mockReturnValue(mockSpace.roomId); + vi.spyOn(sdkContext.spaceStore, "activeSpaceRoom", "get").mockReturnValue(mockSpace); }); it("should fire CreateChat action when createChatRoom is called", () => { - const fireSpy = jest.spyOn(defaultDispatcher, "fire"); + const fireSpy = vi.spyOn(defaultDispatcher, "fire"); vm = new RoomListHeaderViewModel({ matrixClient, spaceStore: sdkContext.spaceStore }); vm.createChatRoom(new Event("click")); @@ -251,7 +252,7 @@ describe("RoomListHeaderViewModel", () => { }); it("should show create video room dialog for space when createVideoRoom is called", () => { - jest.spyOn(SettingsStore, "getValue").mockImplementation((settingName: string) => { + vi.spyOn(SettingsStore, "getValue").mockImplementation((settingName: string) => { if (settingName === "feature_element_call_video_rooms") return false; return false; }); @@ -262,9 +263,9 @@ describe("RoomListHeaderViewModel", () => { }); it("should use UnstableCall type when element_call_video_rooms is enabled", () => { - jest.spyOn(sdkContext.spaceStore, "activeSpaceRoom", "get").mockReturnValue(null); + vi.spyOn(sdkContext.spaceStore, "activeSpaceRoom", "get").mockReturnValue(null); - const dispatchSpy = jest.spyOn(defaultDispatcher, "dispatch"); + const dispatchSpy = vi.spyOn(defaultDispatcher, "dispatch"); vm = new RoomListHeaderViewModel({ matrixClient, spaceStore: sdkContext.spaceStore }); vm.createVideoRoom(); @@ -275,7 +276,7 @@ describe("RoomListHeaderViewModel", () => { }); it("should dispatch ViewRoom action when openSpaceHome is called", () => { - const dispatchSpy = jest.spyOn(defaultDispatcher, "dispatch"); + const dispatchSpy = vi.spyOn(defaultDispatcher, "dispatch"); vm = new RoomListHeaderViewModel({ matrixClient, spaceStore: sdkContext.spaceStore }); vm.openSpaceHome(); @@ -312,20 +313,20 @@ describe("RoomListHeaderViewModel", () => { ["alphabetical" as const, SortingAlgorithm.Alphabetic], ["unread-first" as const, SortingAlgorithm.Unread], ])("should resort when sort is called with '%s'", (option, expectedAlgorithm) => { - const resortSpy = jest.spyOn(RoomListStoreV3.instance, "resort").mockImplementation(jest.fn()); + const resortSpy = vi.spyOn(RoomListStoreV3.instance, "resort").mockImplementation(vi.fn()); vm = new RoomListHeaderViewModel({ matrixClient, spaceStore: sdkContext.spaceStore }); vm.sort(option); expect(resortSpy).toHaveBeenCalledWith(expectedAlgorithm); }); it("should track analytics on resort", () => { - jest.spyOn(RoomListStoreV3.instance, "activeSortAlgorithm", "get").mockReturnValue( + vi.spyOn(RoomListStoreV3.instance, "activeSortAlgorithm", "get").mockReturnValue( SortingAlgorithm.Alphabetic, ); - PosthogTrackers.trackRoomListSortingAlgorithmChange = jest.fn(); + PosthogTrackers.trackRoomListSortingAlgorithmChange = vi.fn(); vm = new RoomListHeaderViewModel({ matrixClient, spaceStore: sdkContext.spaceStore }); - jest.spyOn(RoomListStoreV3.instance, "resort").mockImplementation(jest.fn()); + vi.spyOn(RoomListStoreV3.instance, "resort").mockImplementation(vi.fn()); vm.sort("unread-first"); expect(PosthogTrackers.trackRoomListSortingAlgorithmChange).toHaveBeenCalledWith( @@ -335,7 +336,7 @@ describe("RoomListHeaderViewModel", () => { }); it("should call createSection on RoomListStoreV3 when createSection is called", () => { - const createSectionSpy = jest + const createSectionSpy = vi .spyOn(RoomListStoreV3.instance, "createSection") .mockResolvedValue("element.io.section.work"); vm = new RoomListHeaderViewModel({ matrixClient, spaceStore: sdkContext.spaceStore }); @@ -345,7 +346,7 @@ describe("RoomListHeaderViewModel", () => { describe("collapseOrExpandSections", () => { it("should dispatch RoomListCollapseAllSections when collapseSections is not 'expand'", () => { - const fireSpy = jest.spyOn(defaultDispatcher, "fire"); + const fireSpy = vi.spyOn(defaultDispatcher, "fire"); vm = new RoomListHeaderViewModel({ matrixClient, spaceStore: sdkContext.spaceStore }); vm.collapseOrExpandSections(); @@ -354,7 +355,7 @@ describe("RoomListHeaderViewModel", () => { }); it("should dispatch RoomListExpandAllSections when collapseSections is 'expand'", () => { - const fireSpy = jest.spyOn(defaultDispatcher, "fire"); + const fireSpy = vi.spyOn(defaultDispatcher, "fire"); vm = new RoomListHeaderViewModel({ matrixClient, spaceStore: sdkContext.spaceStore }); // Drive the VM into the "expand" state by simulating all sections collapsed @@ -427,11 +428,11 @@ describe("RoomListHeaderViewModel", () => { }); it("should toggle message preview from enabled to disabled", () => { - jest.spyOn(SettingsStore, "getValue").mockImplementation((settingName: string) => { + vi.spyOn(SettingsStore, "getValue").mockImplementation((settingName: string) => { if (settingName === "RoomList.showMessagePreview") return true; return false; }); - const setValueSpy = jest.spyOn(SettingsStore, "setValue").mockImplementation(jest.fn()); + const setValueSpy = vi.spyOn(SettingsStore, "setValue").mockImplementation(vi.fn()); vm = new RoomListHeaderViewModel({ matrixClient, spaceStore: sdkContext.spaceStore }); expect(vm.getSnapshot().isMessagePreviewEnabled).toBe(true); diff --git a/apps/web/test/viewmodels/room-list/RoomListItemViewModel-test.ts b/apps/web/src/viewmodels/room-list/RoomListItemViewModel.test.ts similarity index 77% rename from apps/web/test/viewmodels/room-list/RoomListItemViewModel-test.ts rename to apps/web/src/viewmodels/room-list/RoomListItemViewModel.test.ts index d0bd7ea05d..7e60ed5307 100644 --- a/apps/web/test/viewmodels/room-list/RoomListItemViewModel-test.ts +++ b/apps/web/src/viewmodels/room-list/RoomListItemViewModel.test.ts @@ -5,7 +5,10 @@ * Please see LICENSE files in the repository root for full details. */ +// @vitest-environment happy-dom + import EventEmitter from "node:events"; +import { vi, describe, it, expect, beforeEach, afterEach, type Mock } from "vitest"; import { type MatrixClient, type MatrixEvent, @@ -15,38 +18,38 @@ import { type RoomMember, } from "matrix-js-sdk/src/matrix"; import { CallType } from "matrix-js-sdk/src/webrtc/call"; -import { waitFor } from "jest-matrix-react"; +import { waitFor } from "test-utils-rtl"; +import { createTestClient, flushPromises } from "test-utils"; -import { createTestClient, flushPromises } from "../../test-utils"; -import { RoomNotificationState } from "../../../src/stores/notifications/RoomNotificationState"; -import { RoomNotificationStateStore } from "../../../src/stores/notifications/RoomNotificationStateStore"; -import { NotificationStateEvents } from "../../../src/stores/notifications/NotificationState"; -import { type MessagePreview, MessagePreviewStore } from "../../../src/stores/message-preview"; -import SettingsStore, { type CallbackFn } from "../../../src/settings/SettingsStore"; -import DMRoomMap from "../../../src/utils/DMRoomMap"; -import { DefaultTagID } from "../../../src/stores/room-list-v3/skip-list/tag"; -import dispatcher from "../../../src/dispatcher/dispatcher"; -import { Action } from "../../../src/dispatcher/actions"; -import { CallStore } from "../../../src/stores/CallStore"; -import { CallEvent, type Call } from "../../../src/models/Call"; -import { RoomListItemViewModel } from "../../../src/viewmodels/room-list/RoomListItemViewModel"; -import RoomListStoreV3 from "../../../src/stores/room-list-v3/RoomListStoreV3"; -import * as tagRoomModule from "../../../src/utils/room/tagRoom"; -import { CHATS_TAG } from "../../../src/stores/room-list-v3/section"; +import { RoomNotificationState } from "../../stores/notifications/RoomNotificationState"; +import { RoomNotificationStateStore } from "../../stores/notifications/RoomNotificationStateStore"; +import { NotificationStateEvents } from "../../stores/notifications/NotificationState"; +import { type MessagePreview, MessagePreviewStore } from "../../stores/message-preview"; +import SettingsStore, { type CallbackFn } from "../../settings/SettingsStore"; +import DMRoomMap from "../../utils/DMRoomMap"; +import { DefaultTagID } from "../../stores/room-list-v3/skip-list/tag"; +import dispatcher from "../../dispatcher/dispatcher"; +import { Action } from "../../dispatcher/actions"; +import { CallStore } from "../../stores/CallStore"; +import { CallEvent, type Call } from "../../models/Call"; +import { RoomListItemViewModel } from "./RoomListItemViewModel"; +import RoomListStoreV3 from "../../stores/room-list-v3/RoomListStoreV3"; +import * as tagRoomModule from "../../utils/room/tagRoom"; +import { CHATS_TAG } from "../../stores/room-list-v3/section"; -jest.mock("../../../src/viewmodels/room-list/utils", () => ({ - hasAccessToOptionsMenu: jest.fn().mockReturnValue(true), - hasAccessToNotificationMenu: jest.fn().mockReturnValue(true), +vi.mock("./utils", () => ({ + hasAccessToOptionsMenu: vi.fn().mockReturnValue(true), + hasAccessToNotificationMenu: vi.fn().mockReturnValue(true), })); -jest.mock("../../../src/stores/CallStore", () => ({ +vi.mock("../../stores/CallStore", () => ({ __esModule: true, CallStore: { instance: { - getCall: jest.fn(), - on: jest.fn(), - off: jest.fn(), - emit: jest.fn(), + getCall: vi.fn(), + on: vi.fn(), + off: vi.fn(), + emit: vi.fn(), }, }, CallStoreEvent: { @@ -70,30 +73,30 @@ describe("RoomListItemViewModel", () => { room.name = "Test Room"; notificationState = new RoomNotificationState(room, false); - jest.spyOn(RoomNotificationStateStore.instance, "getRoomState").mockReturnValue(notificationState); + vi.spyOn(RoomNotificationStateStore.instance, "getRoomState").mockReturnValue(notificationState); const dmRoomMap = { - getUserIdForRoomId: jest.fn().mockReturnValue(undefined), + getUserIdForRoomId: vi.fn().mockReturnValue(undefined), } as unknown as DMRoomMap; DMRoomMap.setShared(dmRoomMap); - jest.spyOn(SettingsStore, "getValue").mockImplementation((setting) => { + vi.spyOn(SettingsStore, "getValue").mockImplementation((setting) => { if (setting === "RoomList.showMessagePreview") return false; if (setting === "RoomList.OrderedCustomSections") return []; if (setting === "RoomList.CustomSectionData") return {}; return false; }); - jest.spyOn(SettingsStore, "setValue").mockResolvedValue(undefined); - jest.spyOn(SettingsStore, "watchSetting").mockImplementation(() => "watcher-id"); + vi.spyOn(SettingsStore, "setValue").mockResolvedValue(undefined); + vi.spyOn(SettingsStore, "watchSetting").mockImplementation(() => "watcher-id"); - jest.spyOn(MessagePreviewStore.instance, "getPreviewForRoom").mockResolvedValue(null); - jest.spyOn(CallStore.instance, "getCall").mockReturnValue(null); - jest.spyOn(RoomListStoreV3.instance, "orderedSectionTags", "get").mockReturnValue([]); + vi.spyOn(MessagePreviewStore.instance, "getPreviewForRoom").mockResolvedValue(null); + vi.spyOn(CallStore.instance, "getCall").mockReturnValue(null); + vi.spyOn(RoomListStoreV3.instance, "orderedSectionTags", "get").mockReturnValue([]); }); afterEach(() => { viewModel?.dispose(); - jest.restoreAllMocks(); + vi.restoreAllMocks(); }); describe("Initialization", () => { @@ -109,8 +112,8 @@ describe("RoomListItemViewModel", () => { }); it("should load message preview when enabled", async () => { - jest.spyOn(SettingsStore, "getValue").mockReturnValue(true); - jest.spyOn(MessagePreviewStore.instance, "getPreviewForRoom").mockResolvedValue({ + vi.spyOn(SettingsStore, "getValue").mockReturnValue(true); + vi.spyOn(MessagePreviewStore.instance, "getPreviewForRoom").mockResolvedValue({ text: "Hello world!", } as MessagePreview); @@ -123,7 +126,7 @@ describe("RoomListItemViewModel", () => { }); it("should not load message preview when disabled", async () => { - jest.spyOn(SettingsStore, "getValue").mockReturnValue(false); + vi.spyOn(SettingsStore, "getValue").mockReturnValue(false); viewModel = new RoomListItemViewModel({ room, client: matrixClient }); @@ -135,8 +138,8 @@ describe("RoomListItemViewModel", () => { describe("Notification state", () => { it("should reflect notification state", async () => { - jest.spyOn(notificationState, "hasAnyNotificationOrActivity", "get").mockReturnValue(true); - jest.spyOn(notificationState, "count", "get").mockReturnValue(5); + vi.spyOn(notificationState, "hasAnyNotificationOrActivity", "get").mockReturnValue(true); + vi.spyOn(notificationState, "count", "get").mockReturnValue(5); viewModel = new RoomListItemViewModel({ room, client: matrixClient }); @@ -153,7 +156,7 @@ describe("RoomListItemViewModel", () => { await flushPromises(); expect(viewModel.getSnapshot().notification.count).toBe(0); - jest.spyOn(notificationState, "count", "get").mockReturnValue(3); + vi.spyOn(notificationState, "count", "get").mockReturnValue(3); notificationState.emit(NotificationStateEvents.Update); await flushPromises(); @@ -161,7 +164,7 @@ describe("RoomListItemViewModel", () => { }); it("should show bold text when has notifications", async () => { - jest.spyOn(notificationState, "hasAnyNotificationOrActivity", "get").mockReturnValue(true); + vi.spyOn(notificationState, "hasAnyNotificationOrActivity", "get").mockReturnValue(true); viewModel = new RoomListItemViewModel({ room, client: matrixClient }); @@ -171,7 +174,7 @@ describe("RoomListItemViewModel", () => { }); it("should show mention badge", async () => { - jest.spyOn(notificationState, "isMention", "get").mockReturnValue(true); + vi.spyOn(notificationState, "isMention", "get").mockReturnValue(true); viewModel = new RoomListItemViewModel({ room, client: matrixClient }); @@ -181,7 +184,7 @@ describe("RoomListItemViewModel", () => { }); it("should show invitation state", async () => { - jest.spyOn(notificationState, "invited", "get").mockReturnValue(true); + vi.spyOn(notificationState, "invited", "get").mockReturnValue(true); viewModel = new RoomListItemViewModel({ room, client: matrixClient }); @@ -193,8 +196,8 @@ describe("RoomListItemViewModel", () => { describe("Message preview", () => { it("should update message preview when store emits update", async () => { - jest.spyOn(SettingsStore, "getValue").mockReturnValue(true); - jest.spyOn(MessagePreviewStore.instance, "getPreviewForRoom").mockResolvedValue({ + vi.spyOn(SettingsStore, "getValue").mockReturnValue(true); + vi.spyOn(MessagePreviewStore.instance, "getPreviewForRoom").mockResolvedValue({ text: "Initial message", } as MessagePreview); @@ -204,7 +207,7 @@ describe("RoomListItemViewModel", () => { expect(viewModel.getSnapshot().messagePreview).toBe("Initial message"); // Update preview - jest.spyOn(MessagePreviewStore.instance, "getPreviewForRoom").mockResolvedValue({ + vi.spyOn(MessagePreviewStore.instance, "getPreviewForRoom").mockResolvedValue({ text: "Updated message", } as MessagePreview); @@ -218,12 +221,12 @@ describe("RoomListItemViewModel", () => { let showPreview = false; let watchCallback: any; - jest.spyOn(SettingsStore, "getValue").mockImplementation(() => showPreview); - jest.spyOn(SettingsStore, "watchSetting").mockImplementation((setting, _room, callback) => { + vi.spyOn(SettingsStore, "getValue").mockImplementation(() => showPreview); + vi.spyOn(SettingsStore, "watchSetting").mockImplementation((setting, _room, callback) => { if (setting === "RoomList.showMessagePreview") watchCallback = callback; return "watcher-id"; }); - jest.spyOn(MessagePreviewStore.instance, "getPreviewForRoom").mockResolvedValue({ + vi.spyOn(MessagePreviewStore.instance, "getPreviewForRoom").mockResolvedValue({ text: "Test message", } as MessagePreview); @@ -285,11 +288,11 @@ describe("RoomListItemViewModel", () => { const mockCall = { callType: CallType.Voice, participants: new Map([[matrixClient.getUserId()!, {}]]), - off: jest.fn(), - on: jest.fn(), + off: vi.fn(), + on: vi.fn(), } as unknown as Call; - jest.spyOn(CallStore.instance, "getCall").mockReturnValue(mockCall); + vi.spyOn(CallStore.instance, "getCall").mockReturnValue(mockCall); viewModel = new RoomListItemViewModel({ room, client: matrixClient }); @@ -302,11 +305,11 @@ describe("RoomListItemViewModel", () => { const mockCall = { callType: CallType.Video, participants: new Map([[matrixClient.getUserId()!, {}]]), - off: jest.fn(), - on: jest.fn(), + off: vi.fn(), + on: vi.fn(), } as unknown as Call; - jest.spyOn(CallStore.instance, "getCall").mockReturnValue(mockCall); + vi.spyOn(CallStore.instance, "getCall").mockReturnValue(mockCall); viewModel = new RoomListItemViewModel({ room, client: matrixClient }); @@ -319,11 +322,11 @@ describe("RoomListItemViewModel", () => { const mockCall = { callType: CallType.Voice, participants: new Map(), - off: jest.fn(), - on: jest.fn(), + off: vi.fn(), + on: vi.fn(), } as unknown as Call; - jest.spyOn(CallStore.instance, "getCall").mockReturnValue(mockCall); + vi.spyOn(CallStore.instance, "getCall").mockReturnValue(mockCall); viewModel = new RoomListItemViewModel({ room, client: matrixClient }); @@ -336,16 +339,16 @@ describe("RoomListItemViewModel", () => { const mockCall = { callType: CallType.Voice, participants: new Map(), - off: jest.fn(), - on: jest.fn(), + off: vi.fn(), + on: vi.fn(), }; - jest.spyOn(CallStore.instance, "getCall").mockReturnValue(mockCall as unknown as Call); + vi.spyOn(CallStore.instance, "getCall").mockReturnValue(mockCall as unknown as Call); viewModel = new RoomListItemViewModel({ room, client: matrixClient }); expect(viewModel.getSnapshot().notification.callType).toBeUndefined(); // Get the callback registered for call state changes - const mockCalls = (CallStore.instance.on as jest.Mock).mock.calls; + const mockCalls = (CallStore.instance.on as Mock).mock.calls; const callStateCallback = mockCalls[mockCalls.length - 1][1]; callStateCallback(); @@ -363,15 +366,15 @@ describe("RoomListItemViewModel", () => { const mockCall = { callType: CallType.Voice, participants: new Map([[matrixClient.getUserId()! as unknown as RoomMember, new Set()]]), - off: jest.fn(), - on: jest.fn(), + off: vi.fn(), + on: vi.fn(), }; - jest.spyOn(CallStore.instance, "getCall").mockReturnValue(mockCall as unknown as Call); + vi.spyOn(CallStore.instance, "getCall").mockReturnValue(mockCall as unknown as Call); viewModel = new RoomListItemViewModel({ room, client: matrixClient }); // Trigger onCallStateChanged so the call is tracked and the participant listener is registered - const mockCalls = (CallStore.instance.on as jest.Mock).mock.calls; + const mockCalls = (CallStore.instance.on as Mock).mock.calls; const callStateCallback = mockCalls[mockCalls.length - 1][1]; callStateCallback(); @@ -393,10 +396,10 @@ describe("RoomListItemViewModel", () => { const mockCall = { callType: CallType.Voice, participants: new Map([]), - off: jest.fn(), - on: jest.fn(), + off: vi.fn(), + on: vi.fn(), }; - jest.spyOn(CallStore.instance, "getCall").mockReturnValue(mockCall as unknown as Call); + vi.spyOn(CallStore.instance, "getCall").mockReturnValue(mockCall as unknown as Call); viewModel = new RoomListItemViewModel({ room, client: matrixClient }); expect(viewModel.getSnapshot().notification.callType).toBeUndefined(); @@ -415,21 +418,21 @@ describe("RoomListItemViewModel", () => { const firstCall = { callType: CallType.Voice, participants: new Map([[matrixClient.getUserId()! as unknown as RoomMember, new Set()]]), - off: jest.fn(), - on: jest.fn(), + off: vi.fn(), + on: vi.fn(), }; const secondCall = { callType: CallType.Video, participants: new Map([[matrixClient.getUserId()! as unknown as RoomMember, new Set()]]), - off: jest.fn(), - on: jest.fn(), + off: vi.fn(), + on: vi.fn(), }; - jest.spyOn(CallStore.instance, "getCall").mockReturnValue(firstCall as unknown as Call); + vi.spyOn(CallStore.instance, "getCall").mockReturnValue(firstCall as unknown as Call); viewModel = new RoomListItemViewModel({ room, client: matrixClient }); // Trigger onCallStateChanged to register the first call - const mockCalls = (CallStore.instance.on as jest.Mock).mock.calls; + const mockCalls = (CallStore.instance.on as Mock).mock.calls; const callStateCallback = mockCalls[mockCalls.length - 1][1]; callStateCallback(); @@ -437,7 +440,7 @@ describe("RoomListItemViewModel", () => { expect(firstCall.on).toHaveBeenCalledWith("participants", participantsCallback); // Now switch to a different call - jest.spyOn(CallStore.instance, "getCall").mockReturnValue(secondCall as unknown as Call); + vi.spyOn(CallStore.instance, "getCall").mockReturnValue(secondCall as unknown as Call); callStateCallback(); // The old call's listener must have been removed @@ -455,7 +458,7 @@ describe("RoomListItemViewModel", () => { } participants = new Map([[matrixClient.getUserId()!, {}]]); })() as unknown as Call; - jest.spyOn(CallStore.instance, "getCall").mockReturnValue(mockCall); + vi.spyOn(CallStore.instance, "getCall").mockReturnValue(mockCall); viewModel = new RoomListItemViewModel({ room, client: matrixClient }); await flushPromises(); @@ -487,7 +490,7 @@ describe("RoomListItemViewModel", () => { describe("DM detection", () => { it("should detect DM rooms", async () => { const dmRoomMap = DMRoomMap.shared(); - jest.spyOn(dmRoomMap, "getUserIdForRoomId").mockReturnValue("@user:server"); + vi.spyOn(dmRoomMap, "getUserIdForRoomId").mockReturnValue("@user:server"); viewModel = new RoomListItemViewModel({ room, client: matrixClient }); @@ -499,7 +502,7 @@ describe("RoomListItemViewModel", () => { it("should detect non-DM rooms", async () => { const dmRoomMap = DMRoomMap.shared(); - jest.spyOn(dmRoomMap, "getUserIdForRoomId").mockReturnValue(undefined); + vi.spyOn(dmRoomMap, "getUserIdForRoomId").mockReturnValue(undefined); viewModel = new RoomListItemViewModel({ room, client: matrixClient }); @@ -513,7 +516,7 @@ describe("RoomListItemViewModel", () => { it("should dispatch view room action on openRoom", () => { viewModel = new RoomListItemViewModel({ room, client: matrixClient }); - const dispatchSpy = jest.spyOn(dispatcher, "dispatch"); + const dispatchSpy = vi.spyOn(dispatcher, "dispatch"); viewModel.onOpenRoom(); @@ -532,7 +535,7 @@ describe("RoomListItemViewModel", () => { it("should dispatch view_invite action when onInvite is called", () => { viewModel = new RoomListItemViewModel({ room, client: matrixClient }); - const dispatchSpy = jest.spyOn(dispatcher, "dispatch"); + const dispatchSpy = vi.spyOn(dispatcher, "dispatch"); viewModel.onInvite(); @@ -544,7 +547,7 @@ describe("RoomListItemViewModel", () => { it("should dispatch copy_room action when onCopyRoomLink is called", () => { viewModel = new RoomListItemViewModel({ room, client: matrixClient }); - const dispatchSpy = jest.spyOn(dispatcher, "dispatch"); + const dispatchSpy = vi.spyOn(dispatcher, "dispatch"); viewModel.onCopyRoomLink(); @@ -557,7 +560,7 @@ describe("RoomListItemViewModel", () => { it("should dispatch leave_room action when onLeaveRoom is called for normal room", () => { room.tags = {}; viewModel = new RoomListItemViewModel({ room, client: matrixClient }); - const dispatchSpy = jest.spyOn(dispatcher, "dispatch"); + const dispatchSpy = vi.spyOn(dispatcher, "dispatch"); viewModel.onLeaveRoom(); @@ -571,7 +574,7 @@ describe("RoomListItemViewModel", () => { room.tags = { [DefaultTagID.Archived]: { order: 0 } }; viewModel = new RoomListItemViewModel({ room, client: matrixClient }); - const dispatchSpy = jest.spyOn(dispatcher, "dispatch"); + const dispatchSpy = vi.spyOn(dispatcher, "dispatch"); viewModel.onLeaveRoom(); @@ -582,10 +585,10 @@ describe("RoomListItemViewModel", () => { }); it("should call createSection on RoomListStoreV3 when onCreateSection is called", async () => { - const createSectionSpy = jest + const createSectionSpy = vi .spyOn(RoomListStoreV3.instance, "createSection") .mockResolvedValue("element.io.section.work"); - const tagRoomSpy = jest.spyOn(tagRoomModule, "tagRoom").mockImplementation(() => {}); + const tagRoomSpy = vi.spyOn(tagRoomModule, "tagRoom").mockImplementation(() => {}); viewModel = new RoomListItemViewModel({ room, client: matrixClient }); viewModel.onCreateSection(); @@ -595,7 +598,7 @@ describe("RoomListItemViewModel", () => { }); it("should call tagRoom when onToggleSection is called", () => { - const tagRoomSpy = jest.spyOn(tagRoomModule, "tagRoom").mockImplementation(() => {}); + const tagRoomSpy = vi.spyOn(tagRoomModule, "tagRoom").mockImplementation(() => {}); viewModel = new RoomListItemViewModel({ room, client: matrixClient }); viewModel.onToggleSection(DefaultTagID.Favourite); @@ -608,7 +611,7 @@ describe("RoomListItemViewModel", () => { const customTag = "element.io.section.custom1"; beforeEach(() => { - jest.spyOn(RoomListStoreV3.instance, "orderedSectionTags", "get").mockReturnValue([ + vi.spyOn(RoomListStoreV3.instance, "orderedSectionTags", "get").mockReturnValue([ DefaultTagID.Favourite, customTag, CHATS_TAG, @@ -633,7 +636,7 @@ describe("RoomListItemViewModel", () => { }); it("should use custom section name from CustomSectionData", () => { - jest.spyOn(SettingsStore, "getValue").mockImplementation((setting) => { + vi.spyOn(SettingsStore, "getValue").mockImplementation((setting) => { if (setting === "RoomList.CustomSectionData") return { [customTag]: { name: "My Custom Section", tag: customTag } }; return false; @@ -646,7 +649,7 @@ describe("RoomListItemViewModel", () => { it("should update sections when OrderedCustomSections setting changes", () => { let watchCallback: CallbackFn<"RoomList.OrderedCustomSections"> = () => {}; - jest.spyOn(SettingsStore, "watchSetting").mockImplementation((setting, _room, callback) => { + vi.spyOn(SettingsStore, "watchSetting").mockImplementation((setting, _room, callback) => { if (setting === "RoomList.OrderedCustomSections") watchCallback = callback; return "watcher-id"; }); @@ -655,7 +658,7 @@ describe("RoomListItemViewModel", () => { expect(viewModel.getSnapshot().sections).toHaveLength(1); // Simulate reordering: custom section removed - jest.spyOn(RoomListStoreV3.instance, "orderedSectionTags", "get").mockReturnValue([ + vi.spyOn(RoomListStoreV3.instance, "orderedSectionTags", "get").mockReturnValue([ DefaultTagID.Favourite, CHATS_TAG, DefaultTagID.LowPriority, @@ -666,7 +669,7 @@ describe("RoomListItemViewModel", () => { }); it("should set areSectionsEnabled to true when RoomList.showSections is enabled", () => { - jest.spyOn(SettingsStore, "getValue").mockImplementation((setting) => { + vi.spyOn(SettingsStore, "getValue").mockImplementation((setting) => { if (setting === "RoomList.showSections") return true; return false; }); @@ -677,7 +680,7 @@ describe("RoomListItemViewModel", () => { it("should update areSectionsEnabled when RoomList.showSections setting changes", () => { let watchCallback: CallbackFn<"RoomList.showSections"> = () => {}; - jest.spyOn(SettingsStore, "watchSetting").mockImplementation((setting, _room, callback) => { + vi.spyOn(SettingsStore, "watchSetting").mockImplementation((setting, _room, callback) => { if (setting === "RoomList.showSections") watchCallback = callback; return "watcher-id"; }); @@ -686,7 +689,7 @@ describe("RoomListItemViewModel", () => { expect(viewModel.getSnapshot().areSectionsEnabled).toBe(false); // Enable sections - jest.spyOn(SettingsStore, "getValue").mockImplementation((setting) => { + vi.spyOn(SettingsStore, "getValue").mockImplementation((setting) => { if (setting === "RoomList.showSections") return true; return false; }); @@ -700,7 +703,7 @@ describe("RoomListItemViewModel", () => { it("should unsubscribe from all events on dispose", () => { viewModel = new RoomListItemViewModel({ room, client: matrixClient }); - const offSpy = jest.spyOn(notificationState, "off"); + const offSpy = vi.spyOn(notificationState, "off"); viewModel.dispose(); diff --git a/apps/web/test/viewmodels/room-list/RoomListSearchViewModel-test.ts b/apps/web/src/viewmodels/room-list/RoomListSearchViewModel.test.ts similarity index 71% rename from apps/web/test/viewmodels/room-list/RoomListSearchViewModel-test.ts rename to apps/web/src/viewmodels/room-list/RoomListSearchViewModel.test.ts index 971ff655e6..a8f3d43462 100644 --- a/apps/web/test/viewmodels/room-list/RoomListSearchViewModel-test.ts +++ b/apps/web/src/viewmodels/room-list/RoomListSearchViewModel.test.ts @@ -5,40 +5,44 @@ * Please see LICENSE files in the repository root for full details. */ -import { mocked } from "jest-mock"; +// @vitest-environment happy-dom -import { RoomListSearchViewModel } from "../../../src/viewmodels/room-list/RoomListSearchViewModel"; -import { MetaSpace } from "../../../src/stores/spaces"; -import { shouldShowComponent } from "../../../src/customisations/helpers/UIComponents"; -import defaultDispatcher from "../../../src/dispatcher/dispatcher"; -import { Action } from "../../../src/dispatcher/actions"; -import LegacyCallHandler, { LegacyCallHandlerEvent } from "../../../src/LegacyCallHandler"; -import { TestSDKContext } from "../../unit-tests/TestSDKContext.ts"; +import { vi, describe, it, expect, beforeEach, afterEach } from "vitest"; +import { TestSDKContext } from "test-utils"; -jest.mock("../../../src/customisations/helpers/UIComponents", () => ({ - shouldShowComponent: jest.fn(), +import { RoomListSearchViewModel } from "./RoomListSearchViewModel"; +import { MetaSpace } from "../../stores/spaces"; +import { shouldShowComponent } from "../../customisations/helpers/UIComponents"; +import defaultDispatcher from "../../dispatcher/dispatcher"; +import { Action } from "../../dispatcher/actions"; +import LegacyCallHandler, { LegacyCallHandlerEvent } from "../../LegacyCallHandler"; + +vi.mock("../../customisations/helpers/UIComponents", () => ({ + shouldShowComponent: vi.fn(), })); -jest.mock("../../../src/PosthogTrackers", () => ({ - trackInteraction: jest.fn(), +vi.mock("../../PosthogTrackers", () => ({ + default: { + trackInteraction: vi.fn(), + }, })); describe("RoomListSearchViewModel", () => { const context = new TestSDKContext(); beforeEach(() => { - mocked(shouldShowComponent).mockReturnValue(true); + vi.mocked(shouldShowComponent).mockReturnValue(true); context._LegacyCallHandler = new LegacyCallHandler(context); - jest.spyOn(context._LegacyCallHandler, "getSupportsPstnProtocol").mockReturnValue(false); + vi.spyOn(context._LegacyCallHandler, "getSupportsPstnProtocol").mockReturnValue(false); }); afterEach(() => { - jest.restoreAllMocks(); + vi.restoreAllMocks(); }); describe("snapshot", () => { it("should show explore button in Home space when UIComponent.ExploreRooms is enabled", () => { - mocked(shouldShowComponent).mockReturnValue(true); + vi.mocked(shouldShowComponent).mockReturnValue(true); const vm = new RoomListSearchViewModel({ activeSpace: MetaSpace.Home, legacyCallHandler: context.legacyCallHandler, @@ -48,7 +52,7 @@ describe("RoomListSearchViewModel", () => { }); it("should hide explore button when not in Home space", () => { - mocked(shouldShowComponent).mockReturnValue(true); + vi.mocked(shouldShowComponent).mockReturnValue(true); const vm = new RoomListSearchViewModel({ activeSpace: MetaSpace.VideoRooms, legacyCallHandler: context.legacyCallHandler, @@ -58,7 +62,7 @@ describe("RoomListSearchViewModel", () => { }); it("should hide explore button when UIComponent.ExploreRooms is disabled", () => { - mocked(shouldShowComponent).mockReturnValue(false); + vi.mocked(shouldShowComponent).mockReturnValue(false); const vm = new RoomListSearchViewModel({ activeSpace: MetaSpace.Home, legacyCallHandler: context.legacyCallHandler, @@ -68,7 +72,7 @@ describe("RoomListSearchViewModel", () => { }); it("should show dial button when PSTN protocol is supported", () => { - jest.spyOn(context.legacyCallHandler, "getSupportsPstnProtocol").mockReturnValue(true); + vi.spyOn(context.legacyCallHandler, "getSupportsPstnProtocol").mockReturnValue(true); const vm = new RoomListSearchViewModel({ activeSpace: MetaSpace.Home, legacyCallHandler: context.legacyCallHandler, @@ -78,7 +82,7 @@ describe("RoomListSearchViewModel", () => { }); it("should hide dial button when PSTN protocol is not supported", () => { - jest.spyOn(context.legacyCallHandler, "getSupportsPstnProtocol").mockReturnValue(false); + vi.spyOn(context.legacyCallHandler, "getSupportsPstnProtocol").mockReturnValue(false); const vm = new RoomListSearchViewModel({ activeSpace: MetaSpace.Home, legacyCallHandler: context.legacyCallHandler, @@ -90,7 +94,7 @@ describe("RoomListSearchViewModel", () => { describe("actions", () => { it("should fire OpenSpotlight action when onSearchClick is called", () => { - const fireSpy = jest.spyOn(defaultDispatcher, "fire"); + const fireSpy = vi.spyOn(defaultDispatcher, "fire"); const vm = new RoomListSearchViewModel({ activeSpace: MetaSpace.Home, legacyCallHandler: context.legacyCallHandler, @@ -101,7 +105,7 @@ describe("RoomListSearchViewModel", () => { }); it("should fire OpenDialPad action when onDialPadClick is called", () => { - const fireSpy = jest.spyOn(defaultDispatcher, "fire"); + const fireSpy = vi.spyOn(defaultDispatcher, "fire"); const vm = new RoomListSearchViewModel({ activeSpace: MetaSpace.Home, legacyCallHandler: context.legacyCallHandler, @@ -112,7 +116,7 @@ describe("RoomListSearchViewModel", () => { }); it("should fire ViewRoomDirectory action and track interaction when onExploreClick is called", () => { - const fireSpy = jest.spyOn(defaultDispatcher, "fire"); + const fireSpy = vi.spyOn(defaultDispatcher, "fire"); const vm = new RoomListSearchViewModel({ activeSpace: MetaSpace.Home, legacyCallHandler: context.legacyCallHandler, @@ -126,7 +130,7 @@ describe("RoomListSearchViewModel", () => { }); it("should update snapshot when PSTN protocol support changes", () => { - jest.spyOn(context.legacyCallHandler, "getSupportsPstnProtocol").mockReturnValue(false); + vi.spyOn(context.legacyCallHandler, "getSupportsPstnProtocol").mockReturnValue(false); const vm = new RoomListSearchViewModel({ activeSpace: MetaSpace.Home, legacyCallHandler: context.legacyCallHandler, @@ -135,7 +139,7 @@ describe("RoomListSearchViewModel", () => { expect(vm.getSnapshot().displayDialButton).toBe(false); // Simulate PSTN protocol support change - jest.spyOn(context.legacyCallHandler, "getSupportsPstnProtocol").mockReturnValue(true); + vi.spyOn(context.legacyCallHandler, "getSupportsPstnProtocol").mockReturnValue(true); context.legacyCallHandler.emit(LegacyCallHandlerEvent.ProtocolSupport); expect(vm.getSnapshot().displayDialButton).toBe(true); diff --git a/apps/web/test/viewmodels/room-list/RoomListSectionHeaderViewModel-test.ts b/apps/web/src/viewmodels/room-list/RoomListSectionHeaderViewModel.test.ts similarity index 80% rename from apps/web/test/viewmodels/room-list/RoomListSectionHeaderViewModel-test.ts rename to apps/web/src/viewmodels/room-list/RoomListSectionHeaderViewModel.test.ts index 76fcf14e59..13ffc0d754 100644 --- a/apps/web/test/viewmodels/room-list/RoomListSectionHeaderViewModel-test.ts +++ b/apps/web/src/viewmodels/room-list/RoomListSectionHeaderViewModel.test.ts @@ -5,41 +5,44 @@ * Please see LICENSE files in the repository root for full details. */ +// @vitest-environment happy-dom + +import { vi, describe, it, expect, beforeEach, afterEach, type Mock } from "vitest"; import { type MatrixClient, type Room } from "matrix-js-sdk/src/matrix"; import { CallType } from "matrix-js-sdk/src/webrtc/call"; +import { createTestClient, mkRoom } from "test-utils"; -import { RoomListSectionHeaderViewModel } from "../../../src/viewmodels/room-list/RoomListSectionHeaderViewModel"; -import { RoomNotificationState } from "../../../src/stores/notifications/RoomNotificationState"; -import { RoomNotificationStateStore } from "../../../src/stores/notifications/RoomNotificationStateStore"; -import { NotificationStateEvents } from "../../../src/stores/notifications/NotificationState"; -import { CallStore } from "../../../src/stores/CallStore"; -import { type Call } from "../../../src/models/Call"; -import { createTestClient, mkRoom } from "../../test-utils"; -import SettingsStore from "../../../src/settings/SettingsStore"; -import { SettingLevel } from "../../../src/settings/SettingLevel"; -import RoomListStoreV3 from "../../../src/stores/room-list-v3/RoomListStoreV3"; -import { DefaultTagID } from "../../../src/stores/room-list-v3/skip-list/tag"; -import { CHATS_TAG, type SectionExpansionState } from "../../../src/stores/room-list-v3/section"; +import { RoomListSectionHeaderViewModel } from "./RoomListSectionHeaderViewModel"; +import { RoomNotificationState } from "../../stores/notifications/RoomNotificationState"; +import { RoomNotificationStateStore } from "../../stores/notifications/RoomNotificationStateStore"; +import { NotificationStateEvents } from "../../stores/notifications/NotificationState"; +import { CallStore } from "../../stores/CallStore"; +import { type Call } from "../../models/Call"; +import SettingsStore from "../../settings/SettingsStore"; +import { SettingLevel } from "../../settings/SettingLevel"; +import RoomListStoreV3 from "../../stores/room-list-v3/RoomListStoreV3"; +import { DefaultTagID } from "../../stores/room-list-v3/skip-list/tag"; +import { CHATS_TAG, type SectionExpansionState } from "../../stores/room-list-v3/section"; describe("RoomListSectionHeaderViewModel", () => { - let onToggleExpanded: jest.Mock; + let onToggleExpanded: Mock; let matrixClient: MatrixClient; // In-memory backing store shared between the getValue/setValue mocks so that // persisted expansion state round-trips within a test. let sectionExpansionState: SectionExpansionState; beforeEach(() => { - onToggleExpanded = jest.fn(); + onToggleExpanded = vi.fn(); matrixClient = createTestClient(); sectionExpansionState = {}; - jest.spyOn(SettingsStore, "watchSetting").mockReturnValue("watcher-id"); - jest.spyOn(SettingsStore, "unwatchSetting").mockReturnValue(undefined); - jest.spyOn(SettingsStore, "getValue").mockImplementation((setting) => { + vi.spyOn(SettingsStore, "watchSetting").mockReturnValue("watcher-id"); + vi.spyOn(SettingsStore, "unwatchSetting").mockReturnValue(undefined); + vi.spyOn(SettingsStore, "getValue").mockImplementation((setting) => { if (setting === "RoomList.OrderedCustomSections") return []; if (setting === "RoomList.SectionExpansionState") return sectionExpansionState; return null; }); - jest.spyOn(SettingsStore, "setValue").mockImplementation(async (setting, _roomId, _level, value) => { + vi.spyOn(SettingsStore, "setValue").mockImplementation(async (setting, _roomId, _level, value) => { if (setting === "RoomList.SectionExpansionState") { sectionExpansionState = value as SectionExpansionState; } @@ -47,7 +50,7 @@ describe("RoomListSectionHeaderViewModel", () => { }); afterEach(() => { - jest.restoreAllMocks(); + vi.restoreAllMocks(); }); it("should initialize snapshot from props", () => { @@ -125,7 +128,7 @@ describe("RoomListSectionHeaderViewModel", () => { }); it("should persist the expanded state at the device level on click", () => { - const setValue = jest.spyOn(SettingsStore, "setValue"); + const setValue = vi.spyOn(SettingsStore, "setValue"); const vm = new RoomListSectionHeaderViewModel({ tag: "m.favourite", title: "Favourites", @@ -142,7 +145,7 @@ describe("RoomListSectionHeaderViewModel", () => { }); it("should persist the expanded state at the device level when set via the setter", () => { - const setValue = jest.spyOn(SettingsStore, "setValue"); + const setValue = vi.spyOn(SettingsStore, "setValue"); const vm = new RoomListSectionHeaderViewModel({ tag: "m.favourite", title: "Favourites", @@ -195,7 +198,7 @@ describe("RoomListSectionHeaderViewModel", () => { let watchCallback: () => void; beforeEach(() => { - jest.spyOn(SettingsStore, "watchSetting").mockImplementation((settingName, _roomId, callback) => { + vi.spyOn(SettingsStore, "watchSetting").mockImplementation((settingName, _roomId, callback) => { if (settingName === "RoomList.CustomSectionData") watchCallback = callback as () => void; return "watcher-id"; }); @@ -211,7 +214,7 @@ describe("RoomListSectionHeaderViewModel", () => { }); expect(vm.getSnapshot().title).toBe("Old Title"); - jest.spyOn(SettingsStore, "getValue").mockReturnValue({ [tag]: { tag, name: "New Title" } }); + vi.spyOn(SettingsStore, "getValue").mockReturnValue({ [tag]: { tag, name: "New Title" } }); watchCallback(); expect(vm.getSnapshot().title).toBe("New Title"); @@ -226,7 +229,7 @@ describe("RoomListSectionHeaderViewModel", () => { onToggleExpanded, }); - jest.spyOn(SettingsStore, "getValue").mockReturnValue({}); + vi.spyOn(SettingsStore, "getValue").mockReturnValue({}); watchCallback(); expect(vm.getSnapshot().title).toBe("My Section"); @@ -248,7 +251,7 @@ describe("RoomListSectionHeaderViewModel", () => { describe("editSection", () => { it("should delegate to RoomListStoreV3.instance.editSection", async () => { - const editSectionSpy = jest.spyOn(RoomListStoreV3.instance, "editSection").mockResolvedValue(undefined); + const editSectionSpy = vi.spyOn(RoomListStoreV3.instance, "editSection").mockResolvedValue(undefined); const tag = "element.io.section.custom"; const vm = new RoomListSectionHeaderViewModel({ tag, @@ -265,15 +268,15 @@ describe("RoomListSectionHeaderViewModel", () => { describe("removeSection", () => { beforeEach(() => { const mockState = { - on: jest.fn(), - off: jest.fn(), + on: vi.fn(), + off: vi.fn(), hasAnyNotificationOrActivity: false, } as unknown as RoomNotificationState; - jest.spyOn(RoomNotificationStateStore.instance, "getRoomState").mockReturnValue(mockState); + vi.spyOn(RoomNotificationStateStore.instance, "getRoomState").mockReturnValue(mockState); }); it("should delegate to RoomListStoreV3.instance.removeSection with isEmpty=true when no rooms", async () => { - const removeSectionSpy = jest.spyOn(RoomListStoreV3.instance, "removeSection").mockResolvedValue(undefined); + const removeSectionSpy = vi.spyOn(RoomListStoreV3.instance, "removeSection").mockResolvedValue(undefined); const tag = "element.io.section.custom"; const vm = new RoomListSectionHeaderViewModel({ tag, @@ -287,7 +290,7 @@ describe("RoomListSectionHeaderViewModel", () => { }); it("should delegate to RoomListStoreV3.instance.removeSection with isEmpty=false when rooms exist", async () => { - const removeSectionSpy = jest.spyOn(RoomListStoreV3.instance, "removeSection").mockResolvedValue(undefined); + const removeSectionSpy = vi.spyOn(RoomListStoreV3.instance, "removeSection").mockResolvedValue(undefined); const tag = "element.io.section.custom"; const vm = new RoomListSectionHeaderViewModel({ tag, @@ -307,14 +310,14 @@ describe("RoomListSectionHeaderViewModel", () => { let notificationState: RoomNotificationState; beforeEach(() => { - jest.useFakeTimers(); + vi.useFakeTimers(); room = mkRoom(matrixClient, "!room:server"); notificationState = new RoomNotificationState(room, false); - jest.spyOn(RoomNotificationStateStore.instance, "getRoomState").mockReturnValue(notificationState); + vi.spyOn(RoomNotificationStateStore.instance, "getRoomState").mockReturnValue(notificationState); }); afterEach(() => { - jest.useRealTimers(); + vi.useRealTimers(); }); it("should set isUnread to false when no rooms have notifications", () => { @@ -330,7 +333,7 @@ describe("RoomListSectionHeaderViewModel", () => { }); it("should set isUnread to true when a room has notifications", () => { - jest.spyOn(notificationState, "hasAnyNotificationOrActivity", "get").mockReturnValue(true); + vi.spyOn(notificationState, "hasAnyNotificationOrActivity", "get").mockReturnValue(true); const vm = new RoomListSectionHeaderViewModel({ tag: "m.favourite", @@ -347,13 +350,13 @@ describe("RoomListSectionHeaderViewModel", () => { const room2 = mkRoom(matrixClient, "!room2:server"); const notificationState2 = new RoomNotificationState(room2, false); - jest.spyOn(RoomNotificationStateStore.instance, "getRoomState") + vi.spyOn(RoomNotificationStateStore.instance, "getRoomState") .mockReturnValueOnce(notificationState) .mockReturnValue(notificationState2); - jest.spyOn(notificationState, "on"); - jest.spyOn(notificationState, "off"); - jest.spyOn(notificationState2, "on"); + vi.spyOn(notificationState, "on"); + vi.spyOn(notificationState, "off"); + vi.spyOn(notificationState2, "on"); const vm = new RoomListSectionHeaderViewModel({ tag: "m.favourite", @@ -386,10 +389,10 @@ describe("RoomListSectionHeaderViewModel", () => { expect(vm.getSnapshot().isUnread).toBe(false); - jest.spyOn(notificationState, "hasAnyNotificationOrActivity", "get").mockReturnValue(true); + vi.spyOn(notificationState, "hasAnyNotificationOrActivity", "get").mockReturnValue(true); notificationState.emit(NotificationStateEvents.Update); - jest.advanceTimersByTime(200); + vi.advanceTimersByTime(200); expect(vm.getSnapshot().isUnread).toBe(true); }); @@ -416,8 +419,8 @@ describe("RoomListSectionHeaderViewModel", () => { }); it("should not show the activity dot for an activity-only section", () => { - jest.spyOn(notificationState, "hasAnyNotificationOrActivity", "get").mockReturnValue(true); - jest.spyOn(notificationState, "isActivityNotification", "get").mockReturnValue(true); + vi.spyOn(notificationState, "hasAnyNotificationOrActivity", "get").mockReturnValue(true); + vi.spyOn(notificationState, "isActivityNotification", "get").mockReturnValue(true); const vm = new RoomListSectionHeaderViewModel({ tag: "m.favourite", @@ -441,17 +444,17 @@ describe("RoomListSectionHeaderViewModel", () => { const room2 = mkRoom(matrixClient, "!room2:server"); const notificationState2 = new RoomNotificationState(room2, false); - jest.spyOn(RoomNotificationStateStore.instance, "getRoomState") + vi.spyOn(RoomNotificationStateStore.instance, "getRoomState") .mockReturnValueOnce(notificationState) .mockReturnValue(notificationState2); - jest.spyOn(notificationState, "isMention", "get").mockReturnValue(true); - jest.spyOn(notificationState, "count", "get").mockReturnValue(3); - jest.spyOn(notificationState, "hasUnreadCount", "get").mockReturnValue(true); + vi.spyOn(notificationState, "isMention", "get").mockReturnValue(true); + vi.spyOn(notificationState, "count", "get").mockReturnValue(3); + vi.spyOn(notificationState, "hasUnreadCount", "get").mockReturnValue(true); - jest.spyOn(notificationState2, "isNotification", "get").mockReturnValue(true); - jest.spyOn(notificationState2, "count", "get").mockReturnValue(9); - jest.spyOn(notificationState2, "hasUnreadCount", "get").mockReturnValue(true); + vi.spyOn(notificationState2, "isNotification", "get").mockReturnValue(true); + vi.spyOn(notificationState2, "count", "get").mockReturnValue(9); + vi.spyOn(notificationState2, "hasUnreadCount", "get").mockReturnValue(true); const vm = new RoomListSectionHeaderViewModel({ tag: "m.favourite", @@ -474,7 +477,7 @@ describe("RoomListSectionHeaderViewModel", () => { }); it("should surface an unsent message from any room", () => { - jest.spyOn(notificationState, "isUnsentMessage", "get").mockReturnValue(true); + vi.spyOn(notificationState, "isUnsentMessage", "get").mockReturnValue(true); const vm = new RoomListSectionHeaderViewModel({ tag: "m.favourite", @@ -493,7 +496,7 @@ describe("RoomListSectionHeaderViewModel", () => { }); it("should aggregate an invitation from any room", () => { - jest.spyOn(notificationState, "invited", "get").mockReturnValue(true); + vi.spyOn(notificationState, "invited", "get").mockReturnValue(true); const vm = new RoomListSectionHeaderViewModel({ tag: "m.favourite", @@ -515,23 +518,23 @@ describe("RoomListSectionHeaderViewModel", () => { const room2 = mkRoom(matrixClient, "!room2:server"); const notificationState2 = new RoomNotificationState(room2, false); - jest.spyOn(RoomNotificationStateStore.instance, "getRoomState") + vi.spyOn(RoomNotificationStateStore.instance, "getRoomState") .mockReturnValueOnce(notificationState) .mockReturnValue(notificationState2); const voiceCall = { participants: new Map([["@a:server", new Set(["DEVICE"])]]), callType: CallType.Voice, - on: jest.fn(), - off: jest.fn(), + on: vi.fn(), + off: vi.fn(), } as unknown as Call; const videoCall = { participants: new Map([["@b:server", new Set(["DEVICE"])]]), callType: CallType.Video, - on: jest.fn(), - off: jest.fn(), + on: vi.fn(), + off: vi.fn(), } as unknown as Call; - jest.spyOn(CallStore.instance, "getCall").mockImplementation((roomId) => + vi.spyOn(CallStore.instance, "getCall").mockImplementation((roomId) => roomId === room.roomId ? voiceCall : videoCall, ); @@ -555,10 +558,10 @@ describe("RoomListSectionHeaderViewModel", () => { const call = { participants: new Map(), callType: CallType.Video, - on: jest.fn(), - off: jest.fn(), + on: vi.fn(), + off: vi.fn(), } as unknown as Call; - jest.spyOn(CallStore.instance, "getCall").mockReturnValue(call); + vi.spyOn(CallStore.instance, "getCall").mockReturnValue(call); const vm = new RoomListSectionHeaderViewModel({ tag: "m.favourite", @@ -573,10 +576,10 @@ describe("RoomListSectionHeaderViewModel", () => { it("should show a notification without a count badge for a mark-as-unread room", () => { // "Mark as unread" sets level=Notification with count=0 (no real notification events). - jest.spyOn(notificationState, "hasAnyNotificationOrActivity", "get").mockReturnValue(true); - jest.spyOn(notificationState, "isNotification", "get").mockReturnValue(true); - jest.spyOn(notificationState, "count", "get").mockReturnValue(0); - jest.spyOn(notificationState, "hasUnreadCount", "get").mockReturnValue(false); + vi.spyOn(notificationState, "hasAnyNotificationOrActivity", "get").mockReturnValue(true); + vi.spyOn(notificationState, "isNotification", "get").mockReturnValue(true); + vi.spyOn(notificationState, "count", "get").mockReturnValue(0); + vi.spyOn(notificationState, "hasUnreadCount", "get").mockReturnValue(false); const vm = new RoomListSectionHeaderViewModel({ tag: "m.favourite", @@ -609,16 +612,16 @@ describe("RoomListSectionHeaderViewModel", () => { expect(vm.getSnapshot().notification?.isMention).toBe(false); - jest.spyOn(notificationState, "isMention", "get").mockReturnValue(true); + vi.spyOn(notificationState, "isMention", "get").mockReturnValue(true); notificationState.emit(NotificationStateEvents.Update); - jest.advanceTimersByTime(200); + vi.advanceTimersByTime(200); expect(vm.getSnapshot().notification?.isMention).toBe(true); }); }); it("should unsubscribe from all notification states on dispose", () => { - jest.spyOn(notificationState, "off"); + vi.spyOn(notificationState, "off"); const vm = new RoomListSectionHeaderViewModel({ tag: "m.favourite", diff --git a/apps/web/test/viewmodels/room-list/RoomListViewModel-test.ts b/apps/web/src/viewmodels/room-list/RoomListViewModel.test.ts similarity index 86% rename from apps/web/test/viewmodels/room-list/RoomListViewModel-test.ts rename to apps/web/src/viewmodels/room-list/RoomListViewModel.test.ts index 39ba3cd00a..7e0a8f40df 100644 --- a/apps/web/test/viewmodels/room-list/RoomListViewModel-test.ts +++ b/apps/web/src/viewmodels/room-list/RoomListViewModel.test.ts @@ -5,10 +5,11 @@ * Please see LICENSE files in the repository root for full details. */ -import { type MatrixClient, type Room } from "matrix-js-sdk/src/matrix"; -import { mocked } from "jest-mock"; -import { waitFor } from "jest-matrix-react"; +// @vitest-environment happy-dom +import { vi, describe, it, expect, beforeEach, afterEach } from "vitest"; +import { type MatrixClient, type Room } from "matrix-js-sdk/src/matrix"; +import { waitFor } from "test-utils-rtl"; import { createTestClient, flushPromises, @@ -16,40 +17,37 @@ import { mkStubRoom, stubClient, TestSDKContext, -} from "../../test-utils"; -import RoomListStoreV3, { RoomListStoreV3Event } from "../../../src/stores/room-list-v3/RoomListStoreV3"; -import { FilterEnum } from "../../../src/stores/room-list-v3/skip-list/filters"; -import dispatcher from "../../../src/dispatcher/dispatcher"; -import { Action } from "../../../src/dispatcher/actions"; -import { SDKContextClass } from "../../../src/contexts/SDKContextClass"; -import DMRoomMap from "../../../src/utils/DMRoomMap"; -import { RoomListViewModel } from "../../../src/viewmodels/room-list/RoomListViewModel"; -import { hasCreateRoomRights } from "../../../src/viewmodels/room-list/utils"; -import { DefaultTagID } from "../../../src/stores/room-list-v3/skip-list/tag"; -import SettingsStore from "../../../src/settings/SettingsStore"; -import { tagRoom } from "../../../src/utils/room/tagRoom"; -import { getSectionTagForRoom } from "../../../src/utils/room/getSectionTagForRoom"; -import { - CHATS_TAG, - CUSTOM_SECTION_TAG_PREFIX, - type SectionExpansionState, -} from "../../../src/stores/room-list-v3/section"; -import { MetaSpace } from "../../../src/stores/spaces"; -import { RoomNotificationStateStore } from "../../../src/stores/notifications/RoomNotificationStateStore"; -import { type RoomNotificationState } from "../../../src/stores/notifications/RoomNotificationState"; +} from "test-utils"; -jest.mock("../../../src/utils/room/tagRoom", () => ({ - tagRoom: jest.fn(), +import RoomListStoreV3, { RoomListStoreV3Event } from "../../stores/room-list-v3/RoomListStoreV3"; +import { FilterEnum } from "../../stores/room-list-v3/skip-list/filters"; +import dispatcher from "../../dispatcher/dispatcher"; +import { Action } from "../../dispatcher/actions"; +import { SDKContextClass } from "../../contexts/SDKContextClass"; +import DMRoomMap from "../../utils/DMRoomMap"; +import { RoomListViewModel } from "./RoomListViewModel"; +import { hasCreateRoomRights } from "./utils"; +import { DefaultTagID } from "../../stores/room-list-v3/skip-list/tag"; +import SettingsStore from "../../settings/SettingsStore"; +import { tagRoom } from "../../utils/room/tagRoom"; +import { getSectionTagForRoom } from "../../utils/room/getSectionTagForRoom"; +import { CHATS_TAG, CUSTOM_SECTION_TAG_PREFIX, type SectionExpansionState } from "../../stores/room-list-v3/section"; +import { MetaSpace } from "../../stores/spaces"; +import { RoomNotificationStateStore } from "../../stores/notifications/RoomNotificationStateStore"; +import { type RoomNotificationState } from "../../stores/notifications/RoomNotificationState"; + +vi.mock("../../utils/room/tagRoom", () => ({ + tagRoom: vi.fn(), })); -jest.mock("../../../src/utils/room/getSectionTagForRoom", () => ({ - getSectionTagForRoom: jest.fn().mockReturnValue(null), +vi.mock("../../utils/room/getSectionTagForRoom", () => ({ + getSectionTagForRoom: vi.fn().mockReturnValue(null), })); -jest.mock("../../../src/viewmodels/room-list/utils", () => ({ - hasCreateRoomRights: jest.fn().mockReturnValue(false), - hasAccessToOptionsMenu: jest.fn().mockReturnValue(true), - hasAccessToNotificationMenu: jest.fn().mockReturnValue(true), +vi.mock("./utils", () => ({ + hasCreateRoomRights: vi.fn().mockReturnValue(false), + hasAccessToOptionsMenu: vi.fn().mockReturnValue(true), + hasAccessToNotificationMenu: vi.fn().mockReturnValue(true), })); describe("RoomListViewModel", () => { @@ -68,12 +66,12 @@ describe("RoomListViewModel", () => { sectionExpansionState = {}; const realGetValue = SettingsStore.getValue.bind(SettingsStore); - jest.spyOn(SettingsStore, "getValue").mockImplementation((setting, roomId, excludeDefault) => { + vi.spyOn(SettingsStore, "getValue").mockImplementation((setting, roomId, excludeDefault) => { if (setting === "RoomList.SectionExpansionState") return sectionExpansionState; return realGetValue(setting, roomId, excludeDefault); }); const realSetValue = SettingsStore.setValue.bind(SettingsStore); - jest.spyOn(SettingsStore, "setValue").mockImplementation(async (setting, roomId, level, value) => { + vi.spyOn(SettingsStore, "setValue").mockImplementation(async (setting, roomId, level, value) => { if (setting === "RoomList.SectionExpansionState") { sectionExpansionState = value as SectionExpansionState; return; @@ -88,25 +86,25 @@ describe("RoomListViewModel", () => { // Setup DMRoomMap const dmRoomMap = { - getUserIdForRoomId: jest.fn().mockReturnValue(null), + getUserIdForRoomId: vi.fn().mockReturnValue(null), } as unknown as DMRoomMap; DMRoomMap.setShared(dmRoomMap); - jest.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ + vi.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ spaceId: "home", sections: [{ tag: CHATS_TAG, rooms: [room1, room2, room3] }], }); - jest.spyOn(RoomListStoreV3.instance, "isLoadingRooms", "get").mockReturnValue(false); - jest.spyOn(SDKContextClass.instance.spaceStore, "activeSpaceRoom", "get").mockReturnValue(null); - jest.spyOn(SDKContextClass.instance.roomViewStore, "getRoomId").mockReturnValue(null); + vi.spyOn(RoomListStoreV3.instance, "isLoadingRooms", "get").mockReturnValue(false); + vi.spyOn(SDKContextClass.instance.spaceStore, "activeSpaceRoom", "get").mockReturnValue(null); + vi.spyOn(SDKContextClass.instance.roomViewStore, "getRoomId").mockReturnValue(null); - mocked(hasCreateRoomRights).mockReturnValue(false); + vi.mocked(hasCreateRoomRights).mockReturnValue(false); }); afterEach(() => { viewModel?.dispose(); - jest.restoreAllMocks(); + vi.restoreAllMocks(); }); describe("Initialization", () => { @@ -127,7 +125,7 @@ describe("RoomListViewModel", () => { }); it("should initialize with empty room list", () => { - jest.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ + vi.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ spaceId: "home", sections: [{ tag: CHATS_TAG, rooms: [] }], }); @@ -144,7 +142,7 @@ describe("RoomListViewModel", () => { }); it("should set canCreateRoom based on user rights", () => { - mocked(hasCreateRoomRights).mockReturnValue(true); + vi.mocked(hasCreateRoomRights).mockReturnValue(true); viewModel = new RoomListViewModel({ client: matrixClient, spaceStore: SDKContextClass.instance.spaceStore, @@ -164,7 +162,7 @@ describe("RoomListViewModel", () => { }); const newRoom = mkStubRoom("!room4:server", "Room 4", matrixClient); - jest.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ + vi.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ spaceId: "home", sections: [{ tag: CHATS_TAG, rooms: [room1, room2, room3, newRoom] }], }); @@ -180,7 +178,7 @@ describe("RoomListViewModel", () => { }); it("should update loading state when ListsLoaded event fires", () => { - jest.spyOn(RoomListStoreV3.instance, "isLoadingRooms", "get").mockReturnValue(true); + vi.spyOn(RoomListStoreV3.instance, "isLoadingRooms", "get").mockReturnValue(true); viewModel = new RoomListViewModel({ client: matrixClient, spaceStore: SDKContextClass.instance.spaceStore, @@ -223,12 +221,12 @@ describe("RoomListViewModel", () => { const spaceRoomList = [room1, room2]; - jest.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ + vi.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ spaceId: "!space:server", sections: [{ tag: CHATS_TAG, rooms: spaceRoomList }], }); - jest.spyOn(SDKContextClass.instance.spaceStore, "getLastSelectedRoomIdForSpace").mockReturnValue( + vi.spyOn(SDKContextClass.instance.spaceStore, "getLastSelectedRoomIdForSpace").mockReturnValue( "!room1:server", ); @@ -249,11 +247,11 @@ describe("RoomListViewModel", () => { const vm1 = viewModel.getRoomItemViewModel("!room1:server")!; const vm2 = viewModel.getRoomItemViewModel("!room2:server")!; - const disposeSpy1 = jest.spyOn(vm1, "dispose"); - const disposeSpy2 = jest.spyOn(vm2, "dispose"); + const disposeSpy1 = vi.spyOn(vm1, "dispose"); + const disposeSpy2 = vi.spyOn(vm2, "dispose"); // Change space - jest.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ + vi.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ spaceId: "!space:server", sections: [{ tag: CHATS_TAG, rooms: [room3] }], }); @@ -273,11 +271,11 @@ describe("RoomListViewModel", () => { const newSpaceRoom = mkStubRoom("!spaceroom:server", "Space Room", matrixClient); - jest.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ + vi.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ spaceId: "!space:server", sections: [{ tag: CHATS_TAG, rooms: [newSpaceRoom] }], }); - jest.spyOn(SDKContextClass.instance.spaceStore, "getLastSelectedRoomIdForSpace").mockReturnValue(null); + vi.spyOn(SDKContextClass.instance.spaceStore, "getLastSelectedRoomIdForSpace").mockReturnValue(null); RoomListStoreV3.instance.emit(RoomListStoreV3Event.ListsUpdate); @@ -296,7 +294,7 @@ describe("RoomListViewModel", () => { roomViewStore: SDKContextClass.instance.roomViewStore, }); - jest.spyOn(SDKContextClass.instance.roomViewStore, "getRoomId").mockReturnValue("!room2:server"); + vi.spyOn(SDKContextClass.instance.roomViewStore, "getRoomId").mockReturnValue("!room2:server"); dispatcher.dispatch({ action: Action.ActiveRoomChanged, @@ -316,7 +314,7 @@ describe("RoomListViewModel", () => { roomViewStore: SDKContextClass.instance.roomViewStore, }); - jest.spyOn(SDKContextClass.instance.roomViewStore, "getRoomId").mockReturnValue(null); + vi.spyOn(SDKContextClass.instance.roomViewStore, "getRoomId").mockReturnValue(null); dispatcher.dispatch({ action: Action.ActiveRoomChanged, @@ -339,7 +337,7 @@ describe("RoomListViewModel", () => { }); // Select room at index 1 - jest.spyOn(SDKContextClass.instance.roomViewStore, "getRoomId").mockReturnValue("!room2:server"); + vi.spyOn(SDKContextClass.instance.roomViewStore, "getRoomId").mockReturnValue("!room2:server"); dispatcher.dispatch({ action: Action.ActiveRoomChanged, newRoomId: "!room2:server", @@ -349,7 +347,7 @@ describe("RoomListViewModel", () => { expect(viewModel.getSnapshot().roomListState.activeRoomIndex).toBe(1); // Simulate room list update that would move room2 to front - jest.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ + vi.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ spaceId: "home", sections: [{ tag: CHATS_TAG, rooms: [room2, room1, room3] }], // room2 moved to front }); @@ -369,7 +367,7 @@ describe("RoomListViewModel", () => { }); // Select room at index 1 - jest.spyOn(SDKContextClass.instance.roomViewStore, "getRoomId").mockReturnValue("!room2:server"); + vi.spyOn(SDKContextClass.instance.roomViewStore, "getRoomId").mockReturnValue("!room2:server"); dispatcher.dispatch({ action: Action.ActiveRoomChanged, newRoomId: "!room2:server", @@ -378,7 +376,7 @@ describe("RoomListViewModel", () => { await flushPromises(); // User switches to room3 - jest.spyOn(SDKContextClass.instance.roomViewStore, "getRoomId").mockReturnValue("!room3:server"); + vi.spyOn(SDKContextClass.instance.roomViewStore, "getRoomId").mockReturnValue("!room3:server"); dispatcher.dispatch({ action: Action.ActiveRoomChanged, oldRoomId: "!room2:server", @@ -400,7 +398,7 @@ describe("RoomListViewModel", () => { expect(viewModel.getSnapshot().activeFilterId).toBeUndefined(); - jest.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ + vi.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ spaceId: "home", sections: [{ tag: CHATS_TAG, rooms: [room1] }], filterKeys: [FilterEnum.UnreadFilter], @@ -420,7 +418,7 @@ describe("RoomListViewModel", () => { }); // Turn filter on - jest.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ + vi.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ spaceId: "home", sections: [{ tag: CHATS_TAG, rooms: [room1] }], filterKeys: [FilterEnum.UnreadFilter], @@ -430,7 +428,7 @@ describe("RoomListViewModel", () => { expect(viewModel.getSnapshot().activeFilterId).toBe("unread"); // Turn filter off - jest.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ + vi.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ spaceId: "home", sections: [{ tag: CHATS_TAG, rooms: [room1, room2, room3] }], }); @@ -446,7 +444,7 @@ describe("RoomListViewModel", () => { describe("Favourites and Low Priority filters (RoomList.showSections)", () => { function mockShowSections(showSections: boolean): void { - jest.spyOn(SettingsStore, "getValue").mockImplementation((setting) => { + vi.spyOn(SettingsStore, "getValue").mockImplementation((setting) => { if (setting === "RoomList.showSections") return showSections; if (setting === "RoomList.CustomSectionData") return {}; if (setting === "RoomList.OrderedCustomSections") return []; @@ -484,14 +482,14 @@ describe("RoomListViewModel", () => { it("recomputes the filters and clears the active filter when the setting changes", () => { let showSections = false; let watchCallback: () => void = () => {}; - jest.spyOn(SettingsStore, "getValue").mockImplementation((setting) => { + vi.spyOn(SettingsStore, "getValue").mockImplementation((setting) => { if (setting === "RoomList.showSections") return showSections; if (setting === "RoomList.CustomSectionData") return {}; if (setting === "RoomList.OrderedCustomSections") return []; if (setting === "RoomList.SectionExpansionState") return {}; return undefined as any; }); - jest.spyOn(SettingsStore, "watchSetting").mockImplementation((setting, _room, callback) => { + vi.spyOn(SettingsStore, "watchSetting").mockImplementation((setting, _room, callback) => { if (setting === "RoomList.showSections") watchCallback = callback as () => void; return "watcher-id"; }); @@ -504,7 +502,7 @@ describe("RoomListViewModel", () => { expect(viewModel.getSnapshot().filterIds).toContain("favourite"); // Activate the Favourites filter - jest.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ + vi.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ spaceId: "home", sections: [{ tag: CHATS_TAG, rooms: [room1] }], filterKeys: [FilterEnum.FavouriteFilter], @@ -514,7 +512,7 @@ describe("RoomListViewModel", () => { // Enabling sections hides the Favourites filter and resets the active filter showSections = true; - jest.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ + vi.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ spaceId: "home", sections: [{ tag: CHATS_TAG, rooms: [room1, room2, room3] }], }); @@ -573,7 +571,7 @@ describe("RoomListViewModel", () => { }); // Normal list update removes room2 from the list - jest.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ + vi.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ spaceId: "home", sections: [{ tag: CHATS_TAG, rooms: [room1, room3] }], }); @@ -593,11 +591,11 @@ describe("RoomListViewModel", () => { const spaceRoom = mkStubRoom("!newroom:server", "New Room", matrixClient); // Space change: new space only has spaceRoom - jest.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ + vi.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ spaceId: "!space:server", sections: [{ tag: CHATS_TAG, rooms: [spaceRoom] }], }); - jest.spyOn(SDKContextClass.instance.spaceStore, "getLastSelectedRoomIdForSpace").mockReturnValue(null); + vi.spyOn(SDKContextClass.instance.spaceStore, "getLastSelectedRoomIdForSpace").mockReturnValue(null); RoomListStoreV3.instance.emit(RoomListStoreV3Event.ListsUpdate); @@ -629,8 +627,8 @@ describe("RoomListViewModel", () => { const vm2 = viewModel.getRoomItemViewModel("!room2:server")!; const vm3 = viewModel.getRoomItemViewModel("!room3:server")!; - const disposeSpy1 = jest.spyOn(vm1, "dispose"); - const disposeSpy3 = jest.spyOn(vm3, "dispose"); + const disposeSpy1 = vi.spyOn(vm1, "dispose"); + const disposeSpy3 = vi.spyOn(vm3, "dispose"); // Update to show only middle room (index 1) viewModel.updateVisibleRooms(1, 2); @@ -652,7 +650,7 @@ describe("RoomListViewModel", () => { roomViewStore: SDKContextClass.instance.roomViewStore, }); - const dispatchSpy = jest.spyOn(dispatcher, "fire"); + const dispatchSpy = vi.spyOn(dispatcher, "fire").mockImplementation(() => {}); viewModel.createChatRoom(); @@ -666,7 +664,7 @@ describe("RoomListViewModel", () => { roomViewStore: SDKContextClass.instance.roomViewStore, }); - const dispatchSpy = jest.spyOn(dispatcher, "dispatch"); + const dispatchSpy = vi.spyOn(dispatcher, "dispatch").mockImplementation(() => {}); viewModel.createRoom(); @@ -677,7 +675,7 @@ describe("RoomListViewModel", () => { it("should dispatch CreateRoom action with parent space", () => { const spaceRoom = mkStubRoom("!space:server", "Space", matrixClient); - jest.spyOn(SDKContextClass.instance.spaceStore, "activeSpaceRoom", "get").mockReturnValue(spaceRoom); + vi.spyOn(SDKContextClass.instance.spaceStore, "activeSpaceRoom", "get").mockReturnValue(spaceRoom); viewModel = new RoomListViewModel({ client: matrixClient, @@ -685,7 +683,7 @@ describe("RoomListViewModel", () => { roomViewStore: SDKContextClass.instance.roomViewStore, }); - const dispatchSpy = jest.spyOn(dispatcher, "dispatch"); + const dispatchSpy = vi.spyOn(dispatcher, "dispatch").mockImplementation(() => {}); viewModel.createRoom(); @@ -709,15 +707,16 @@ describe("RoomListViewModel", () => { roomViewStore: SDKContextClass.instance.roomViewStore, }); - jest.spyOn(SDKContextClass.instance.roomViewStore, "getRoomId").mockReturnValue("!room1:server"); + vi.spyOn(SDKContextClass.instance.roomViewStore, "getRoomId").mockReturnValue("!room1:server"); - const dispatchSpy = jest.spyOn(dispatcher, "dispatch"); + const dispatchSpy = vi.spyOn(dispatcher, "dispatch"); dispatcher.dispatch({ action: Action.ViewRoomDelta, delta: 1, unread: false, }); + dispatchSpy.mockImplementation(() => {}); await flushPromises(); @@ -736,15 +735,16 @@ describe("RoomListViewModel", () => { roomViewStore: SDKContextClass.instance.roomViewStore, }); - jest.spyOn(SDKContextClass.instance.roomViewStore, "getRoomId").mockReturnValue("!room2:server"); + vi.spyOn(SDKContextClass.instance.roomViewStore, "getRoomId").mockReturnValue("!room2:server"); - const dispatchSpy = jest.spyOn(dispatcher, "dispatch"); + const dispatchSpy = vi.spyOn(dispatcher, "dispatch"); dispatcher.dispatch({ action: Action.ViewRoomDelta, delta: -1, unread: false, }); + dispatchSpy.mockImplementation(() => {}); await flushPromises(); @@ -763,15 +763,16 @@ describe("RoomListViewModel", () => { roomViewStore: SDKContextClass.instance.roomViewStore, }); - jest.spyOn(SDKContextClass.instance.roomViewStore, "getRoomId").mockReturnValue("!room1:server"); + vi.spyOn(SDKContextClass.instance.roomViewStore, "getRoomId").mockReturnValue("!room1:server"); - const dispatchSpy = jest.spyOn(dispatcher, "dispatch"); + const dispatchSpy = vi.spyOn(dispatcher, "dispatch"); dispatcher.dispatch({ action: Action.ViewRoomDelta, delta: -1, unread: false, }); + dispatchSpy.mockImplementation(() => {}); await flushPromises(); @@ -790,9 +791,9 @@ describe("RoomListViewModel", () => { roomViewStore: SDKContextClass.instance.roomViewStore, }); - jest.spyOn(SDKContextClass.instance.roomViewStore, "getRoomId").mockReturnValue("!unknown:server"); + vi.spyOn(SDKContextClass.instance.roomViewStore, "getRoomId").mockReturnValue("!unknown:server"); - const dispatchSpy = jest.spyOn(dispatcher, "dispatch"); + const dispatchSpy = vi.spyOn(dispatcher, "dispatch"); dispatchSpy.mockClear(); dispatcher.dispatch({ @@ -800,6 +801,7 @@ describe("RoomListViewModel", () => { delta: 1, unread: false, }); + dispatchSpy.mockImplementation(() => {}); await flushPromises(); @@ -818,9 +820,9 @@ describe("RoomListViewModel", () => { roomViewStore: SDKContextClass.instance.roomViewStore, }); - jest.spyOn(SDKContextClass.instance.roomViewStore, "getRoomId").mockReturnValue(null); + vi.spyOn(SDKContextClass.instance.roomViewStore, "getRoomId").mockReturnValue(null); - const dispatchSpy = jest.spyOn(dispatcher, "dispatch"); + const dispatchSpy = vi.spyOn(dispatcher, "dispatch"); dispatchSpy.mockClear(); dispatcher.dispatch({ @@ -828,6 +830,7 @@ describe("RoomListViewModel", () => { delta: 1, unread: false, }); + dispatchSpy.mockImplementation(() => {}); await flushPromises(); @@ -841,11 +844,11 @@ describe("RoomListViewModel", () => { describe("Cleanup", () => { beforeEach(() => { - jest.useFakeTimers(); + vi.useFakeTimers(); }); afterEach(() => { - jest.useRealTimers(); + vi.useRealTimers(); }); it("should dispose all room item view models on dispose", () => { @@ -858,8 +861,8 @@ describe("RoomListViewModel", () => { const vm1 = viewModel.getRoomItemViewModel("!room1:server")!; const vm2 = viewModel.getRoomItemViewModel("!room2:server")!; - const disposeSpy1 = jest.spyOn(vm1, "dispose"); - const disposeSpy2 = jest.spyOn(vm2, "dispose"); + const disposeSpy1 = vi.spyOn(vm1, "dispose"); + const disposeSpy2 = vi.spyOn(vm2, "dispose"); viewModel.dispose(); @@ -912,7 +915,7 @@ describe("RoomListViewModel", () => { RoomListStoreV3.instance.emit(RoomListStoreV3Event.SectionCreated); expect(viewModel.getSnapshot().toast).toBe("section_created"); - jest.advanceTimersByTime(15 * 1000); + vi.advanceTimersByTime(15 * 1000); expect(viewModel.getSnapshot().toast).toBeUndefined(); }); @@ -924,22 +927,22 @@ describe("RoomListViewModel", () => { }); RoomListStoreV3.instance.emit(RoomListStoreV3Event.SectionCreated); - jest.advanceTimersByTime(10 * 1000); + vi.advanceTimersByTime(10 * 1000); // Second section created — resets the timer RoomListStoreV3.instance.emit(RoomListStoreV3Event.SectionCreated); - jest.advanceTimersByTime(10 * 1000); + vi.advanceTimersByTime(10 * 1000); // Toast should still be visible (only 10s since last emit) expect(viewModel.getSnapshot().toast).toBe("section_created"); - jest.advanceTimersByTime(5 * 1000); + vi.advanceTimersByTime(5 * 1000); expect(viewModel.getSnapshot().toast).toBeUndefined(); }); /** Make only `room3` report an unread count, so it is the unread room below the fold. */ const mockRoom3Unread = (): void => { - jest.spyOn(RoomNotificationStateStore.instance, "getRoomState").mockImplementation( + vi.spyOn(RoomNotificationStateStore.instance, "getRoomState").mockImplementation( (room) => ({ hasUnreadCount: room === room3 }) as unknown as RoomNotificationState, ); }; @@ -973,7 +976,7 @@ describe("RoomListViewModel", () => { expect(viewModel.getSnapshot().toast).toBe("chat_moved"); // …and once it auto-dismisses, the unread-activity toast returns. - jest.advanceTimersByTime(15 * 1000); + vi.advanceTimersByTime(15 * 1000); expect(viewModel.getSnapshot().toast).toBe("unread_activity"); }); }); @@ -992,7 +995,7 @@ describe("RoomListViewModel", () => { regularRoom1 = mkStubRoom("!reg1:server", "Reg 1", matrixClient); regularRoom2 = mkStubRoom("!reg2:server", "Reg 2", matrixClient); - jest.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ + vi.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ spaceId: "home", sections: [ { tag: DefaultTagID.Favourite, rooms: [favRoom1, favRoom2] }, @@ -1030,7 +1033,7 @@ describe("RoomListViewModel", () => { }); it("should be a flat list when only chats section has rooms", () => { - jest.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ + vi.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ spaceId: "home", sections: [ { tag: DefaultTagID.Favourite, rooms: [] }, @@ -1051,7 +1054,7 @@ describe("RoomListViewModel", () => { }); it("should be a flat list when the room list is empty", () => { - jest.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ + vi.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ spaceId: "home", sections: [ { tag: DefaultTagID.Favourite, rooms: [] }, @@ -1086,7 +1089,7 @@ describe("RoomListViewModel", () => { }); it("should omit empty sections from snapshot", () => { - jest.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ + vi.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ spaceId: "home", sections: [ { tag: DefaultTagID.Favourite, rooms: [] }, @@ -1167,18 +1170,21 @@ describe("RoomListViewModel", () => { expect(favHeader.isExpanded).toBe(false); // Select regularRoom1, which is the first room in the chats section - jest.spyOn(SDKContextClass.instance.roomViewStore, "getRoomId").mockReturnValue("!reg1:server"); + vi.spyOn(SDKContextClass.instance.roomViewStore, "getRoomId").mockReturnValue("!reg1:server"); dispatcher.dispatch({ action: Action.ActiveRoomChanged, newRoomId: "!reg1:server", }); - await waitFor(() => { - const snapshot = viewModel.getSnapshot(); - // The favourite section is collapsed so its 2 rooms are not visible. - // regularRoom1 should be at index 0 in the visible list, not index 2. - expect(snapshot.roomListState.activeRoomIndex).toBe(0); - }); + // `waitFor` polls using real timers, which never fire while fake timers are + // installed (and vitest fake timers aren't auto-detected by testing-library the + // way jest's are). Use the fake-timer-aware flush helper instead. + await flushPromisesWithFakeTimers(); + + const snapshot = viewModel.getSnapshot(); + // The favourite section is collapsed so its 2 rooms are not visible. + // regularRoom1 should be at index 0 in the visible list, not index 2. + expect(snapshot.roomListState.activeRoomIndex).toBe(0); }); it("should restore room IDs when a section is re-expanded", () => { @@ -1209,7 +1215,7 @@ describe("RoomListViewModel", () => { const newFav = mkStubRoom("!fav3:server", "Fav 3", matrixClient); - jest.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ + vi.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ spaceId: "home", sections: [ { tag: DefaultTagID.Favourite, rooms: [favRoom1, favRoom2, newFav] }, @@ -1257,7 +1263,7 @@ describe("RoomListViewModel", () => { // Switch to a different space with its own rooms const spaceFav = mkStubRoom("!spacefav:server", "Space Fav", matrixClient); const spaceReg = mkStubRoom("!spacereg:server", "Space Reg", matrixClient); - jest.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ + vi.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ spaceId: "!space:server", sections: [ { tag: DefaultTagID.Favourite, rooms: [spaceFav] }, @@ -1265,7 +1271,7 @@ describe("RoomListViewModel", () => { { tag: DefaultTagID.LowPriority, rooms: [] }, ], }); - jest.spyOn(SDKContextClass.instance.spaceStore, "getLastSelectedRoomIdForSpace").mockReturnValue(null); + vi.spyOn(SDKContextClass.instance.spaceStore, "getLastSelectedRoomIdForSpace").mockReturnValue(null); RoomListStoreV3.instance.emit(RoomListStoreV3Event.ListsUpdate); @@ -1280,7 +1286,7 @@ describe("RoomListViewModel", () => { expect(chatsSection!.roomIds).toEqual(["!spacereg:server"]); // Switch back to home space - jest.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ + vi.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ spaceId: "home", sections: [ { tag: DefaultTagID.Favourite, rooms: [favRoom1, favRoom2] }, @@ -1310,7 +1316,7 @@ describe("RoomListViewModel", () => { }); // Only favRoom1 is unread - jest.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ + vi.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ spaceId: "home", sections: [ { tag: DefaultTagID.Favourite, rooms: [favRoom1] }, @@ -1334,13 +1340,13 @@ describe("RoomListViewModel", () => { const customTag = `${CUSTOM_SECTION_TAG_PREFIX}test-uuid` as const; beforeEach(() => { - jest.spyOn(SDKContextClass.instance.spaceStore, "enabledMetaSpaces", "get").mockReturnValue([ + vi.spyOn(SDKContextClass.instance.spaceStore, "enabledMetaSpaces", "get").mockReturnValue([ MetaSpace.Home, ]); - jest.spyOn(SDKContextClass.instance.spaceStore, "spacePanelSpaces", "get").mockReturnValue([ + vi.spyOn(SDKContextClass.instance.spaceStore, "spacePanelSpaces", "get").mockReturnValue([ mkStubRoom("!space:server", "My Space", matrixClient), ]); - jest.spyOn(SettingsStore, "getValue").mockImplementation((setting: string) => { + vi.spyOn(SettingsStore, "getValue").mockImplementation((setting: string) => { if (setting === "RoomList.CustomSectionData") return { [customTag]: { tag: customTag, name: "My Section", spaceId: "!space:server" }, @@ -1350,12 +1356,12 @@ describe("RoomListViewModel", () => { }); it("shows an empty custom section when viewing its originating space", () => { - jest.spyOn(SettingsStore, "getValue").mockImplementation((setting: string) => { + vi.spyOn(SettingsStore, "getValue").mockImplementation((setting: string) => { if (setting === "RoomList.CustomSectionData") return { [customTag]: { tag: customTag, name: "My Section", spaceId: MetaSpace.Home } }; return false; }); - jest.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ + vi.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ spaceId: MetaSpace.Home, sections: [ { tag: customTag, rooms: [] }, @@ -1373,7 +1379,7 @@ describe("RoomListViewModel", () => { }); it("hides an empty custom section in a different space", () => { - jest.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ + vi.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ spaceId: MetaSpace.Home, sections: [ { tag: customTag, rooms: [] }, @@ -1391,7 +1397,7 @@ describe("RoomListViewModel", () => { }); it("shows a non-empty custom section regardless of originating space", () => { - jest.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ + vi.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ spaceId: MetaSpace.Home, sections: [ { tag: customTag, rooms: [regularRoom1] }, @@ -1464,7 +1470,7 @@ describe("RoomListViewModel", () => { roomViewStore: SDKContextClass.instance.roomViewStore, }); - const dispatchSpy = jest.spyOn(dispatcher, "dispatch"); + const dispatchSpy = vi.spyOn(dispatcher, "dispatch").mockImplementation(() => {}); RoomListStoreV3.instance.emit(RoomListStoreV3Event.ListsUpdate); expect(dispatchSpy).toHaveBeenCalledWith({ @@ -1485,7 +1491,7 @@ describe("RoomListViewModel", () => { viewModel.getSectionHeaderViewModel(CHATS_TAG).isExpanded = false; viewModel.getSectionHeaderViewModel(DefaultTagID.LowPriority).isExpanded = false; - const dispatchSpy = jest.spyOn(dispatcher, "dispatch"); + const dispatchSpy = vi.spyOn(dispatcher, "dispatch").mockImplementation(() => {}); RoomListStoreV3.instance.emit(RoomListStoreV3Event.ListsUpdate); expect(dispatchSpy).toHaveBeenCalledWith({ @@ -1498,7 +1504,7 @@ describe("RoomListViewModel", () => { { label: "flat list", chatsRooms: true }, { label: "empty room list", chatsRooms: false }, ])("should dispatch collapseSection=undefined when it is a $label", ({ chatsRooms }) => { - jest.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ + vi.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ spaceId: "home", sections: [ { tag: DefaultTagID.Favourite, rooms: [] }, @@ -1512,7 +1518,7 @@ describe("RoomListViewModel", () => { roomViewStore: SDKContextClass.instance.roomViewStore, }); - const dispatchSpy = jest.spyOn(dispatcher, "dispatch"); + const dispatchSpy = vi.spyOn(dispatcher, "dispatch").mockImplementation(() => {}); RoomListStoreV3.instance.emit(RoomListStoreV3Event.ListsUpdate); expect(dispatchSpy).toHaveBeenCalledWith({ @@ -1531,7 +1537,7 @@ describe("RoomListViewModel", () => { }); // Select favRoom1 (index 0 globally, index 0 in favourites section) - jest.spyOn(SDKContextClass.instance.roomViewStore, "getRoomId").mockReturnValue("!fav1:server"); + vi.spyOn(SDKContextClass.instance.roomViewStore, "getRoomId").mockReturnValue("!fav1:server"); dispatcher.dispatch({ action: Action.ActiveRoomChanged, newRoomId: "!fav1:server", @@ -1541,7 +1547,7 @@ describe("RoomListViewModel", () => { expect(viewModel.getSnapshot().roomListState.activeRoomIndex).toBe(0); // Room list update moves favRoom1 to second position within favourites - jest.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ + vi.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ spaceId: "home", sections: [ { tag: DefaultTagID.Favourite, rooms: [favRoom2, favRoom1] }, @@ -1572,7 +1578,7 @@ describe("RoomListViewModel", () => { }); it("should delegate changeSectionOrder to RoomListStoreV3.reorderSection", async () => { - const reorderSpy = jest + const reorderSpy = vi .spyOn(RoomListStoreV3.instance, "reorderSection") .mockResolvedValue(undefined); @@ -1582,7 +1588,7 @@ describe("RoomListViewModel", () => { }); it("should scroll the moved section back into view after reordering", async () => { - jest.spyOn(RoomListStoreV3.instance, "reorderSection").mockResolvedValue(undefined); + vi.spyOn(RoomListStoreV3.instance, "reorderSection").mockResolvedValue(undefined); await viewModel.changeSectionOrder(DefaultTagID.Favourite, CHATS_TAG); expect(viewModel.getSnapshot().roomListState.scrollToSectionTag).toBe(DefaultTagID.Favourite); @@ -1673,12 +1679,12 @@ describe("RoomListViewModel", () => { spaceStore: SDKContextClass.instance.spaceStore, roomViewStore: SDKContextClass.instance.roomViewStore, }); - mocked(tagRoom).mockClear(); + vi.mocked(tagRoom).mockClear(); }); it("should call tagRoom with the room and target tag", () => { - jest.spyOn(matrixClient, "getRoom").mockReturnValue(room1); - mocked(getSectionTagForRoom).mockReturnValue(null); + vi.spyOn(matrixClient, "getRoom").mockReturnValue(room1); + vi.mocked(getSectionTagForRoom).mockReturnValue(null); viewModel.changeRoomSection(room1.roomId, DefaultTagID.Favourite); @@ -1686,7 +1692,7 @@ describe("RoomListViewModel", () => { }); it("should do nothing when the room is not found", () => { - jest.spyOn(matrixClient, "getRoom").mockReturnValue(null); + vi.spyOn(matrixClient, "getRoom").mockReturnValue(null); viewModel.changeRoomSection("!unknown:server", DefaultTagID.Favourite); @@ -1694,8 +1700,8 @@ describe("RoomListViewModel", () => { }); it("should do nothing when the room is already in the target section", () => { - jest.spyOn(matrixClient, "getRoom").mockReturnValue(room1); - mocked(getSectionTagForRoom).mockReturnValue(DefaultTagID.Favourite); + vi.spyOn(matrixClient, "getRoom").mockReturnValue(room1); + vi.mocked(getSectionTagForRoom).mockReturnValue(DefaultTagID.Favourite); viewModel.changeRoomSection(room1.roomId, DefaultTagID.Favourite); @@ -1716,7 +1722,7 @@ describe("RoomListViewModel", () => { roomViewStore: sdkContext.roomViewStore, spaceStore: sdkContext.spaceStore, }); - const scrollSpy = jest.fn(); + const scrollSpy = vi.fn(); viewModel.setScrollToIndex(scrollSpy); dispatcher.dispatch({ @@ -1734,7 +1740,7 @@ describe("RoomListViewModel", () => { const favRoom1 = mkStubRoom("!fav1:server", "Fav 1", matrixClient); const favRoom2 = mkStubRoom("!fav2:server", "Fav 2", matrixClient); const regularRoom1 = mkStubRoom("!reg1:server", "Reg 1", matrixClient); - jest.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ + vi.spyOn(RoomListStoreV3.instance, "getSortedRoomsInActiveSpace").mockReturnValue({ spaceId: "home", sections: [ { tag: DefaultTagID.Favourite, rooms: [favRoom1, favRoom2] }, @@ -1746,7 +1752,7 @@ describe("RoomListViewModel", () => { roomViewStore: sdkContext.roomViewStore, spaceStore: sdkContext.spaceStore, }); - const scrollSpy = jest.fn(); + const scrollSpy = vi.fn(); viewModel.setScrollToIndex(scrollSpy); dispatcher.dispatch({ @@ -1766,7 +1772,7 @@ describe("RoomListViewModel", () => { roomViewStore: sdkContext.roomViewStore, spaceStore: sdkContext.spaceStore, }); - const scrollSpy = jest.fn(); + const scrollSpy = vi.fn(); viewModel.setScrollToIndex(scrollSpy); dispatcher.dispatch({ diff --git a/apps/web/test/viewmodels/room-list/utils-test.ts b/apps/web/src/viewmodels/room-list/utils.test.ts similarity index 64% rename from apps/web/test/viewmodels/room-list/utils-test.ts rename to apps/web/src/viewmodels/room-list/utils.test.ts index e7e303aed5..f0cb9572a6 100644 --- a/apps/web/test/viewmodels/room-list/utils-test.ts +++ b/apps/web/src/viewmodels/room-list/utils.test.ts @@ -5,22 +5,24 @@ * 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 } from "vitest"; +import { createTestClient, mkStubRoom } from "test-utils"; import type { MatrixClient, Room, RoomState } from "matrix-js-sdk/src/matrix"; -import { createTestClient, mkStubRoom } from "../../test-utils"; -import { shouldShowComponent } from "../../../src/customisations/helpers/UIComponents"; -import defaultDispatcher from "../../../src/dispatcher/dispatcher"; -import { Action } from "../../../src/dispatcher/actions"; -import { showCreateNewRoom } from "../../../src/utils/space"; -import { hasCreateRoomRights, createRoom, hasAccessToNotificationMenu } from "../../../src/viewmodels/room-list/utils"; +import { shouldShowComponent } from "../../customisations/helpers/UIComponents"; +import defaultDispatcher from "../../dispatcher/dispatcher"; +import { Action } from "../../dispatcher/actions"; +import { showCreateNewRoom } from "../../utils/space"; +import { hasCreateRoomRights, createRoom, hasAccessToNotificationMenu } from "./utils"; -jest.mock("../../../src/customisations/helpers/UIComponents", () => ({ - shouldShowComponent: jest.fn(), +vi.mock("../../customisations/helpers/UIComponents", () => ({ + shouldShowComponent: vi.fn(), })); -jest.mock("../../../src/utils/space", () => ({ - showCreateNewRoom: jest.fn(), +vi.mock("../../utils/space", () => ({ + showCreateNewRoom: vi.fn(), })); describe("utils", () => { @@ -34,7 +36,7 @@ describe("utils", () => { describe("createRoom", () => { it("should fire Action.CreateRoom when createRoom is called without a space", async () => { - const spy = jest.spyOn(defaultDispatcher, "fire"); + const spy = vi.spyOn(defaultDispatcher, "fire"); await createRoom(); expect(spy).toHaveBeenCalledWith(Action.CreateRoom); @@ -48,19 +50,19 @@ describe("utils", () => { describe("hasCreateRoomRights", () => { it("should return false when UIComponent.CreateRooms is disabled", () => { - mocked(shouldShowComponent).mockReturnValue(false); + vi.mocked(shouldShowComponent).mockReturnValue(false); expect(hasCreateRoomRights(matrixClient, space)).toBe(false); }); it("should return true when UIComponent.CreateRooms is enabled and no space", () => { - mocked(shouldShowComponent).mockReturnValue(true); + vi.mocked(shouldShowComponent).mockReturnValue(true); expect(hasCreateRoomRights(matrixClient)).toBe(true); }); it("should return false in space when UIComponent.CreateRooms is enabled and the user doesn't have the rights", () => { - mocked(shouldShowComponent).mockReturnValue(true); - jest.spyOn(space.getLiveTimeline(), "getState").mockReturnValue({ - maySendStateEvent: jest.fn().mockReturnValue(true), + vi.mocked(shouldShowComponent).mockReturnValue(true); + vi.spyOn(space.getLiveTimeline(), "getState").mockReturnValue({ + maySendStateEvent: vi.fn().mockReturnValue(true), } as unknown as RoomState); expect(hasCreateRoomRights(matrixClient)).toBe(true); @@ -68,7 +70,7 @@ describe("utils", () => { }); it("hasAccessToNotificationMenu", () => { - mocked(shouldShowComponent).mockReturnValue(true); + vi.mocked(shouldShowComponent).mockReturnValue(true); const room = mkStubRoom("roomId", "roomName", matrixClient); const isGuest = false; const isArchived = false; diff --git a/apps/web/test/viewmodels/room/EventTileActionBarViewModel-test.ts b/apps/web/src/viewmodels/room/EventTileActionBarViewModel.test.ts similarity index 77% rename from apps/web/test/viewmodels/room/EventTileActionBarViewModel-test.ts rename to apps/web/src/viewmodels/room/EventTileActionBarViewModel.test.ts index 10a61b8e58..576d884592 100644 --- a/apps/web/test/viewmodels/room/EventTileActionBarViewModel-test.ts +++ b/apps/web/src/viewmodels/room/EventTileActionBarViewModel.test.ts @@ -5,9 +5,10 @@ * Please see LICENSE files in the repository root for full details. */ +// @vitest-environment happy-dom + import EventEmitter from "node:events"; import { waitFor } from "@testing-library/dom"; -import { mocked } from "jest-mock"; import { EventStatus, EventTimeline, @@ -20,60 +21,58 @@ import { RoomStateEvent, } from "matrix-js-sdk/src/matrix"; import { ActionBarAction } from "@element-hq/web-shared-components"; +import { vi, describe, it, expect, beforeEach, afterEach, type Mock } from "vitest"; +import { createTestClient } from "test-utils"; -import { - EventTileActionBarViewModel, - type EventTileActionBarViewModelProps, -} from "../../../src/viewmodels/room/EventTileActionBarViewModel"; -import { TimelineRenderingType } from "../../../src/contexts/RoomContext"; -import { MatrixClientPeg } from "../../../src/MatrixClientPeg"; -import defaultDispatcher from "../../../src/dispatcher/dispatcher"; -import { Action } from "../../../src/dispatcher/actions"; -import Resend from "../../../src/Resend"; -import PinningUtils from "../../../src/utils/PinningUtils"; -import PosthogTrackers from "../../../src/PosthogTrackers"; -import Modal from "../../../src/Modal"; -import ErrorDialog from "../../../src/components/views/dialogs/ErrorDialog"; -import SettingsStore from "../../../src/settings/SettingsStore"; -import { ModuleApi } from "../../../src/modules/Api"; -import { canCancel, canEditContent, editEvent, isContentActionable } from "../../../src/utils/EventUtils"; -import { shouldDisplayReply } from "../../../src/utils/Reply"; -import { MediaEventHelper } from "../../../src/utils/MediaEventHelper"; -import { getMediaVisibility, setMediaVisibility } from "../../../src/utils/media/mediaVisibility"; -import { createTestClient } from "../../test-utils"; +import { EventTileActionBarViewModel, type EventTileActionBarViewModelProps } from "./EventTileActionBarViewModel"; +import { TimelineRenderingType } from "../../contexts/RoomContext"; +import { MatrixClientPeg } from "../../MatrixClientPeg"; +import defaultDispatcher from "../../dispatcher/dispatcher"; +import { Action } from "../../dispatcher/actions"; +import Resend from "../../Resend"; +import PinningUtils from "../../utils/PinningUtils"; +import PosthogTrackers from "../../PosthogTrackers"; +import Modal from "../../Modal"; +import ErrorDialog from "../../components/views/dialogs/ErrorDialog"; +import SettingsStore from "../../settings/SettingsStore"; +import { ModuleApi } from "../../modules/Api"; +import { canCancel, canEditContent, editEvent, isContentActionable } from "../../utils/EventUtils"; +import { shouldDisplayReply } from "../../utils/Reply"; +import { MediaEventHelper } from "../../utils/MediaEventHelper"; +import { getMediaVisibility, setMediaVisibility } from "../../utils/media/mediaVisibility"; -jest.mock("../../../src/dispatcher/dispatcher", () => ({ +vi.mock("../../dispatcher/dispatcher", () => ({ __esModule: true, default: { - dispatch: jest.fn(), - register: jest.fn().mockReturnValue("dispatcher-ref"), - unregister: jest.fn(), + dispatch: vi.fn(), + register: vi.fn().mockReturnValue("dispatcher-ref"), + unregister: vi.fn(), }, })); -jest.mock("../../../src/Resend", () => ({ +vi.mock("../../Resend", () => ({ __esModule: true, default: { - resend: jest.fn(), - removeFromQueue: jest.fn(), + resend: vi.fn(), + removeFromQueue: vi.fn(), }, })); -jest.mock("../../../src/PosthogTrackers", () => ({ +vi.mock("../../PosthogTrackers", () => ({ __esModule: true, default: { - trackPinUnpinMessage: jest.fn(), + trackPinUnpinMessage: vi.fn(), }, })); -jest.mock("../../../src/Modal", () => ({ +vi.mock("../../Modal", () => ({ __esModule: true, default: { - createDialog: jest.fn(), + createDialog: vi.fn(), }, })); -jest.mock("../../../src/languageHandler", () => ({ +vi.mock("../../languageHandler", () => ({ _t: (key: string) => { switch (key) { case "timeline|download_failed": @@ -89,37 +88,39 @@ jest.mock("../../../src/languageHandler", () => ({ _td: (key: string) => key, })); -jest.mock("../../../src/utils/EventUtils", () => ({ - canCancel: jest.fn(), - canEditContent: jest.fn(), - editEvent: jest.fn(), - isContentActionable: jest.fn(), +vi.mock("../../utils/EventUtils", () => ({ + canCancel: vi.fn(), + canEditContent: vi.fn(), + editEvent: vi.fn(), + isContentActionable: vi.fn(), })); -jest.mock("../../../src/utils/PinningUtils", () => ({ +vi.mock("../../utils/PinningUtils", () => ({ __esModule: true, default: { - canPin: jest.fn(), - canUnpin: jest.fn(), - isPinned: jest.fn(), - pinOrUnpinEvent: jest.fn(), + canPin: vi.fn(), + canUnpin: vi.fn(), + isPinned: vi.fn(), + pinOrUnpinEvent: vi.fn(), }, })); -jest.mock("../../../src/utils/Reply", () => ({ - shouldDisplayReply: jest.fn(), +vi.mock("../../utils/Reply", () => ({ + shouldDisplayReply: vi.fn(), })); -jest.mock("../../../src/utils/media/mediaVisibility", () => ({ - getMediaVisibility: jest.fn(), - setMediaVisibility: jest.fn(), +vi.mock("../../utils/media/mediaVisibility", () => ({ + getMediaVisibility: vi.fn(), + setMediaVisibility: vi.fn(), })); -const mockDownload = jest.fn(); -jest.mock("../../../src/utils/FileDownloader", () => ({ - FileDownloader: jest.fn().mockImplementation(() => ({ - download: mockDownload, - })), +const mockDownload = vi.fn(); +vi.mock("../../utils/FileDownloader", () => ({ + FileDownloader: vi.fn().mockImplementation(function () { + return { + download: mockDownload, + }; + }), })); describe("EventTileActionBarViewModel", () => { @@ -136,9 +137,9 @@ describe("EventTileActionBarViewModel", () => { let client: ReturnType; let roomState: EventEmitter; let room: { - getLiveTimeline: jest.Mock; + getLiveTimeline: Mock; }; - let getHintsForMessageSpy: jest.SpyInstance; + let getHintsForMessageSpy: Mock; const createMessageEvent = (overrides: Partial[0]> = {}): MatrixEvent => new MatrixEvent({ @@ -176,45 +177,43 @@ describe("EventTileActionBarViewModel", () => { }; beforeEach(() => { - jest.clearAllMocks(); + vi.clearAllMocks(); client = createTestClient(); roomState = new EventEmitter(); room = { - getLiveTimeline: jest.fn().mockReturnValue({ - getState: jest - .fn() - .mockImplementation((dir) => (dir === EventTimeline.FORWARDS ? roomState : undefined)), + getLiveTimeline: vi.fn().mockReturnValue({ + getState: vi.fn().mockImplementation((dir) => (dir === EventTimeline.FORWARDS ? roomState : undefined)), }), }; - jest.spyOn(MatrixClientPeg, "safeGet").mockReturnValue(client); - jest.spyOn(client, "getRoom").mockReturnValue(room as never); - jest.spyOn(client, "decryptEventIfNeeded"); + vi.spyOn(MatrixClientPeg, "safeGet").mockReturnValue(client); + vi.spyOn(client, "getRoom").mockReturnValue(room as never); + vi.spyOn(client, "decryptEventIfNeeded"); - jest.spyOn(SettingsStore, "watchSetting").mockImplementation((name, scope) => `${name}:${scope ?? "global"}`); - jest.spyOn(SettingsStore, "unwatchSetting").mockImplementation(() => {}); + vi.spyOn(SettingsStore, "watchSetting").mockImplementation((name, scope) => `${name}:${scope ?? "global"}`); + vi.spyOn(SettingsStore, "unwatchSetting").mockImplementation(() => {}); - mocked(canCancel).mockImplementation((status) => status === EventStatus.QUEUED); - mocked(canEditContent).mockReturnValue(true); - mocked(isContentActionable).mockReturnValue(true); - mocked(shouldDisplayReply).mockReturnValue(true); - mocked(getMediaVisibility).mockReturnValue(true); - mocked(setMediaVisibility).mockResolvedValue(undefined); - mocked(PinningUtils.canPin).mockReturnValue(false); - mocked(PinningUtils.canUnpin).mockReturnValue(false); - mocked(PinningUtils.isPinned).mockReturnValue(false); - mocked(PinningUtils.pinOrUnpinEvent).mockResolvedValue(undefined); - jest.spyOn(MediaEventHelper, "isEligible").mockReturnValue(false); - jest.spyOn(MediaEventHelper, "canHide").mockReturnValue(false); + vi.mocked(canCancel).mockImplementation((status) => status === EventStatus.QUEUED); + vi.mocked(canEditContent).mockReturnValue(true); + vi.mocked(isContentActionable).mockReturnValue(true); + vi.mocked(shouldDisplayReply).mockReturnValue(true); + vi.mocked(getMediaVisibility).mockReturnValue(true); + vi.mocked(setMediaVisibility).mockResolvedValue(undefined); + vi.mocked(PinningUtils.canPin).mockReturnValue(false); + vi.mocked(PinningUtils.canUnpin).mockReturnValue(false); + vi.mocked(PinningUtils.isPinned).mockReturnValue(false); + vi.mocked(PinningUtils.pinOrUnpinEvent).mockResolvedValue(undefined); + vi.spyOn(MediaEventHelper, "isEligible").mockReturnValue(false); + vi.spyOn(MediaEventHelper, "canHide").mockReturnValue(false); mockDownload.mockResolvedValue(undefined); - getHintsForMessageSpy = jest.spyOn(ModuleApi.instance.customComponents, "getHintsForMessage"); + getHintsForMessageSpy = vi.spyOn(ModuleApi.instance.customComponents, "getHintsForMessage"); getHintsForMessageSpy.mockReturnValue(null); }); afterEach(() => { getHintsForMessageSpy.mockRestore(); - jest.restoreAllMocks(); + vi.restoreAllMocks(); }); it("builds the snapshot for an actionable message", async () => { @@ -241,10 +240,10 @@ describe("EventTileActionBarViewModel", () => { }); it("reacts to media download permission hints and room state updates", async () => { - jest.spyOn(MediaEventHelper, "isEligible").mockReturnValue(true); - jest.spyOn(MediaEventHelper, "canHide").mockReturnValue(true); + vi.spyOn(MediaEventHelper, "isEligible").mockReturnValue(true); + vi.spyOn(MediaEventHelper, "canHide").mockReturnValue(true); getHintsForMessageSpy.mockReturnValue({ - allowDownloadingMedia: jest.fn().mockResolvedValue(true), + allowDownloadingMedia: vi.fn().mockResolvedValue(true), } as never); const vm = createVm({ @@ -258,7 +257,7 @@ describe("EventTileActionBarViewModel", () => { await waitFor(() => expect(vm.getSnapshot().actions).toContain(ActionBarAction.Download)); - mocked(PinningUtils.isPinned).mockReturnValue(true); + vi.mocked(PinningUtils.isPinned).mockReturnValue(true); roomState.emit( RoomStateEvent.Events, new MatrixEvent({ @@ -271,7 +270,7 @@ describe("EventTileActionBarViewModel", () => { expect(vm.getSnapshot().isPinned).toBe(true); - mocked(getMediaVisibility).mockReturnValue(false); + vi.mocked(getMediaVisibility).mockReturnValue(false); roomState.emit( RoomStateEvent.Events, new MatrixEvent({ @@ -286,7 +285,7 @@ describe("EventTileActionBarViewModel", () => { }); it("ignores stale download permission results after setProps changes the event", async () => { - jest.spyOn(MediaEventHelper, "isEligible").mockReturnValue(true); + vi.spyOn(MediaEventHelper, "isEligible").mockReturnValue(true); const permissionA = createPendingPromise(); const permissionB = createPendingPromise(); const eventA = createMessageEvent({ @@ -301,13 +300,13 @@ describe("EventTileActionBarViewModel", () => { getHintsForMessageSpy.mockImplementation((event) => { if (event === eventA) { return { - allowDownloadingMedia: jest.fn().mockReturnValue(permissionA.promise), + allowDownloadingMedia: vi.fn().mockReturnValue(permissionA.promise), } as never; } if (event === eventB) { return { - allowDownloadingMedia: jest.fn().mockReturnValue(permissionB.promise), + allowDownloadingMedia: vi.fn().mockReturnValue(permissionB.promise), } as never; } @@ -331,8 +330,8 @@ describe("EventTileActionBarViewModel", () => { it("refreshes on event status changes and removes listeners on dispose", () => { const mxEvent = createMessageEvent(); - const offSpy = jest.spyOn(mxEvent, "off"); - const roomStateOffSpy = jest.spyOn(roomState, "off"); + const offSpy = vi.spyOn(mxEvent, "off"); + const roomStateOffSpy = vi.spyOn(roomState, "off"); const vm = createVm({ mxEvent }); expect(vm.getSnapshot().actions).not.toContain(ActionBarAction.Cancel); @@ -360,8 +359,8 @@ describe("EventTileActionBarViewModel", () => { localRedactionEvent.setStatus(EventStatus.SENT); replacingEvent.setStatus(EventStatus.QUEUED); - jest.spyOn(mxEvent, "localRedactionEvent").mockReturnValue(localRedactionEvent); - jest.spyOn(mxEvent, "replacingEvent").mockReturnValue(replacingEvent); + vi.spyOn(mxEvent, "localRedactionEvent").mockReturnValue(localRedactionEvent); + vi.spyOn(mxEvent, "replacingEvent").mockReturnValue(replacingEvent); const vm = createVm({ mxEvent }); @@ -374,7 +373,7 @@ describe("EventTileActionBarViewModel", () => { it("downloads a cached blob and shows an error dialog on failure", async () => { const blob = new Blob(["downloaded"]); - jest.spyOn(MediaEventHelper, "isEligible").mockReturnValue(true); + vi.spyOn(MediaEventHelper, "isEligible").mockReturnValue(true); const vm = createVm({ mxEvent: createMessageEvent({ @@ -404,7 +403,7 @@ describe("EventTileActionBarViewModel", () => { }); it("ignores stale download completion after setProps changes the event", async () => { - jest.spyOn(MediaEventHelper, "isEligible").mockReturnValue(true); + vi.spyOn(MediaEventHelper, "isEligible").mockReturnValue(true); const firstDownload = createPendingPromise(); const eventA = createMessageEvent({ event_id: "$eventA", @@ -443,7 +442,7 @@ describe("EventTileActionBarViewModel", () => { }); it("ignores stale download permission results after dispose", async () => { - jest.spyOn(MediaEventHelper, "isEligible").mockReturnValue(true); + vi.spyOn(MediaEventHelper, "isEligible").mockReturnValue(true); const permission = createPendingPromise(); const event = createMessageEvent({ event_id: "$eventA", @@ -451,7 +450,7 @@ describe("EventTileActionBarViewModel", () => { }); getHintsForMessageSpy.mockReturnValue({ - allowDownloadingMedia: jest.fn().mockReturnValue(permission.promise), + allowDownloadingMedia: vi.fn().mockReturnValue(permission.promise), } as never); const vm = createVm({ mxEvent: event }); @@ -465,9 +464,9 @@ describe("EventTileActionBarViewModel", () => { }); it("dispatches reply and thread actions and forwards callbacks", async () => { - const onOptionsClick = jest.fn(); - const onReactionsClick = jest.fn(); - const onToggleThreadExpanded = jest.fn(); + const onOptionsClick = vi.fn(); + const onReactionsClick = vi.fn(); + const onToggleThreadExpanded = vi.fn(); const threadReply = createMessageEvent({ sender: "@bob:example.org", event_id: "$reply", @@ -482,7 +481,7 @@ describe("EventTileActionBarViewModel", () => { }); Object.defineProperty(threadReply, "isThreadRoot", { value: false }); - jest.spyOn(threadReply, "getThread").mockReturnValue({ rootEvent } as never); + vi.spyOn(threadReply, "getThread").mockReturnValue({ rootEvent } as never); const vm = createVm({ mxEvent: threadReply, @@ -491,7 +490,7 @@ describe("EventTileActionBarViewModel", () => { onReactionsClick, onToggleThreadExpanded, }); - mocked(PinningUtils.isPinned).mockReturnValue(false); + vi.mocked(PinningUtils.isPinned).mockReturnValue(false); vm.onReplyClick(null); vm.onReplyInThreadClick(null); @@ -555,7 +554,7 @@ describe("EventTileActionBarViewModel", () => { unexpectedActions: [ActionBarAction.React], }, ])("$name", ({ actionable, props, expectedActions, unexpectedActions }) => { - mocked(isContentActionable).mockReturnValue(actionable); + vi.mocked(isContentActionable).mockReturnValue(actionable); const vm = createVm(props); @@ -583,7 +582,7 @@ describe("EventTileActionBarViewModel", () => { expected: false, }, ])("$name", ({ quoteExpanded, displayReply, expected }) => { - mocked(shouldDisplayReply).mockReturnValue(displayReply); + vi.mocked(shouldDisplayReply).mockReturnValue(displayReply); const vm = createVm({ isQuoteExpanded: quoteExpanded }); @@ -644,7 +643,7 @@ describe("EventTileActionBarViewModel", () => { event_id: "$scenario", content, }); - jest.spyOn(mxEvent, "getRelation").mockReturnValue(relation as never); + vi.spyOn(mxEvent, "getRelation").mockReturnValue(relation as never); const vm = createVm({ mxEvent, timelineRenderingType }); @@ -654,8 +653,8 @@ describe("EventTileActionBarViewModel", () => { it("shows thread action for deleted messages with a thread in the room timeline", () => { const mxEvent = createMessageEvent(); - mocked(isContentActionable).mockReturnValue(false); - jest.spyOn(mxEvent, "getThread").mockReturnValue({ rootEvent } as never); + vi.mocked(isContentActionable).mockReturnValue(false); + vi.spyOn(mxEvent, "getThread").mockReturnValue({ rootEvent } as never); const vm = createVm({ mxEvent, timelineRenderingType: TimelineRenderingType.Room }); @@ -664,10 +663,10 @@ describe("EventTileActionBarViewModel", () => { }); it("matches media visibility rules for hide and download actions", async () => { - jest.spyOn(MediaEventHelper, "isEligible").mockReturnValue(true); - jest.spyOn(MediaEventHelper, "canHide").mockReturnValue(true); + vi.spyOn(MediaEventHelper, "isEligible").mockReturnValue(true); + vi.spyOn(MediaEventHelper, "canHide").mockReturnValue(true); getHintsForMessageSpy.mockReturnValue({ - allowDownloadingMedia: jest.fn().mockResolvedValue(false), + allowDownloadingMedia: vi.fn().mockResolvedValue(false), } as never); const mxEvent = createMessageEvent({ @@ -685,7 +684,7 @@ describe("EventTileActionBarViewModel", () => { }); it("recomputes parity-relevant flags and resets download state when the event changes", () => { - jest.spyOn(MediaEventHelper, "isEligible").mockReturnValue(true); + vi.spyOn(MediaEventHelper, "isEligible").mockReturnValue(true); const vm = createVm({ mxEvent: createMessageEvent({ @@ -696,8 +695,8 @@ describe("EventTileActionBarViewModel", () => { (vm as unknown as { downloadedBlob?: Blob; isDownloadLoading: boolean }).downloadedBlob = new Blob(["x"]); (vm as unknown as { downloadedBlob?: Blob; isDownloadLoading: boolean }).isDownloadLoading = true; - mocked(isContentActionable).mockReturnValue(false); - jest.spyOn(MediaEventHelper, "isEligible").mockReturnValue(false); + vi.mocked(isContentActionable).mockReturnValue(false); + vi.spyOn(MediaEventHelper, "isEligible").mockReturnValue(false); vm.setProps({ mxEvent: createMessageEvent({ diff --git a/apps/web/test/viewmodels/room/RoomStatusBar-test.ts b/apps/web/src/viewmodels/room/RoomStatusBar.test.ts similarity index 93% rename from apps/web/test/viewmodels/room/RoomStatusBar-test.ts rename to apps/web/src/viewmodels/room/RoomStatusBar.test.ts index b4119ffddd..de92231250 100644 --- a/apps/web/test/viewmodels/room/RoomStatusBar-test.ts +++ b/apps/web/src/viewmodels/room/RoomStatusBar.test.ts @@ -5,6 +5,8 @@ * Please see LICENSE files in the repository root for full details. */ +// @vitest-environment happy-dom + import { SyncState, MatrixError, @@ -15,11 +17,11 @@ import { EventStatus, } from "matrix-js-sdk/src/matrix"; import { RoomStatusBarState } from "@element-hq/web-shared-components"; -import { type MockedObject } from "jest-mock-vitest-adapter"; +import { vi, describe, it, expect, beforeEach, afterEach, type MockedObject } from "vitest"; +import { mkEvent, mkRoom, stubClient } from "test-utils"; -import { mkEvent, mkRoom, stubClient } from "../../test-utils"; -import { RoomStatusBarViewModel } from "../../../src/viewmodels/room/RoomStatusBar"; -import { LocalRoom, LocalRoomState } from "../../../src/models/LocalRoom"; +import { RoomStatusBarViewModel } from "./RoomStatusBar"; +import { LocalRoom, LocalRoomState } from "../../models/LocalRoom"; const userId = "@example:example.org"; @@ -43,7 +45,7 @@ describe("RoomStatusBarViewModel", () => { beforeEach(() => { client = stubClient() as MockedObject; room = mkRoom(client, "!example"); - jest.spyOn(room, "on").mockImplementationOnce((_event, fn) => { + vi.spyOn(room, "on").mockImplementationOnce((_event, fn) => { roomEmitFn = fn as any; return room; }); @@ -53,7 +55,7 @@ describe("RoomStatusBarViewModel", () => { }); afterEach(() => { - jest.restoreAllMocks(); + vi.restoreAllMocks(); }); it("should not be visible by default", () => { diff --git a/apps/web/test/viewmodels/room/RoomUploadViewModel-test.tsx b/apps/web/src/viewmodels/room/RoomUploadViewModel.test.tsx similarity index 89% rename from apps/web/test/viewmodels/room/RoomUploadViewModel-test.tsx rename to apps/web/src/viewmodels/room/RoomUploadViewModel.test.tsx index ce17c09c52..43f433cceb 100644 --- a/apps/web/test/viewmodels/room/RoomUploadViewModel-test.tsx +++ b/apps/web/src/viewmodels/room/RoomUploadViewModel.test.tsx @@ -4,37 +4,41 @@ * 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. */ + +// @vitest-environment happy-dom + import React from "react"; import { type IEventRelation, type MatrixClient, type Room, RoomEvent } from "matrix-js-sdk/src/matrix"; -import { render } from "jest-matrix-react"; +import { render } from "test-utils-rtl"; +import { vi, describe, it, expect, beforeEach, afterAll, type MockedObject } from "vitest"; +import { getRoomContext, mkEvent, mkStubRoom, stubClient } from "test-utils"; -import type { MockedObject } from "jest-mock"; -import { RoomUploadContextProvider, RoomUploadViewModel } from "../../../src/viewmodels/room/RoomUploadViewModel"; -import { getRoomContext, mkEvent, mkStubRoom, stubClient } from "../../test-utils"; -import { TimelineRenderingType } from "../../../src/contexts/RoomContext"; -import defaultDispatcher, { MatrixDispatcher } from "../../../src/dispatcher/dispatcher"; -import ContentMessages from "../../../src/ContentMessages"; -import { ComposerApi } from "../../../src/modules/ComposerApi"; -import type { ComposerInsertFilesPayload } from "../../../src/dispatcher/payloads/ComposerInsertFilePayload"; -import { ScopedRoomContextProvider } from "../../../src/contexts/ScopedRoomContext"; -import { Action } from "../../../src/dispatcher/actions"; -import MatrixClientContext from "../../../src/contexts/MatrixClientContext"; -const sendContentListToRoomSpy = jest.spyOn(ContentMessages.sharedInstance(), "sendContentListToRoom"); +import { RoomUploadContextProvider, RoomUploadViewModel } from "./RoomUploadViewModel"; +import { TimelineRenderingType } from "../../contexts/RoomContext"; +import defaultDispatcher, { MatrixDispatcher } from "../../dispatcher/dispatcher"; +import ContentMessages from "../../ContentMessages"; +import { ComposerApi } from "../../modules/ComposerApi"; +import type { ComposerInsertFilesPayload } from "../../dispatcher/payloads/ComposerInsertFilePayload"; +import { ScopedRoomContextProvider } from "../../contexts/ScopedRoomContext"; +import { Action } from "../../dispatcher/actions"; +import MatrixClientContext from "../../contexts/MatrixClientContext"; + +const sendContentListToRoomSpy = vi.spyOn(ContentMessages.sharedInstance(), "sendContentListToRoom"); describe("RoomUploadViewModel", () => { let client: MockedObject; let room: MockedObject; let dis: MockedObject; beforeEach(() => { - jest.clearAllMocks(); + vi.clearAllMocks(); client = stubClient() as MockedObject; room = mkStubRoom("!room", undefined, undefined) as MockedObject; dis = { - dispatch: jest.fn(), + dispatch: vi.fn(), } as Partial as MockedObject; }); afterAll(() => { - jest.restoreAllMocks(); + vi.restoreAllMocks(); }); it.each([true, false])("handles state when room.maySendMessage = %s", (maySendMessage) => { @@ -69,7 +73,7 @@ describe("RoomUploadViewModel", () => { () => {}, compApi, ); - const onSelected = jest.fn(); + const onSelected = vi.fn(); const icon = { myicon: 5 } as any; compApi.addFileUploadOption({ type: "org.example.test", diff --git a/apps/web/test/viewmodels/room/ThreadListActionBarViewModel-test.ts b/apps/web/src/viewmodels/room/ThreadListActionBarViewModel.test.ts similarity index 83% rename from apps/web/test/viewmodels/room/ThreadListActionBarViewModel-test.ts rename to apps/web/src/viewmodels/room/ThreadListActionBarViewModel.test.ts index 64b00aa056..090093bdf2 100644 --- a/apps/web/test/viewmodels/room/ThreadListActionBarViewModel-test.ts +++ b/apps/web/src/viewmodels/room/ThreadListActionBarViewModel.test.ts @@ -5,9 +5,12 @@ * Please see LICENSE files in the repository root for full details. */ -import { ActionBarAction } from "@element-hq/web-shared-components"; +// @vitest-environment happy-dom -import { ThreadListActionBarViewModel } from "../../../src/viewmodels/room/ThreadListActionBarViewModel"; +import { ActionBarAction } from "@element-hq/web-shared-components"; +import { vi, describe, it, expect } from "vitest"; + +import { ThreadListActionBarViewModel } from "./ThreadListActionBarViewModel"; describe("ThreadListActionBarViewModel", () => { it("builds the thread-list action bar snapshot", () => { @@ -25,8 +28,8 @@ describe("ThreadListActionBarViewModel", () => { }); it("forwards actions to the configured handlers", () => { - const onViewInRoomClick = jest.fn(); - const onCopyLinkClick = jest.fn(); + const onViewInRoomClick = vi.fn(); + const onCopyLinkClick = vi.fn(); const vm = new ThreadListActionBarViewModel({ onViewInRoomClick, onCopyLinkClick, @@ -41,8 +44,8 @@ describe("ThreadListActionBarViewModel", () => { }); it("uses updated handlers after setProps", () => { - const initialOnViewInRoomClick = jest.fn(); - const nextOnViewInRoomClick = jest.fn(); + const initialOnViewInRoomClick = vi.fn(); + const nextOnViewInRoomClick = vi.fn(); const vm = new ThreadListActionBarViewModel({ onViewInRoomClick: initialOnViewInRoomClick, }); diff --git a/apps/web/test/viewmodels/room/notification-badge/NotificationBadgeViewModel-test.ts b/apps/web/src/viewmodels/room/notification-badge/NotificationBadgeViewModel.test.ts similarity index 90% rename from apps/web/test/viewmodels/room/notification-badge/NotificationBadgeViewModel-test.ts rename to apps/web/src/viewmodels/room/notification-badge/NotificationBadgeViewModel.test.ts index 2debb3dd8e..93c9df25cf 100644 --- a/apps/web/test/viewmodels/room/notification-badge/NotificationBadgeViewModel-test.ts +++ b/apps/web/src/viewmodels/room/notification-badge/NotificationBadgeViewModel.test.ts @@ -5,8 +5,10 @@ * Please see LICENSE files in the repository root for full details. */ -import { NotificationBadgeViewModel } from "../../../../src/viewmodels/room/notification-badge/NotificationBadgeViewModel"; -import { NotificationLevel } from "../../../../src/stores/notifications/NotificationLevel"; +import { vi, describe, it, expect } from "vitest"; + +import { NotificationBadgeViewModel } from "./NotificationBadgeViewModel"; +import { NotificationLevel } from "../../../stores/notifications/NotificationLevel"; describe("NotificationBadgeViewModel", () => { it("computes an activity dot snapshot", () => { @@ -34,7 +36,7 @@ describe("NotificationBadgeViewModel", () => { count: 0, level: NotificationLevel.Activity, }); - const listener = jest.fn(); + const listener = vi.fn(); vm.subscribe(listener); vm.setHideIfDot(false); @@ -83,7 +85,7 @@ describe("NotificationBadgeViewModel", () => { }); it("updates clickable options without emitting for unchanged values", () => { - const onClick = jest.fn(); + const onClick = vi.fn(); const vm = new NotificationBadgeViewModel({ symbol: "!", count: 0, @@ -92,7 +94,7 @@ describe("NotificationBadgeViewModel", () => { ariaLabel: "Jump to unread", tabIndex: 0, }); - const listener = jest.fn(); + const listener = vi.fn(); vm.subscribe(listener); vm.setClickOptions({ diff --git a/apps/web/test/viewmodels/room/notification-badge/UnreadNotificationBadgeViewModel-test.ts b/apps/web/src/viewmodels/room/notification-badge/UnreadNotificationBadgeViewModel.test.ts similarity index 92% rename from apps/web/test/viewmodels/room/notification-badge/UnreadNotificationBadgeViewModel-test.ts rename to apps/web/src/viewmodels/room/notification-badge/UnreadNotificationBadgeViewModel.test.ts index 05b3497cad..53cf10858a 100644 --- a/apps/web/test/viewmodels/room/notification-badge/UnreadNotificationBadgeViewModel-test.ts +++ b/apps/web/src/viewmodels/room/notification-badge/UnreadNotificationBadgeViewModel.test.ts @@ -5,11 +5,14 @@ * Please see LICENSE files in the repository root for full details. */ +// @vitest-environment happy-dom + import { NotificationCountType, PendingEventOrdering, Room, RoomEvent } from "matrix-js-sdk/src/matrix"; +import { vi, describe, it, expect, beforeEach } from "vitest"; +import { stubClient } from "test-utils"; import type { MatrixClient } from "matrix-js-sdk/src/matrix"; -import { stubClient } from "../../../test-utils/test-utils"; -import { UnreadNotificationBadgeViewModel } from "../../../../src/viewmodels/room/notification-badge/UnreadNotificationBadgeViewModel"; +import { UnreadNotificationBadgeViewModel } from "./UnreadNotificationBadgeViewModel"; describe("UnreadNotificationBadgeViewModel", () => { let client: MatrixClient; @@ -54,7 +57,7 @@ describe("UnreadNotificationBadgeViewModel", () => { it("updates when the room unread state changes", () => { const vm = new UnreadNotificationBadgeViewModel({ room }); - const listener = jest.fn(); + const listener = vi.fn(); vm.subscribe(listener); setUnreads(0, 2); @@ -71,7 +74,7 @@ describe("UnreadNotificationBadgeViewModel", () => { it("skips unchanged force-dot setter updates", () => { setUnreads(1, 0); const vm = new UnreadNotificationBadgeViewModel({ room, forceDot: false }); - const listener = jest.fn(); + const listener = vi.fn(); vm.subscribe(listener); vm.setForceDot(false); diff --git a/apps/web/test/viewmodels/room/right-panel/WidgetContextMenuViewModel-test.tsx b/apps/web/src/viewmodels/room/right-panel/WidgetContextMenuViewModel.test.tsx similarity index 73% rename from apps/web/test/viewmodels/room/right-panel/WidgetContextMenuViewModel-test.tsx rename to apps/web/src/viewmodels/room/right-panel/WidgetContextMenuViewModel.test.tsx index 6c99855fda..b39484676c 100644 --- a/apps/web/test/viewmodels/room/right-panel/WidgetContextMenuViewModel-test.tsx +++ b/apps/web/src/viewmodels/room/right-panel/WidgetContextMenuViewModel.test.tsx @@ -5,25 +5,25 @@ * Please see LICENSE files in the repository root for full details. */ +// @vitest-environment happy-dom + import React from "react"; import { MatrixWidgetType } from "matrix-widget-api"; import { type MatrixClient, Room } from "matrix-js-sdk/src/matrix"; +import { vi, describe, it, expect, beforeEach, afterEach } from "vitest"; +import { stubClient } from "test-utils"; -import { - WidgetContextMenuViewModel, - type WidgetContextMenuViewModelProps, -} from "../../../../src/viewmodels/room/right-panel/WidgetContextMenuViewModel"; -import { stubClient } from "../../../test-utils"; -import WidgetUtils from "../../../../src/utils/WidgetUtils"; -import { type IApp } from "../../../../src/utils/WidgetUtils-types"; -import { WidgetLayoutStore } from "../../../../src/stores/widgets/WidgetLayoutStore"; -import * as livestream from "../../../../src/Livestream"; -import Modal from "../../../../src/Modal"; -import SettingsStore from "../../../../src/settings/SettingsStore"; -import { SettingLevel } from "../../../../src/settings/SettingLevel"; -import * as widgetStore from "../../../../src/stores/WidgetStore"; -import { WidgetMessagingStore } from "../../../../src/stores/widgets/WidgetMessagingStore"; -import { type WidgetMessaging } from "../../../../src/stores/widgets/WidgetMessaging"; +import { WidgetContextMenuViewModel, type WidgetContextMenuViewModelProps } from "./WidgetContextMenuViewModel"; +import WidgetUtils from "../../../utils/WidgetUtils"; +import { type IApp } from "../../../utils/WidgetUtils-types"; +import { WidgetLayoutStore } from "../../../stores/widgets/WidgetLayoutStore"; +import * as livestream from "../../../Livestream"; +import Modal from "../../../Modal"; +import SettingsStore from "../../../settings/SettingsStore"; +import { SettingLevel } from "../../../settings/SettingLevel"; +import * as widgetStore from "../../../stores/WidgetStore"; +import { WidgetMessagingStore } from "../../../stores/widgets/WidgetMessagingStore"; +import { type WidgetMessaging } from "../../../stores/widgets/WidgetMessaging"; describe("WidgetContextMenuViewModel", () => { const widgetId = "w1"; @@ -52,29 +52,29 @@ describe("WidgetContextMenuViewModel", () => { showUnpin: true, userWidget: true, trigger: <>, - onEditClick: jest.fn(), - onDeleteClick: jest.fn(), - onFinished: jest.fn(), + onEditClick: vi.fn(), + onDeleteClick: vi.fn(), + onFinished: vi.fn(), }; beforeEach(() => { - jest.spyOn(WidgetUtils, "canUserModifyWidgets").mockReturnValue(true); - jest.spyOn(WidgetUtils, "isManagedByManager").mockReturnValue(true); - jest.spyOn(WidgetUtils, "editWidget").mockReturnValue(); + vi.spyOn(WidgetUtils, "canUserModifyWidgets").mockReturnValue(true); + vi.spyOn(WidgetUtils, "isManagedByManager").mockReturnValue(true); + vi.spyOn(WidgetUtils, "editWidget").mockReturnValue(); const mockMessaging = { on: () => {}, off: () => {}, stop: () => {}, widgetApi: { - hasCapability: jest.fn(), + hasCapability: vi.fn(), }, } as unknown as WidgetMessaging; - jest.spyOn(WidgetMessagingStore.instance, "getMessagingForUid").mockReturnValue(mockMessaging); + vi.spyOn(WidgetMessagingStore.instance, "getMessagingForUid").mockReturnValue(mockMessaging); client = stubClient(); }); afterEach(() => { - jest.clearAllMocks(); + vi.clearAllMocks(); }); it("should return the snapshot", () => { @@ -130,7 +130,7 @@ describe("WidgetContextMenuViewModel", () => { }); it("should move widget position when onmovebutton is called", () => { - jest.spyOn(WidgetLayoutStore.instance, "moveWithinContainer").mockReturnValue(); + vi.spyOn(WidgetLayoutStore.instance, "moveWithinContainer").mockReturnValue(); const props = { ...defaultProps, room: new Room(roomId, client, userId), @@ -153,8 +153,8 @@ describe("WidgetContextMenuViewModel", () => { }); it("should startJitsiAudioLivestream when onStreamAudioClick button is clicked", async () => { - jest.spyOn(livestream, "startJitsiAudioLivestream").mockImplementation(jest.fn()); - jest.spyOn(livestream, "getConfigLivestreamUrl").mockReturnValue("https://url"); + vi.spyOn(livestream, "startJitsiAudioLivestream").mockImplementation(vi.fn()); + vi.spyOn(livestream, "getConfigLivestreamUrl").mockReturnValue("https://url"); const props = { ...defaultProps, room: new Room(roomId, client, userId), @@ -166,14 +166,14 @@ describe("WidgetContextMenuViewModel", () => { }); it("should show modal when startJitsiAudioLivestream is on error and onStreamAudioClick button is clicked", async () => { - jest.spyOn(livestream, "startJitsiAudioLivestream").mockImplementation(() => { + vi.spyOn(livestream, "startJitsiAudioLivestream").mockImplementation(() => { console.log("failllllled"); throw new Error("Failed"); }); - jest.spyOn(livestream, "getConfigLivestreamUrl").mockReturnValue("https://url"); - jest.spyOn(Modal, "createDialog").mockReturnValue({ + vi.spyOn(livestream, "getConfigLivestreamUrl").mockReturnValue("https://url"); + vi.spyOn(Modal, "createDialog").mockReturnValue({ finished: Promise.resolve([true, true, false]), - close: jest.fn(), + close: vi.fn(), }); const props = { @@ -186,8 +186,8 @@ describe("WidgetContextMenuViewModel", () => { }); it("should throw when no room is given and onStreamAudioClick button is clicked", async () => { - jest.spyOn(livestream, "startJitsiAudioLivestream").mockImplementation(jest.fn()); - jest.spyOn(livestream, "getConfigLivestreamUrl").mockReturnValue("https://url"); + vi.spyOn(livestream, "startJitsiAudioLivestream").mockImplementation(vi.fn()); + vi.spyOn(livestream, "getConfigLivestreamUrl").mockReturnValue("https://url"); const props = { ...defaultProps, room: new Room(roomId, client, userId), @@ -209,9 +209,9 @@ describe("WidgetContextMenuViewModel", () => { }); it("should display modal when no custom function is provided and a room is given", () => { - jest.spyOn(Modal, "createDialog").mockReturnValue({ + vi.spyOn(Modal, "createDialog").mockReturnValue({ finished: Promise.resolve([true, true, false]), - close: jest.fn(), + close: vi.fn(), }); const props = { @@ -242,10 +242,10 @@ describe("WidgetContextMenuViewModel", () => { it("should set new level for allowedwidget when onrevoke button is clicked", () => { const current = { [eventId]: true }; - jest.spyOn(SettingsStore, "getValue").mockReturnValue(current); - jest.spyOn(SettingsStore, "firstSupportedLevel").mockReturnValue(SettingLevel.DEFAULT); - jest.spyOn(SettingsStore, "setValue").mockResolvedValue(); - jest.spyOn(widgetStore, "isAppWidget").mockReturnValue(true); + vi.spyOn(SettingsStore, "getValue").mockReturnValue(current); + vi.spyOn(SettingsStore, "firstSupportedLevel").mockReturnValue(SettingLevel.DEFAULT); + vi.spyOn(SettingsStore, "setValue").mockResolvedValue(); + vi.spyOn(widgetStore, "isAppWidget").mockReturnValue(true); const props = { ...defaultProps, room: new Room(roomId, client, userId), @@ -262,10 +262,10 @@ describe("WidgetContextMenuViewModel", () => { ); const current2 = { [eventId]: false }; - jest.spyOn(SettingsStore, "getValue").mockReturnValue(current2); - jest.spyOn(SettingsStore, "firstSupportedLevel").mockReturnValue(SettingLevel.DEFAULT); - jest.spyOn(SettingsStore, "setValue").mockResolvedValue(); - jest.spyOn(widgetStore, "isAppWidget").mockReturnValue(false); + vi.spyOn(SettingsStore, "getValue").mockReturnValue(current2); + vi.spyOn(SettingsStore, "firstSupportedLevel").mockReturnValue(SettingLevel.DEFAULT); + vi.spyOn(SettingsStore, "setValue").mockResolvedValue(); + vi.spyOn(widgetStore, "isAppWidget").mockReturnValue(false); vm.onRevokeClick(); @@ -278,7 +278,7 @@ describe("WidgetContextMenuViewModel", () => { }); it("should throw an error when first supported level is not set", () => { - jest.spyOn(SettingsStore, "firstSupportedLevel").mockReturnValue(null); + vi.spyOn(SettingsStore, "firstSupportedLevel").mockReturnValue(null); const props = { ...defaultProps, room: undefined, diff --git a/apps/web/test/viewmodels/event-tiles/E2eMessageSharedIconViewModel-test.ts b/apps/web/src/viewmodels/room/timeline/event-tile/E2eMessageSharedIconViewModel.test.ts similarity index 91% rename from apps/web/test/viewmodels/event-tiles/E2eMessageSharedIconViewModel-test.ts rename to apps/web/src/viewmodels/room/timeline/event-tile/E2eMessageSharedIconViewModel.test.ts index 5f8571a6e4..685631aec9 100644 --- a/apps/web/test/viewmodels/event-tiles/E2eMessageSharedIconViewModel-test.ts +++ b/apps/web/src/viewmodels/room/timeline/event-tile/E2eMessageSharedIconViewModel.test.ts @@ -14,11 +14,12 @@ import { type RoomMember, type RoomState, } from "matrix-js-sdk/src/matrix"; +import { vi, describe, it, expect, type Mock } from "vitest"; -import { E2eMessageSharedIconViewModel } from "../../../src/viewmodels/room/timeline/event-tile/E2eMessageSharedIconViewModel"; +import { E2eMessageSharedIconViewModel } from "./E2eMessageSharedIconViewModel"; type TestRoomState = EventEmitter & { - getMember: jest.Mock; + getMember: Mock<(userId: string) => RoomMember | null>; }; const USER_ID = "@bob:example.com"; @@ -28,8 +29,8 @@ const OTHER_ROOM_ID = "!otherRoomId"; function createGetMember( displayNames: Record, -): jest.Mock { - const getMember = jest.fn((userId: string): RoomMember | null => { +): Mock<(userId: string) => RoomMember | null> { + const getMember = vi.fn((userId: string): RoomMember | null => { const displayName = displayNames[userId]; if (displayName === undefined) return null; @@ -47,8 +48,8 @@ function createRoomState(displayNames: Record = {}): function createRoom(roomState: RoomState): Room { const room = { - getLiveTimeline: jest.fn(() => ({ - getState: jest.fn((timeline: EventTimeline) => { + getLiveTimeline: vi.fn(() => ({ + getState: vi.fn((timeline: EventTimeline) => { expect(timeline).toBe(EventTimeline.FORWARDS); return roomState; }), @@ -60,7 +61,7 @@ function createRoom(roomState: RoomState): Room { function createClient(roomStates: Record): MatrixClient { return { - getRoom: jest.fn((roomId: string) => { + getRoom: vi.fn((roomId: string) => { const roomState = roomStates[roomId]; return roomState ? createRoom(roomState) : null; @@ -119,7 +120,7 @@ describe("E2eMessageSharedIconViewModel", () => { it("updates when room state events change the forwarding member display name", () => { const { roomState, vm } = createViewModel("Bob"); - const listener = jest.fn(); + const listener = vi.fn(); vm.subscribe(listener); roomState.getMember.mockReturnValue({ rawDisplayName: "Alice" } as RoomMember); @@ -140,7 +141,7 @@ describe("E2eMessageSharedIconViewModel", () => { roomId: ROOM_ID, keyForwardingUserId: USER_ID, }); - const listener = jest.fn(); + const listener = vi.fn(); vm.subscribe(listener); vm.setKeyForwardingUserId(OTHER_USER_ID); @@ -164,7 +165,7 @@ describe("E2eMessageSharedIconViewModel", () => { roomId: ROOM_ID, keyForwardingUserId: USER_ID, }); - const listener = jest.fn(); + const listener = vi.fn(); vm.subscribe(listener); vm.setRoomId(OTHER_ROOM_ID); @@ -189,7 +190,7 @@ describe("E2eMessageSharedIconViewModel", () => { it("does not emit updates when setters receive unchanged values", () => { const { vm } = createViewModel("Bob"); - const listener = jest.fn(); + const listener = vi.fn(); vm.subscribe(listener); vm.setRoomId(ROOM_ID); diff --git a/apps/web/test/viewmodels/event-tiles/EncryptionEventViewModel-test.ts b/apps/web/src/viewmodels/room/timeline/event-tile/EncryptionEventViewModel.test.ts similarity index 82% rename from apps/web/test/viewmodels/event-tiles/EncryptionEventViewModel-test.ts rename to apps/web/src/viewmodels/room/timeline/event-tile/EncryptionEventViewModel.test.ts index 6ffbb093b6..06423902b5 100644 --- a/apps/web/test/viewmodels/event-tiles/EncryptionEventViewModel-test.ts +++ b/apps/web/src/viewmodels/room/timeline/event-tile/EncryptionEventViewModel.test.ts @@ -5,16 +5,18 @@ * Please see LICENSE files in the repository root for full details. */ +// @vitest-environment happy-dom + import { waitFor } from "@testing-library/dom"; -import { mocked } from "jest-mock"; import { RoomStateEvent, type MatrixClient, type MatrixEvent, type Room } from "matrix-js-sdk/src/matrix"; import { EncryptionEventState } from "@element-hq/web-shared-components"; +import { vi, describe, it, expect, beforeEach } from "vitest"; +import { mkEvent, stubClient } from "test-utils"; import type { RoomEncryptionEventContent } from "matrix-js-sdk/src/types"; -import { EncryptionEventViewModel } from "../../../src/viewmodels/room/timeline/event-tile/EncryptionEventViewModel"; -import { LocalRoom } from "../../../src/models/LocalRoom"; -import DMRoomMap from "../../../src/utils/DMRoomMap"; -import { mkEvent, stubClient } from "../../test-utils"; +import { EncryptionEventViewModel } from "./EncryptionEventViewModel"; +import { LocalRoom } from "../../../../models/LocalRoom"; +import DMRoomMap from "../../../../utils/DMRoomMap"; describe("EncryptionEventViewModel", () => { const roomId = "!room:example.com"; @@ -24,10 +26,10 @@ describe("EncryptionEventViewModel", () => { let room: Room; beforeEach(() => { - jest.clearAllMocks(); + vi.clearAllMocks(); client = stubClient(); room = client.getRoom(roomId)!; - mocked(client.getRoom).mockReturnValue(room); + vi.mocked(client.getRoom).mockReturnValue(room); event = mkEvent({ event: true, room: roomId, @@ -38,14 +40,14 @@ describe("EncryptionEventViewModel", () => { }, prev_content: {}, }); - jest.spyOn(DMRoomMap, "shared").mockReturnValue({ - getUserIdForRoomId: jest.fn(), + vi.spyOn(DMRoomMap, "shared").mockReturnValue({ + getUserIdForRoomId: vi.fn(), } as unknown as DMRoomMap); }); const setRoomEncrypted = (encrypted: boolean): void => { const crypto = client.getCrypto()!; - mocked(crypto.isEncryptionEnabledInRoom).mockResolvedValue(encrypted); + vi.mocked(crypto.isEncryptionEnabledInRoom).mockResolvedValue(encrypted); }; const createVm = ( @@ -69,7 +71,7 @@ describe("EncryptionEventViewModel", () => { }); it("uses synchronous room encryption state for the initial snapshot", () => { - jest.spyOn(room, "hasEncryptionStateEvent").mockReturnValue(true); + vi.spyOn(room, "hasEncryptionStateEvent").mockReturnValue(true); setRoomEncrypted(false); const vm = createVm(); @@ -128,10 +130,10 @@ describe("EncryptionEventViewModel", () => { it("sets ENABLED_DM with partner display name", async () => { setRoomEncrypted(true); - jest.spyOn(DMRoomMap, "shared").mockReturnValue({ - getUserIdForRoomId: jest.fn().mockReturnValue("@alice:example.com"), + vi.spyOn(DMRoomMap, "shared").mockReturnValue({ + getUserIdForRoomId: vi.fn().mockReturnValue("@alice:example.com"), } as unknown as DMRoomMap); - mocked(room.getMember).mockReturnValue({ + vi.mocked(room.getMember).mockReturnValue({ rawDisplayName: "Alice", } as unknown as ReturnType); @@ -143,8 +145,8 @@ describe("EncryptionEventViewModel", () => { it("sets ENABLED_LOCAL for encrypted local room", async () => { const localRoomId = "local+123"; const localRoom = new LocalRoom(localRoomId, client, client.getUserId()!); - jest.spyOn(localRoom, "isEncryptionEnabled").mockReturnValue(true); - mocked(client.getRoom).mockReturnValue(localRoom); + vi.spyOn(localRoom, "isEncryptionEnabled").mockReturnValue(true); + vi.mocked(client.getRoom).mockReturnValue(localRoom); event = mkEvent({ event: true, room: localRoomId, @@ -153,8 +155,8 @@ describe("EncryptionEventViewModel", () => { content: { algorithm }, prev_content: {}, }); - jest.spyOn(DMRoomMap, "shared").mockReturnValue({ - getUserIdForRoomId: jest.fn(), + vi.spyOn(DMRoomMap, "shared").mockReturnValue({ + getUserIdForRoomId: vi.fn(), } as unknown as DMRoomMap); const vm = createVm(); @@ -178,12 +180,12 @@ describe("EncryptionEventViewModel", () => { const vm = createVm(); await waitFor(() => expect(vm.getSnapshot().state).toBe(EncryptionEventState.ENABLED)); - const listener = jest.fn(); + const listener = vi.fn(); const unsubscribe = vm.subscribe(listener); room.emit(RoomStateEvent.Update, room.currentState); - await waitFor(() => expect(mocked(client.getCrypto()!.isEncryptionEnabledInRoom)).toHaveBeenCalledTimes(2)); + await waitFor(() => expect(vi.mocked(client.getCrypto()!.isEncryptionEnabledInRoom)).toHaveBeenCalledTimes(2)); expect(listener).not.toHaveBeenCalled(); unsubscribe(); }); diff --git a/apps/web/test/unit-tests/viewmodels/room/timeline/event-tile/EventPreviewViewModel-test.tsx b/apps/web/src/viewmodels/room/timeline/event-tile/EventPreviewViewModel.test.tsx similarity index 90% rename from apps/web/test/unit-tests/viewmodels/room/timeline/event-tile/EventPreviewViewModel-test.tsx rename to apps/web/src/viewmodels/room/timeline/event-tile/EventPreviewViewModel.test.tsx index 62994994af..34ad4f7e5a 100644 --- a/apps/web/test/unit-tests/viewmodels/room/timeline/event-tile/EventPreviewViewModel-test.tsx +++ b/apps/web/src/viewmodels/room/timeline/event-tile/EventPreviewViewModel.test.tsx @@ -5,19 +5,22 @@ * Please see LICENSE files in the repository root for full details. */ -import React from "react"; -import { render, screen, waitFor } from "jest-matrix-react"; -import { EventType, type MatrixClient, MatrixEvent, MsgType } from "matrix-js-sdk/src/matrix"; +// @vitest-environment happy-dom -import { EventPreviewViewModel } from "../../../../../../src/viewmodels/room/timeline/event-tile/EventPreviewViewModel"; -import { mkEvent, stubClient } from "../../../../../test-utils"; +import React from "react"; +import { render, screen, waitFor } from "test-utils-rtl"; +import { EventType, type MatrixClient, MatrixEvent, MsgType } from "matrix-js-sdk/src/matrix"; +import { vi, describe, it, expect, beforeEach, afterEach, type Mock } from "vitest"; +import { mkEvent, stubClient } from "test-utils"; + +import { EventPreviewViewModel } from "./EventPreviewViewModel"; describe("EventPreviewViewModel", () => { const roomId = "!room:example.com"; const userId = "@alice:example.com"; let cli: MatrixClient; - let decryptEventIfNeeded: jest.SpiedFunction; + let decryptEventIfNeeded: Mock; const makeMessageEvent = ({ body = "Hello", @@ -39,11 +42,11 @@ describe("EventPreviewViewModel", () => { beforeEach(() => { cli = stubClient(); - decryptEventIfNeeded = jest.spyOn(cli, "decryptEventIfNeeded").mockResolvedValue(undefined); + decryptEventIfNeeded = vi.spyOn(cli, "decryptEventIfNeeded").mockResolvedValue(undefined); }); afterEach(() => { - jest.restoreAllMocks(); + vi.restoreAllMocks(); }); it("generates a text preview and tooltip", async () => { @@ -107,7 +110,7 @@ describe("EventPreviewViewModel", () => { const originalEvent = makeMessageEvent({ body: "Original" }); const updatedEvent = makeMessageEvent({ body: "Updated" }); const vm = new EventPreviewViewModel({ cli, mxEvent: originalEvent }); - const listener = jest.fn(); + const listener = vi.fn(); await waitFor(() => expect(vm.getSnapshot().previewContent).toBe("Original")); decryptEventIfNeeded.mockClear(); @@ -129,7 +132,7 @@ describe("EventPreviewViewModel", () => { it("removes event listeners when disposed", async () => { const mxEvent = makeMessageEvent({ body: "Original" }); const vm = new EventPreviewViewModel({ cli, mxEvent }); - const listener = jest.fn(); + const listener = vi.fn(); await waitFor(() => expect(vm.getSnapshot().previewContent).toBe("Original")); decryptEventIfNeeded.mockClear(); diff --git a/apps/web/test/viewmodels/event-tiles/EventTileE2eState-test.ts b/apps/web/src/viewmodels/room/timeline/event-tile/EventTileE2eState.test.ts similarity index 93% rename from apps/web/test/viewmodels/event-tiles/EventTileE2eState-test.ts rename to apps/web/src/viewmodels/room/timeline/event-tile/EventTileE2eState.test.ts index 0246ae36b3..c624ba6373 100644 --- a/apps/web/test/viewmodels/event-tiles/EventTileE2eState-test.ts +++ b/apps/web/src/viewmodels/room/timeline/event-tile/EventTileE2eState.test.ts @@ -5,16 +5,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. */ +// @vitest-environment happy-dom + import { EventStatus, EventType, type MatrixEvent, MsgType } from "matrix-js-sdk/src/matrix"; import { DecryptionFailureCode, EventShieldColour, EventShieldReason } from "matrix-js-sdk/src/crypto-api"; import { E2ePadlockIcon } from "@element-hq/web-shared-components"; +import { vi, describe, it, expect } from "vitest"; +import { mkEvent } from "test-utils"; -import { mkEvent } from "../../test-utils"; import { getEventTileE2ePadlockState, getEventTileE2ePadlockViewState, type EventTileE2ePadlockStateInput, -} from "../../../src/viewmodels/room/timeline/event-tile/EventTileE2eState"; +} from "./EventTileE2eState"; const roomId = "!room:example.org"; const userId = "@alice:example.org"; @@ -47,7 +50,7 @@ function makeInput(overrides: Partial = {}): Even } function mockDecryptionFailure(mxEvent: MatrixEvent, reason: DecryptionFailureCode): void { - jest.spyOn(mxEvent, "isDecryptionFailure").mockReturnValue(true); + vi.spyOn(mxEvent, "isDecryptionFailure").mockReturnValue(true); Object.defineProperty(mxEvent, "decryptionFailureReason", { configurable: true, value: reason, @@ -94,7 +97,7 @@ describe("EventTileE2eState", () => { it("shows a message-shared state when the authenticity warning has a key forwarding user", () => { const mxEvent = makeEvent(); - jest.spyOn(mxEvent, "getKeyForwardingUser").mockReturnValue("@bob:example.org"); + vi.spyOn(mxEvent, "getKeyForwardingUser").mockReturnValue("@bob:example.org"); const state = getEventTileE2ePadlockState( makeInput({ @@ -161,7 +164,7 @@ describe("EventTileE2eState", () => { it("does not show an unencrypted warning for state events in encrypted rooms", () => { const mxEvent = makeEvent(); - jest.spyOn(mxEvent, "isState").mockReturnValue(true); + vi.spyOn(mxEvent, "isState").mockReturnValue(true); const state = getEventTileE2ePadlockState(makeInput({ mxEvent, isRoomEncrypted: true })); @@ -170,7 +173,7 @@ describe("EventTileE2eState", () => { it("does not show an unencrypted warning for redacted events in encrypted rooms", () => { const mxEvent = makeEvent(); - jest.spyOn(mxEvent, "isRedacted").mockReturnValue(true); + vi.spyOn(mxEvent, "isRedacted").mockReturnValue(true); const state = getEventTileE2ePadlockState(makeInput({ mxEvent, isRoomEncrypted: true })); @@ -179,7 +182,7 @@ describe("EventTileE2eState", () => { it("does not show an unencrypted warning for encrypted events", () => { const mxEvent = makeEvent(); - jest.spyOn(mxEvent, "isEncrypted").mockReturnValue(true); + vi.spyOn(mxEvent, "isEncrypted").mockReturnValue(true); const state = getEventTileE2ePadlockState(makeInput({ mxEvent, isRoomEncrypted: true })); @@ -248,7 +251,7 @@ describe("EventTileE2eState", () => { it("keeps forwarded-message state renderable by the shared-message indicator", () => { const mxEvent = makeEvent(); - jest.spyOn(mxEvent, "getKeyForwardingUser").mockReturnValue("@bob:example.org"); + vi.spyOn(mxEvent, "getKeyForwardingUser").mockReturnValue("@bob:example.org"); const state = getEventTileE2ePadlockViewState( makeInput({ diff --git a/apps/web/test/viewmodels/event-tiles/EventTileE2eViewModel-test.ts b/apps/web/src/viewmodels/room/timeline/event-tile/EventTileE2eViewModel.test.ts similarity index 90% rename from apps/web/test/viewmodels/event-tiles/EventTileE2eViewModel-test.ts rename to apps/web/src/viewmodels/room/timeline/event-tile/EventTileE2eViewModel.test.ts index 30f4e772ee..57b3af84e3 100644 --- a/apps/web/test/viewmodels/event-tiles/EventTileE2eViewModel-test.ts +++ b/apps/web/src/viewmodels/room/timeline/event-tile/EventTileE2eViewModel.test.ts @@ -5,6 +5,8 @@ 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 { waitFor } from "@testing-library/dom"; import { EventType, MatrixEventEvent, type MatrixClient, type MatrixEvent, MsgType } from "matrix-js-sdk/src/matrix"; import { @@ -14,15 +16,16 @@ import { EventShieldReason, } from "matrix-js-sdk/src/crypto-api"; import { E2ePadlockIcon } from "@element-hq/web-shared-components"; +import { vi, describe, it, expect, beforeEach, afterEach } from "vitest"; +import { mkEvent, MockClientWithEventEmitter } from "test-utils"; -import { mkEvent, MockClientWithEventEmitter } from "../../test-utils"; -import { EventTileE2eViewModel } from "../../../src/viewmodels/room/timeline/event-tile/EventTileE2eViewModel"; +import { EventTileE2eViewModel } from "./EventTileE2eViewModel"; function makeClient( - getEncryptionInfoForEvent = jest.fn, [MatrixEvent]>(), + getEncryptionInfoForEvent = vi.fn<(event: MatrixEvent) => Promise>(), ): MockClientWithEventEmitter & MatrixClient { return new MockClientWithEventEmitter({ - getCrypto: jest.fn(() => ({ + getCrypto: vi.fn(() => ({ getEncryptionInfoForEvent, })), }) as MockClientWithEventEmitter & MatrixClient; @@ -64,9 +67,9 @@ describe("EventTileE2eViewModel", () => { it("verifies encrypted events on start", async () => { const mxEvent = makeEvent(); - jest.spyOn(mxEvent, "isEncrypted").mockReturnValue(true); + vi.spyOn(mxEvent, "isEncrypted").mockReturnValue(true); const cli = makeClient( - jest.fn().mockResolvedValue({ + vi.fn().mockResolvedValue({ shieldColour: EventShieldColour.GREY, shieldReason: EventShieldReason.UNSIGNED_DEVICE, } as EventEncryptionInfo), @@ -91,9 +94,9 @@ describe("EventTileE2eViewModel", () => { it("re-verifies when the sender verification changes", async () => { const mxEvent = makeEvent(); - jest.spyOn(mxEvent, "isEncrypted").mockReturnValue(true); + vi.spyOn(mxEvent, "isEncrypted").mockReturnValue(true); const cli = makeClient( - jest + vi .fn() .mockResolvedValueOnce({ shieldColour: EventShieldColour.GREY, @@ -127,9 +130,9 @@ describe("EventTileE2eViewModel", () => { it("uses the replacing event for verification after edits", async () => { const mxEvent = makeEvent(); const replacementEvent = makeEvent(); - jest.spyOn(mxEvent, "isEncrypted").mockReturnValue(true); - jest.spyOn(replacementEvent, "isEncrypted").mockReturnValue(true); - const getEncryptionInfoForEvent = jest.fn(async (event: MatrixEvent) => { + vi.spyOn(mxEvent, "isEncrypted").mockReturnValue(true); + vi.spyOn(replacementEvent, "isEncrypted").mockReturnValue(true); + const getEncryptionInfoForEvent = vi.fn(async (event: MatrixEvent) => { return { shieldColour: event === replacementEvent ? EventShieldColour.RED : EventShieldColour.NONE, shieldReason: event === replacementEvent ? EventShieldReason.UNKNOWN_DEVICE : null, @@ -233,8 +236,8 @@ describe("EventTileE2eViewModel", () => { it("does not re-verify when a different user's verification changes", async () => { const mxEvent = makeEvent(); - jest.spyOn(mxEvent, "isEncrypted").mockReturnValue(true); - const getEncryptionInfoForEvent = jest.fn().mockResolvedValue({ + vi.spyOn(mxEvent, "isEncrypted").mockReturnValue(true); + const getEncryptionInfoForEvent = vi.fn().mockResolvedValue({ shieldColour: EventShieldColour.GREY, shieldReason: EventShieldReason.UNSIGNED_DEVICE, } as EventEncryptionInfo); @@ -255,13 +258,13 @@ describe("EventTileE2eViewModel", () => { it("ignores stale async verification results", async () => { const mxEvent = makeEvent(); - jest.spyOn(mxEvent, "isEncrypted").mockReturnValue(true); + vi.spyOn(mxEvent, "isEncrypted").mockReturnValue(true); let resolveFirst: (value: EventEncryptionInfo) => void; const firstResult = new Promise((resolve) => { resolveFirst = resolve; }); - const getEncryptionInfoForEvent = jest + const getEncryptionInfoForEvent = vi .fn() .mockReturnValueOnce(firstResult) .mockResolvedValueOnce({ diff --git a/apps/web/test/viewmodels/event-tiles/EventTileInteractionState-test.ts b/apps/web/src/viewmodels/room/timeline/event-tile/EventTileInteractionState.test.ts similarity index 97% rename from apps/web/test/viewmodels/event-tiles/EventTileInteractionState-test.ts rename to apps/web/src/viewmodels/room/timeline/event-tile/EventTileInteractionState.test.ts index f9e75b9d60..e7ff034de7 100644 --- a/apps/web/test/viewmodels/event-tiles/EventTileInteractionState-test.ts +++ b/apps/web/src/viewmodels/room/timeline/event-tile/EventTileInteractionState.test.ts @@ -5,6 +5,8 @@ * Please see LICENSE files in the repository root for full details. */ +import { describe, it, expect } from "vitest"; + import { eventTileActionBarFocusChange, eventTileBlurWithin, @@ -16,7 +18,7 @@ import { eventTileOpenContextMenu, initialEventTileInteractionState, type EventTileInteractionState, -} from "../../../src/viewmodels/room/timeline/event-tile/EventTileInteractionState"; +} from "./EventTileInteractionState"; function makeState(overrides: Partial = {}): EventTileInteractionState { return { diff --git a/apps/web/test/viewmodels/event-tiles/EventTileReceiptState-test.ts b/apps/web/src/viewmodels/room/timeline/event-tile/EventTileReceiptState.test.ts similarity index 95% rename from apps/web/test/viewmodels/event-tiles/EventTileReceiptState-test.ts rename to apps/web/src/viewmodels/room/timeline/event-tile/EventTileReceiptState.test.ts index f780a31913..0989d13d37 100644 --- a/apps/web/test/viewmodels/event-tiles/EventTileReceiptState-test.ts +++ b/apps/web/src/viewmodels/room/timeline/event-tile/EventTileReceiptState.test.ts @@ -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. */ -import { EventStatus, EventType, M_POLL_END, M_POLL_START, type MatrixEvent, MsgType } from "matrix-js-sdk/src/matrix"; +// @vitest-environment happy-dom -import { mkEvent } from "../../test-utils"; -import { TimelineRenderingType } from "../../../src/contexts/RoomContext"; +import { EventStatus, EventType, M_POLL_END, M_POLL_START, type MatrixEvent, MsgType } from "matrix-js-sdk/src/matrix"; +import { describe, it, expect } from "vitest"; +import { mkEvent } from "test-utils"; + +import { TimelineRenderingType } from "../../../../contexts/RoomContext"; import { getEventTileReceiptState, isEligibleForSpecialReceipt, type EventTileReceiptStateInput, -} from "../../../src/viewmodels/room/timeline/event-tile/EventTileReceiptState"; +} from "./EventTileReceiptState"; const roomId = "!room:example.org"; const ownUserId = "@alice:example.org"; diff --git a/apps/web/test/viewmodels/event-tiles/EventTileReplyChainState-test.ts b/apps/web/src/viewmodels/room/timeline/event-tile/EventTileReplyChainState.test.ts similarity index 88% rename from apps/web/test/viewmodels/event-tiles/EventTileReplyChainState-test.ts rename to apps/web/src/viewmodels/room/timeline/event-tile/EventTileReplyChainState.test.ts index 3bcb8adff9..a917cbff13 100644 --- a/apps/web/test/viewmodels/event-tiles/EventTileReplyChainState-test.ts +++ b/apps/web/src/viewmodels/room/timeline/event-tile/EventTileReplyChainState.test.ts @@ -5,10 +5,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 MatrixEvent } from "matrix-js-sdk/src/matrix"; +// @vitest-environment happy-dom -import { mkMessage } from "../../test-utils"; -import { getEventTileReplyChainState } from "../../../src/viewmodels/room/timeline/event-tile/EventTileReplyChainState"; +import { type MatrixEvent } from "matrix-js-sdk/src/matrix"; +import { vi, describe, it, expect } from "vitest"; +import { mkMessage } from "test-utils"; + +import { getEventTileReplyChainState } from "./EventTileReplyChainState"; const roomId = "!room:example.org"; @@ -67,7 +70,7 @@ describe("EventTileReplyChainState", () => { it("does not show a reply chain for redacted reply events", () => { const replyEvent = makeReply(); - jest.spyOn(replyEvent, "isRedacted").mockReturnValue(true); + vi.spyOn(replyEvent, "isRedacted").mockReturnValue(true); const state = getEventTileReplyChainState({ mxEvent: replyEvent, diff --git a/apps/web/test/viewmodels/event-tiles/EventTileThreadState-test.ts b/apps/web/src/viewmodels/room/timeline/event-tile/EventTileThreadState.test.ts similarity index 88% rename from apps/web/test/viewmodels/event-tiles/EventTileThreadState-test.ts rename to apps/web/src/viewmodels/room/timeline/event-tile/EventTileThreadState.test.ts index 541597e805..61a1482c69 100644 --- a/apps/web/test/viewmodels/event-tiles/EventTileThreadState-test.ts +++ b/apps/web/src/viewmodels/room/timeline/event-tile/EventTileThreadState.test.ts @@ -5,16 +5,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. */ -import { EventType, type MatrixEvent, MsgType, type Thread } from "matrix-js-sdk/src/matrix"; +// @vitest-environment happy-dom -import { mkEvent } from "../../test-utils"; -import { TimelineRenderingType } from "../../../src/contexts/RoomContext"; +import { EventType, type MatrixEvent, MsgType, type Thread } from "matrix-js-sdk/src/matrix"; +import { vi, describe, it, expect } from "vitest"; +import { mkEvent } from "test-utils"; + +import { TimelineRenderingType } from "../../../../contexts/RoomContext"; import { getEventTileThread, getEventTileThreadState, type EventTileThreadLookup, type EventTileThreadStateInput, -} from "../../../src/viewmodels/room/timeline/event-tile/EventTileThreadState"; +} from "./EventTileThreadState"; const roomId = "!room:example.org"; const userId = "@alice:example.org"; @@ -67,9 +70,9 @@ describe("EventTileThreadState", () => { it("uses the event thread when it is already available", () => { const mxEvent = makeEvent(); const thread = makeThread(); - jest.spyOn(mxEvent, "getThread").mockReturnValue(thread); + vi.spyOn(mxEvent, "getThread").mockReturnValue(thread); const room: EventTileThreadLookup = { - findThreadForEvent: jest.fn(), + findThreadForEvent: vi.fn(), }; expect(getEventTileThread(mxEvent, room)).toBe(thread); @@ -79,9 +82,9 @@ describe("EventTileThreadState", () => { it("falls back to the room thread lookup", () => { const mxEvent = makeEvent(); const thread = makeThread(); - jest.spyOn(mxEvent, "getThread").mockReturnValue(undefined); + vi.spyOn(mxEvent, "getThread").mockReturnValue(undefined); const room: EventTileThreadLookup = { - findThreadForEvent: jest.fn().mockReturnValue(thread), + findThreadForEvent: vi.fn().mockReturnValue(thread), }; expect(getEventTileThread(mxEvent, room)).toBe(thread); @@ -90,7 +93,7 @@ describe("EventTileThreadState", () => { it("returns null when no thread can be found", () => { const mxEvent = makeEvent(); - jest.spyOn(mxEvent, "getThread").mockReturnValue(undefined); + vi.spyOn(mxEvent, "getThread").mockReturnValue(undefined); expect(getEventTileThread(mxEvent, null)).toBeNull(); }); @@ -108,7 +111,7 @@ describe("EventTileThreadState", () => { it("derives the thread panel timestamp from the latest reply", () => { const replyToEvent = makeEvent({ id: "$reply" }); - jest.spyOn(replyToEvent, "getTs").mockReturnValue(123); + vi.spyOn(replyToEvent, "getTs").mockReturnValue(123); const state = getEventTileThreadState( makeInput({ diff --git a/apps/web/test/viewmodels/event-tiles/EventTileViewModel-test.ts b/apps/web/src/viewmodels/room/timeline/event-tile/EventTileViewModel.test.ts similarity index 97% rename from apps/web/test/viewmodels/event-tiles/EventTileViewModel-test.ts rename to apps/web/src/viewmodels/room/timeline/event-tile/EventTileViewModel.test.ts index 823b66ef86..379ff8103c 100644 --- a/apps/web/test/viewmodels/event-tiles/EventTileViewModel-test.ts +++ b/apps/web/src/viewmodels/room/timeline/event-tile/EventTileViewModel.test.ts @@ -5,15 +5,19 @@ * Please see LICENSE files in the repository root for full details. */ -import { TimelineRenderingType } from "../../../src/contexts/RoomContext"; -import { Layout } from "../../../src/settings/enums/Layout"; -import { mkEvent, stubClient } from "../../test-utils"; +// @vitest-environment happy-dom + +import { vi, describe, it, expect } from "vitest"; +import { mkEvent, stubClient } from "test-utils"; + +import { TimelineRenderingType } from "../../../../contexts/RoomContext"; +import { Layout } from "../../../../settings/enums/Layout"; import { EventTileViewModel, type EventTileViewModelDependencies, type NormalizedEventTileViewModelProps, type EventTileViewModelProps, -} from "../../../src/viewmodels/room/timeline/event-tile/EventTileViewModel"; +} from "./EventTileViewModel"; describe("EventTileViewModel", () => { const matrixClient = stubClient(); @@ -508,7 +512,7 @@ describe("EventTileViewModel", () => { it("updates an instance snapshot when inputs change", () => { const vm = new EventTileViewModel(makeDependencies(), makeProps()); - const listener = jest.fn(); + const listener = vi.fn(); const unsubscribe = vm.subscribe(listener); expect(vm.getSnapshot().snapshot.timestamp.show).toBe(false); @@ -524,7 +528,7 @@ describe("EventTileViewModel", () => { it("emits once when dependencies and inputs are updated together", () => { const vm = new EventTileViewModel(makeDependencies(), makeProps()); - const listener = jest.fn(); + const listener = vi.fn(); const unsubscribe = vm.subscribe(listener); vm.setInputs(makeDependencies(), makeProps({ interaction: { hover: true } })); @@ -599,8 +603,8 @@ describe("EventTileViewModel", () => { it("normalizes event identity, replacement, renderer, and decryption state", () => { const event = makeEvent(); - jest.spyOn(event, "replacingEventId").mockReturnValue("$replaced-event"); - jest.spyOn(event, "isDecryptionFailure").mockReturnValue(true); + vi.spyOn(event, "replacingEventId").mockReturnValue("$replaced-event"); + vi.spyOn(event, "isDecryptionFailure").mockReturnValue(true); const vm = new EventTileViewModel(makeDependencies(event), makeProps()); const snapshot = vm.getSnapshot().snapshot; @@ -707,8 +711,8 @@ describe("EventTileViewModel", () => { it("owns and updates the thread-list action bar child view model", () => { const vm = new EventTileViewModel(makeDependencies(), makeProps()); - const onViewInRoomClick = jest.fn(); - const onCopyLinkClick = jest.fn(); + const onViewInRoomClick = vi.fn(); + const onCopyLinkClick = vi.fn(); const threadListActionBarViewModel = vm.getThreadListActionBarViewModel({ onViewInRoomClick, diff --git a/apps/web/test/viewmodels/event-tiles/MJitsiWidgetEventViewModel-test.ts b/apps/web/src/viewmodels/room/timeline/event-tile/MJitsiWidgetEventViewModel.test.ts similarity index 82% rename from apps/web/test/viewmodels/event-tiles/MJitsiWidgetEventViewModel-test.ts rename to apps/web/src/viewmodels/room/timeline/event-tile/MJitsiWidgetEventViewModel.test.ts index 1968b50b01..496b26b91c 100644 --- a/apps/web/test/viewmodels/event-tiles/MJitsiWidgetEventViewModel-test.ts +++ b/apps/web/src/viewmodels/room/timeline/event-tile/MJitsiWidgetEventViewModel.test.ts @@ -5,15 +5,18 @@ * Please see LICENSE files in the repository root for full details. */ +// @vitest-environment happy-dom + import { EventEmitter } from "node:events"; import { type MatrixClient, type Room } from "matrix-js-sdk/src/matrix"; +import { vi, describe, it, expect, beforeEach, afterEach } from "vitest"; +import { mkEvent, stubClient } from "test-utils"; -import { MJitsiWidgetEventViewModel } from "../../../src/viewmodels/room/timeline/event-tile/MJitsiWidgetEventViewModel"; -import { UPDATE_EVENT } from "../../../src/stores/AsyncStore"; -import { WidgetLayoutStore } from "../../../src/stores/widgets/WidgetLayoutStore"; -import { mkEvent, stubClient } from "../../test-utils"; -import type WidgetStore from "../../../src/stores/WidgetStore"; -import type { IApp } from "../../../src/stores/WidgetStore"; +import { MJitsiWidgetEventViewModel } from "./MJitsiWidgetEventViewModel"; +import { UPDATE_EVENT } from "../../../../stores/AsyncStore"; +import { WidgetLayoutStore } from "../../../../stores/widgets/WidgetLayoutStore"; +import type WidgetStore from "../../../../stores/WidgetStore"; +import type { IApp } from "../../../../stores/WidgetStore"; describe("MJitsiWidgetEventViewModel", () => { const roomId = "!room:example.com"; @@ -55,15 +58,15 @@ describe("MJitsiWidgetEventViewModel", () => { type: "m.jitsi", } as IApp; widgetStore = Object.assign(new EventEmitter(), { - getRoom: jest.fn().mockReturnValue({ widgets: [widget] }), + getRoom: vi.fn().mockReturnValue({ widgets: [widget] }), }) as unknown as WidgetStore & EventEmitter; widgetLayoutStore = Object.assign(new EventEmitter(), { - isInContainer: jest.fn().mockReturnValue(false), + isInContainer: vi.fn().mockReturnValue(false), }) as unknown as WidgetLayoutStore & EventEmitter; }); afterEach(() => { - jest.restoreAllMocks(); + vi.restoreAllMocks(); }); it("renders a started Jitsi event with the top join prompt", () => { @@ -77,7 +80,7 @@ describe("MJitsiWidgetEventViewModel", () => { }); it("uses the right-panel join prompt when the widget is in the right container", () => { - jest.mocked(widgetLayoutStore.isInContainer).mockReturnValue(true); + vi.mocked(widgetLayoutStore.isInContainer).mockReturnValue(true); const vm = createVm(); @@ -85,7 +88,7 @@ describe("MJitsiWidgetEventViewModel", () => { }); it("omits the join prompt when the widget no longer exists", () => { - jest.mocked(widgetStore.getRoom).mockReturnValue({ widgets: [] }); + vi.mocked(widgetStore.getRoom).mockReturnValue({ widgets: [] }); const vm = createVm(); @@ -121,7 +124,7 @@ describe("MJitsiWidgetEventViewModel", () => { }); it("hides the event when the room is unavailable", () => { - jest.spyOn(cli, "getRoom").mockReturnValue(null); + vi.spyOn(cli, "getRoom").mockReturnValue(null); const vm = createVm(); @@ -134,7 +137,7 @@ describe("MJitsiWidgetEventViewModel", () => { it("updates the snapshot when the event changes", () => { const vm = createVm(); - const listener = jest.fn(); + const listener = vi.fn(); vm.subscribe(listener); vm.setEvent(createEvent({ url: "https://jitsi.example.com/room" }, { url: "https://old.example.com/room" })); @@ -145,7 +148,7 @@ describe("MJitsiWidgetEventViewModel", () => { it("does not emit updates when setEvent receives the current event", () => { const mxEvent = createEvent({ url: "https://jitsi.example.com/room" }); - const listener = jest.fn(); + const listener = vi.fn(); const vm = createVm({ mxEvent }); vm.subscribe(listener); @@ -156,9 +159,9 @@ describe("MJitsiWidgetEventViewModel", () => { it("updates when widget stores emit for the room", () => { const vm = createVm(); - const listener = jest.fn(); + const listener = vi.fn(); vm.subscribe(listener); - jest.mocked(widgetLayoutStore.isInContainer).mockReturnValue(true); + vi.mocked(widgetLayoutStore.isInContainer).mockReturnValue(true); widgetStore.emit(UPDATE_EVENT, roomId); @@ -168,9 +171,9 @@ describe("MJitsiWidgetEventViewModel", () => { it("updates when the widget layout store emits for the room", () => { const vm = createVm(); - const listener = jest.fn(); + const listener = vi.fn(); vm.subscribe(listener); - jest.mocked(widgetLayoutStore.isInContainer).mockReturnValue(true); + vi.mocked(widgetLayoutStore.isInContainer).mockReturnValue(true); widgetLayoutStore.emit(WidgetLayoutStore.emissionForRoom(room)); diff --git a/apps/web/test/viewmodels/event-tiles/MKeyVerificationRequestViewModel-test.tsx b/apps/web/src/viewmodels/room/timeline/event-tile/MKeyVerificationRequestViewModel.test.tsx similarity index 89% rename from apps/web/test/viewmodels/event-tiles/MKeyVerificationRequestViewModel-test.tsx rename to apps/web/src/viewmodels/room/timeline/event-tile/MKeyVerificationRequestViewModel.test.tsx index 2afd7e4227..f8215a9a62 100644 --- a/apps/web/test/viewmodels/event-tiles/MKeyVerificationRequestViewModel-test.tsx +++ b/apps/web/src/viewmodels/room/timeline/event-tile/MKeyVerificationRequestViewModel.test.tsx @@ -7,8 +7,9 @@ import React from "react"; import { type MatrixClient, MatrixEvent, type Room, type RoomMember } from "matrix-js-sdk/src/matrix"; +import { vi, describe, it, expect, beforeEach } from "vitest"; -import { MKeyVerificationRequestViewModel } from "../../../src/viewmodels/room/timeline/event-tile/MKeyVerificationRequestViewModel"; +import { MKeyVerificationRequestViewModel } from "./MKeyVerificationRequestViewModel"; describe("MKeyVerificationRequestViewModel", () => { const roomId = "!room:example.org"; @@ -18,11 +19,11 @@ describe("MKeyVerificationRequestViewModel", () => { beforeEach(() => { room = { - getMember: jest.fn(), + getMember: vi.fn(), } as unknown as Room; cli = { - getSafeUserId: jest.fn().mockReturnValue(myUserId), - getRoom: jest.fn().mockReturnValue(room), + getSafeUserId: vi.fn().mockReturnValue(myUserId), + getRoom: vi.fn().mockReturnValue(room), } as unknown as MatrixClient; }); @@ -56,7 +57,7 @@ describe("MKeyVerificationRequestViewModel", () => { }); it("renders a request sent by me", () => { - jest.mocked(room.getMember).mockReturnValue({ + vi.mocked(room.getMember).mockReturnValue({ name: "Alice", } as RoomMember); @@ -72,7 +73,7 @@ describe("MKeyVerificationRequestViewModel", () => { }); it("renders a request sent by someone else", () => { - jest.mocked(room.getMember).mockReturnValue({ + vi.mocked(room.getMember).mockReturnValue({ name: "Alice", } as RoomMember); @@ -104,7 +105,7 @@ describe("MKeyVerificationRequestViewModel", () => { cli, mxEvent: createEvent("@alice:example.org"), }); - const listener = jest.fn(); + const listener = vi.fn(); vm.subscribe(listener); vm.setEvent(createEvent(myUserId, "@bob:example.org")); @@ -122,7 +123,7 @@ describe("MKeyVerificationRequestViewModel", () => { cli, mxEvent: createEvent("@alice:example.org"), }); - const listener = jest.fn(); + const listener = vi.fn(); vm.subscribe(listener); vm.setTimestamp(timestamp); @@ -136,7 +137,7 @@ describe("MKeyVerificationRequestViewModel", () => { cli, mxEvent: createEvent("@alice:example.org"), }); - const listener = jest.fn(); + const listener = vi.fn(); vm.subscribe(listener); vm.setEvent(createEvent("@alice:example.org")); @@ -151,7 +152,7 @@ describe("MKeyVerificationRequestViewModel", () => { mxEvent: createEvent("@alice:example.org"), timestamp, }); - const listener = jest.fn(); + const listener = vi.fn(); vm.subscribe(listener); vm.setTimestamp(timestamp); diff --git a/apps/web/test/viewmodels/event-tiles/RoomAvatarEventViewModel-test.ts b/apps/web/src/viewmodels/room/timeline/event-tile/RoomAvatarEventViewModel.test.ts similarity index 84% rename from apps/web/test/viewmodels/event-tiles/RoomAvatarEventViewModel-test.ts rename to apps/web/src/viewmodels/room/timeline/event-tile/RoomAvatarEventViewModel.test.ts index 9735a4c0aa..ad4f2f99e1 100644 --- a/apps/web/test/viewmodels/event-tiles/RoomAvatarEventViewModel-test.ts +++ b/apps/web/src/viewmodels/room/timeline/event-tile/RoomAvatarEventViewModel.test.ts @@ -5,30 +5,33 @@ * Please see LICENSE files in the repository root for full details. */ -import { EventType, type MatrixClient, MatrixEvent, type Room } from "matrix-js-sdk/src/matrix"; +// @vitest-environment happy-dom -import Modal from "../../../src/Modal"; -import { RoomAvatarEventViewModel } from "../../../src/viewmodels/room/timeline/event-tile/RoomAvatarEventViewModel"; +import { EventType, type MatrixClient, MatrixEvent, type Room } from "matrix-js-sdk/src/matrix"; +import { vi, describe, it, expect, beforeEach, afterEach, type Mock } from "vitest"; + +import Modal from "../../../../Modal"; +import { RoomAvatarEventViewModel } from "./RoomAvatarEventViewModel"; describe("RoomAvatarEventViewModel", () => { const roomId = "!room:example.org"; let cli: MatrixClient; let room: Room; - let mxcUrlToHttp: jest.Mock; + let mxcUrlToHttp: Mock; beforeEach(() => { - mxcUrlToHttp = jest.fn().mockReturnValue("https://example.org/_matrix/media/v3/download/avatar"); + mxcUrlToHttp = vi.fn().mockReturnValue("https://example.org/_matrix/media/v3/download/avatar"); room = { name: "General", } as unknown as Room; cli = { - getRoom: jest.fn().mockReturnValue(room), + getRoom: vi.fn().mockReturnValue(room), mxcUrlToHttp, } as unknown as MatrixClient; }); afterEach(() => { - jest.restoreAllMocks(); + vi.restoreAllMocks(); }); const createEvent = ( @@ -78,7 +81,7 @@ describe("RoomAvatarEventViewModel", () => { it("updates the snapshot when the event changes", () => { const vm = new RoomAvatarEventViewModel({ cli, mxEvent: createEvent("mxc://example.org/avatar") }); - const listener = jest.fn(); + const listener = vi.fn(); vm.subscribe(listener); vm.setEvent(createEvent("mxc://example.org/next", "@bob:example.org")); @@ -93,7 +96,7 @@ describe("RoomAvatarEventViewModel", () => { it("does not emit when the event-derived snapshot is unchanged", () => { const vm = new RoomAvatarEventViewModel({ cli, mxEvent: createEvent("mxc://example.org/avatar") }); - const listener = jest.fn(); + const listener = vi.fn(); vm.subscribe(listener); vm.setEvent(createEvent("mxc://example.org/avatar")); @@ -102,7 +105,7 @@ describe("RoomAvatarEventViewModel", () => { }); it("opens the room avatar in the lightbox", () => { - const dialogSpy = jest.spyOn(Modal, "createDialog").mockReturnValue({ close: jest.fn() } as any); + const dialogSpy = vi.spyOn(Modal, "createDialog").mockReturnValue({ close: vi.fn() } as any); const vm = new RoomAvatarEventViewModel({ cli, mxEvent: createEvent("mxc://example.org/avatar") }); vm.onAvatarClick(); @@ -128,7 +131,7 @@ describe("RoomAvatarEventViewModel", () => { }); it("does not open the lightbox when the event has no avatar URL", () => { - const dialogSpy = jest.spyOn(Modal, "createDialog").mockReturnValue({ close: jest.fn() } as any); + const dialogSpy = vi.spyOn(Modal, "createDialog").mockReturnValue({ close: vi.fn() } as any); const vm = new RoomAvatarEventViewModel({ cli, mxEvent: createEvent("") }); vm.onAvatarClick(); diff --git a/apps/web/test/viewmodels/event-tiles/TextualEventViewModel-test.ts b/apps/web/src/viewmodels/room/timeline/event-tile/TextualEventViewModel.test.ts similarity index 68% rename from apps/web/test/viewmodels/event-tiles/TextualEventViewModel-test.ts rename to apps/web/src/viewmodels/room/timeline/event-tile/TextualEventViewModel.test.ts index c53dac955a..91f84efa02 100644 --- a/apps/web/test/viewmodels/event-tiles/TextualEventViewModel-test.ts +++ b/apps/web/src/viewmodels/room/timeline/event-tile/TextualEventViewModel.test.ts @@ -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. */ +// @vitest-environment happy-dom + import { MatrixEvent, MatrixEventEvent } from "matrix-js-sdk/src/matrix"; +import { vi, describe, it, expect } from "vitest"; +import { stubClient } from "test-utils"; -import { TextualEventViewModel } from "../../../src/viewmodels/room/timeline/event-tile/TextualEventViewModel"; -import { stubClient } from "../../test-utils"; +import { TextualEventViewModel } from "./TextualEventViewModel"; -jest.mock("../../../src/TextForEvent.tsx", () => ({ - textForEvent: jest.fn().mockReturnValue("Test Message"), +vi.mock("../../../../TextForEvent.tsx", () => ({ + textForEvent: vi.fn().mockReturnValue("Test Message"), })); describe("TextualEventViewModel", () => { @@ -24,7 +27,7 @@ describe("TextualEventViewModel", () => { mxEvent: fakeEvent, }); - const cb = jest.fn(); + const cb = vi.fn(); vm.subscribe(cb); diff --git a/apps/web/test/viewmodels/event-tiles/ThreadSummaryViewModel-test.ts b/apps/web/src/viewmodels/room/timeline/event-tile/ThreadSummaryViewModel.test.ts similarity index 86% rename from apps/web/test/viewmodels/event-tiles/ThreadSummaryViewModel-test.ts rename to apps/web/src/viewmodels/room/timeline/event-tile/ThreadSummaryViewModel.test.ts index 07f51a861b..f6318e026d 100644 --- a/apps/web/test/viewmodels/event-tiles/ThreadSummaryViewModel-test.ts +++ b/apps/web/src/viewmodels/room/timeline/event-tile/ThreadSummaryViewModel.test.ts @@ -5,6 +5,8 @@ * Please see LICENSE files in the repository root for full details. */ +// @vitest-environment happy-dom + import { EventEmitter } from "node:events"; import { type MouseEvent } from "react"; import { @@ -22,40 +24,41 @@ import { ThreadEvent, } from "matrix-js-sdk/src/matrix"; import { logger } from "matrix-js-sdk/src/logger"; -import { waitFor } from "jest-matrix-react"; +import { waitFor } from "test-utils-rtl"; +import { vi, describe, it, expect, beforeEach, afterEach, type Mock } from "vitest"; +import { mkEvent } from "test-utils"; -import { mkEvent } from "../../test-utils"; -import { NotificationLevel } from "../../../src/stores/notifications/NotificationLevel"; -import { TimelineRenderingType } from "../../../src/contexts/RoomContext"; -import { MessagePreviewStore } from "../../../src/stores/message-preview"; -import defaultDispatcher from "../../../src/dispatcher/dispatcher"; -import PosthogTrackers from "../../../src/PosthogTrackers"; -import { determineUnreadState } from "../../../src/RoomNotifs"; +import { NotificationLevel } from "../../../../stores/notifications/NotificationLevel"; +import { TimelineRenderingType } from "../../../../contexts/RoomContext"; +import { MessagePreviewStore } from "../../../../stores/message-preview"; +import defaultDispatcher from "../../../../dispatcher/dispatcher"; +import PosthogTrackers from "../../../../PosthogTrackers"; +import { determineUnreadState } from "../../../../RoomNotifs"; import { ThreadMessagePreviewViewModel, type ThreadMessagePreviewViewModelProps, ThreadSummaryViewModel, type ThreadSummaryViewModelProps, -} from "../../../src/viewmodels/room/timeline/event-tile/ThreadSummaryViewModel"; +} from "./ThreadSummaryViewModel"; -jest.mock("../../../src/dispatcher/dispatcher", () => ({ +vi.mock("../../../../dispatcher/dispatcher", () => ({ __esModule: true, default: { - dispatch: jest.fn(), - register: jest.fn(), - unregister: jest.fn(), + dispatch: vi.fn(), + register: vi.fn(), + unregister: vi.fn(), }, })); -jest.mock("../../../src/PosthogTrackers", () => ({ +vi.mock("../../../../PosthogTrackers", () => ({ __esModule: true, default: { - trackInteraction: jest.fn(), + trackInteraction: vi.fn(), }, })); -jest.mock("../../../src/RoomNotifs", () => ({ - determineUnreadState: jest.fn(() => ({ +vi.mock("../../../../RoomNotifs", () => ({ + determineUnreadState: vi.fn(() => ({ symbol: null, count: 0, level: 0, @@ -65,11 +68,11 @@ jest.mock("../../../src/RoomNotifs", () => ({ const roomId = "!room:example.org"; const userId = "@alice:example.org"; -const clientMxcUrlToHttpMocks = new WeakMap(); +const clientMxcUrlToHttpMocks = new WeakMap(); class TestRoom extends EventEmitter { public roomId = roomId; - public getMember = jest.fn(); + public getMember = vi.fn(); } class TestThread extends EventEmitter { @@ -82,8 +85,8 @@ class TestThread extends EventEmitter { } } -function makeClient(decryptEventIfNeeded = jest.fn().mockResolvedValue(undefined)): MatrixClient { - const mxcUrlToHttp = jest.fn( +function makeClient(decryptEventIfNeeded = vi.fn().mockResolvedValue(undefined)): MatrixClient { + const mxcUrlToHttp = vi.fn( (mxc: string, width?: number, height?: number, resizeMethod?: string) => `https://matrix.example.org/_matrix/media/${mxc}/${width}x${height}/${resizeMethod}`, ); @@ -95,7 +98,7 @@ function makeClient(decryptEventIfNeeded = jest.fn().mockResolvedValue(undefined return cli; } -function getMxcUrlToHttpMock(cli: MatrixClient): jest.Mock { +function getMxcUrlToHttpMock(cli: MatrixClient): Mock { const mock = clientMxcUrlToHttpMocks.get(cli); if (!mock) throw new Error("Missing mxcUrlToHttp mock for test client"); return mock; @@ -108,8 +111,8 @@ function makeMember(name: string, senderUserId = userId, mxcAvatarUrl?: string): name, rawDisplayName: name, roomId, - getAvatarUrl: jest.fn(), - getMxcAvatarUrl: jest.fn(() => mxcAvatarUrl), + getAvatarUrl: vi.fn(), + getMxcAvatarUrl: vi.fn(() => mxcAvatarUrl), } as unknown as RoomMember; } @@ -202,18 +205,18 @@ function makeSummaryVm(overrides: Partial = {}): { describe("ThreadSummaryViewModel", () => { beforeEach(() => { - jest.clearAllMocks(); - jest.mocked(determineUnreadState).mockReturnValue({ + vi.clearAllMocks(); + vi.mocked(determineUnreadState).mockReturnValue({ symbol: null, count: 0, level: NotificationLevel.None, invited: false, }); - jest.spyOn(MessagePreviewStore.instance, "generatePreviewForEvent").mockReturnValue("Latest reply"); + vi.spyOn(MessagePreviewStore.instance, "generatePreviewForEvent").mockReturnValue("Latest reply"); }); afterEach(() => { - jest.restoreAllMocks(); + vi.restoreAllMocks(); }); it("computes initial summary state from the thread", () => { @@ -251,12 +254,12 @@ describe("ThreadSummaryViewModel", () => { it("does not emit when setters receive unchanged values", () => { const { vm, thread, rootEvent, room, cli } = makeSummaryVm(); const previewVm = vm.getSnapshot().previewVm as ThreadMessagePreviewViewModel; - const setClientSpy = jest.spyOn(previewVm, "setClient"); - const setRoomSpy = jest.spyOn(previewVm, "setRoom"); - const setTimelineRenderingTypeSpy = jest.spyOn(previewVm, "setTimelineRenderingType"); - const setLowBandwidthSpy = jest.spyOn(previewVm, "setLowBandwidth"); - const setUseOnlyCurrentProfilesSpy = jest.spyOn(previewVm, "setUseOnlyCurrentProfiles"); - const listener = jest.fn(); + const setClientSpy = vi.spyOn(previewVm, "setClient"); + const setRoomSpy = vi.spyOn(previewVm, "setRoom"); + const setTimelineRenderingTypeSpy = vi.spyOn(previewVm, "setTimelineRenderingType"); + const setLowBandwidthSpy = vi.spyOn(previewVm, "setLowBandwidth"); + const setUseOnlyCurrentProfilesSpy = vi.spyOn(previewVm, "setUseOnlyCurrentProfiles"); + const listener = vi.fn(); vm.subscribe(listener); vm.setRootEvent(rootEvent); @@ -283,11 +286,11 @@ describe("ThreadSummaryViewModel", () => { const nextClient = makeClient(); const nextRoom = new TestRoom() as TestRoom & Room; - const setClientSpy = jest.spyOn(previewVm, "setClient"); - const setRoomSpy = jest.spyOn(previewVm, "setRoom"); - const setTimelineRenderingTypeSpy = jest.spyOn(previewVm, "setTimelineRenderingType"); - const setLowBandwidthSpy = jest.spyOn(previewVm, "setLowBandwidth"); - const setUseOnlyCurrentProfilesSpy = jest.spyOn(previewVm, "setUseOnlyCurrentProfiles"); + const setClientSpy = vi.spyOn(previewVm, "setClient"); + const setRoomSpy = vi.spyOn(previewVm, "setRoom"); + const setTimelineRenderingTypeSpy = vi.spyOn(previewVm, "setTimelineRenderingType"); + const setLowBandwidthSpy = vi.spyOn(previewVm, "setLowBandwidth"); + const setUseOnlyCurrentProfilesSpy = vi.spyOn(previewVm, "setUseOnlyCurrentProfiles"); vm.setClient(nextClient); vm.setRoom(nextRoom); @@ -304,7 +307,7 @@ describe("ThreadSummaryViewModel", () => { it("refreshes notification indicator for thread unread events", () => { const { vm, room, thread } = makeSummaryVm(); - jest.mocked(determineUnreadState).mockReturnValue({ + vi.mocked(determineUnreadState).mockReturnValue({ symbol: null, count: 1, level: NotificationLevel.Highlight, @@ -318,8 +321,8 @@ describe("ThreadSummaryViewModel", () => { it("ignores unread notifications for other threads and refreshes on room notification events", () => { const { vm, room } = makeSummaryVm(); - jest.mocked(determineUnreadState).mockClear(); - jest.mocked(determineUnreadState).mockReturnValue({ + vi.mocked(determineUnreadState).mockClear(); + vi.mocked(determineUnreadState).mockReturnValue({ symbol: null, count: 1, level: NotificationLevel.Notification, @@ -397,20 +400,20 @@ describe("ThreadSummaryViewModel", () => { describe("ThreadMessagePreviewViewModel", () => { beforeEach(() => { - jest.clearAllMocks(); - jest.mocked(determineUnreadState).mockReturnValue({ + vi.clearAllMocks(); + vi.mocked(determineUnreadState).mockReturnValue({ symbol: null, count: 0, level: NotificationLevel.None, invited: false, }); - jest.spyOn(MessagePreviewStore.instance, "generatePreviewForEvent").mockImplementation((event) => { + vi.spyOn(MessagePreviewStore.instance, "generatePreviewForEvent").mockImplementation((event) => { return event.getContent().body; }); }); afterEach(() => { - jest.restoreAllMocks(); + vi.restoreAllMocks(); }); it("hides the preview when the thread has no latest reply", () => { @@ -458,7 +461,7 @@ describe("ThreadMessagePreviewViewModel", () => { it("skips preview recomputation when guarded setters receive unchanged values", async () => { const { vm, thread, room, cli } = makePreviewVm(); await waitFor(() => expect(vm.getSnapshot().isVisible).toBe(true)); - jest.mocked(cli.decryptEventIfNeeded).mockClear(); + vi.mocked(cli.decryptEventIfNeeded).mockClear(); vm.setClient(cli); vm.setThread(thread); @@ -538,12 +541,12 @@ describe("ThreadMessagePreviewViewModel", () => { }); await waitFor(() => expect(vm.getSnapshot().previewContent).toBe("First reply")); - jest.mocked(MessagePreviewStore.instance.generatePreviewForEvent).mockReturnValue("Edited reply"); + vi.mocked(MessagePreviewStore.instance.generatePreviewForEvent).mockReturnValue("Edited reply"); event.emit(MatrixEventEvent.Replaced, event); await waitFor(() => expect(vm.getSnapshot().previewContent).toBe("Edited reply")); - jest.mocked(MessagePreviewStore.instance.generatePreviewForEvent).mockReturnValue("Decrypted reply"); + vi.mocked(MessagePreviewStore.instance.generatePreviewForEvent).mockReturnValue("Decrypted reply"); event.emit(MatrixEventEvent.Decrypted, event); await waitFor(() => expect(vm.getSnapshot().previewContent).toBe("Decrypted reply")); @@ -551,7 +554,7 @@ describe("ThreadMessagePreviewViewModel", () => { it("hides redacted replies and replies without generated previews", async () => { const redactedEvent = makeEvent("Redacted reply"); - jest.spyOn(redactedEvent, "isRedacted").mockReturnValue(true); + vi.spyOn(redactedEvent, "isRedacted").mockReturnValue(true); const redactedVm = makePreviewVm({ thread: Object.assign(new TestThread(new TestRoom() as TestRoom & Room), { replyToEvent: redactedEvent, @@ -560,7 +563,7 @@ describe("ThreadMessagePreviewViewModel", () => { expect(redactedVm.getSnapshot().isVisible).toBe(false); - jest.mocked(MessagePreviewStore.instance.generatePreviewForEvent).mockReturnValue(""); + vi.mocked(MessagePreviewStore.instance.generatePreviewForEvent).mockReturnValue(""); const emptyPreviewVm = makePreviewVm({ thread: Object.assign(new TestThread(new TestRoom() as TestRoom & Room), { replyToEvent: makeEvent("Unsupported reply"), @@ -573,7 +576,7 @@ describe("ThreadMessagePreviewViewModel", () => { it("shows a decryption failure preview without trying to decrypt again", async () => { const decryptionFailureEvent = makeEvent("Encrypted reply"); - jest.spyOn(decryptionFailureEvent, "isDecryptionFailure").mockReturnValue(true); + vi.spyOn(decryptionFailureEvent, "isDecryptionFailure").mockReturnValue(true); const cli = makeClient(); const { vm } = makePreviewVm({ cli, @@ -591,8 +594,8 @@ describe("ThreadMessagePreviewViewModel", () => { it("logs and hides the preview when decryption rejects", async () => { const decryptError = new Error("No key"); - const cli = makeClient(jest.fn().mockRejectedValue(decryptError)); - const loggerSpy = jest.spyOn(logger, "error").mockImplementation(() => {}); + const cli = makeClient(vi.fn().mockRejectedValue(decryptError)); + const loggerSpy = vi.spyOn(logger, "error").mockImplementation(() => {}); const { vm } = makePreviewVm({ cli }); await waitFor(() => @@ -604,10 +607,10 @@ describe("ThreadMessagePreviewViewModel", () => { it("catches fire-and-forget preview update errors", async () => { const previewError = new Error("Preview failed"); - jest.mocked(MessagePreviewStore.instance.generatePreviewForEvent).mockImplementation(() => { + vi.mocked(MessagePreviewStore.instance.generatePreviewForEvent).mockImplementation(() => { throw previewError; }); - const loggerSpy = jest.spyOn(logger, "error").mockImplementation(() => {}); + const loggerSpy = vi.spyOn(logger, "error").mockImplementation(() => {}); makePreviewVm(); @@ -617,14 +620,14 @@ describe("ThreadMessagePreviewViewModel", () => { it("shows a decryption failure preview when decryption rejects into a failure state", async () => { const decryptError = new Error("No key"); const event = makeEvent("Encrypted reply"); - const isDecryptionFailureSpy = jest.spyOn(event, "isDecryptionFailure").mockReturnValue(false); + const isDecryptionFailureSpy = vi.spyOn(event, "isDecryptionFailure").mockReturnValue(false); const cli = makeClient( - jest.fn().mockImplementation(async () => { + vi.fn().mockImplementation(async () => { isDecryptionFailureSpy.mockReturnValue(true); throw decryptError; }), ); - jest.spyOn(logger, "error").mockImplementation(() => {}); + vi.spyOn(logger, "error").mockImplementation(() => {}); const { vm } = makePreviewVm({ cli, thread: Object.assign(new TestThread(new TestRoom() as TestRoom & Room), { @@ -640,9 +643,9 @@ describe("ThreadMessagePreviewViewModel", () => { it("hides the preview when an event is redacted during decryption", async () => { const event = makeEvent("Redacted during decrypt"); - const isRedactedSpy = jest.spyOn(event, "isRedacted").mockReturnValue(false); + const isRedactedSpy = vi.spyOn(event, "isRedacted").mockReturnValue(false); const cli = makeClient( - jest.fn().mockImplementation(async () => { + vi.fn().mockImplementation(async () => { isRedactedSpy.mockReturnValue(true); }), ); @@ -661,9 +664,9 @@ describe("ThreadMessagePreviewViewModel", () => { it("shows a decryption failure preview when an event fails after decryption", async () => { const event = makeEvent("Failure during decrypt"); - const isDecryptionFailureSpy = jest.spyOn(event, "isDecryptionFailure").mockReturnValue(false); + const isDecryptionFailureSpy = vi.spyOn(event, "isDecryptionFailure").mockReturnValue(false); const cli = makeClient( - jest.fn().mockImplementation(async () => { + vi.fn().mockImplementation(async () => { isDecryptionFailureSpy.mockReturnValue(true); }), ); @@ -685,7 +688,7 @@ describe("ThreadMessagePreviewViewModel", () => { const firstDecrypt = new Promise((resolve) => { resolveFirstDecrypt = resolve; }); - const cli = makeClient(jest.fn().mockReturnValueOnce(firstDecrypt).mockResolvedValue(undefined)); + const cli = makeClient(vi.fn().mockReturnValueOnce(firstDecrypt).mockResolvedValue(undefined)); const room = new TestRoom() as TestRoom & Room; const thread = new TestThread(room) as TestThread & Thread; thread.replyToEvent = makeEvent("First reply"); @@ -716,8 +719,8 @@ describe("ThreadMessagePreviewViewModel", () => { const firstDecrypt = new Promise((_resolve, reject) => { rejectFirstDecrypt = reject; }); - const cli = makeClient(jest.fn().mockReturnValueOnce(firstDecrypt).mockResolvedValue(undefined)); - const loggerSpy = jest.spyOn(logger, "error").mockImplementation(() => {}); + const cli = makeClient(vi.fn().mockReturnValueOnce(firstDecrypt).mockResolvedValue(undefined)); + const loggerSpy = vi.spyOn(logger, "error").mockImplementation(() => {}); const room = new TestRoom() as TestRoom & Room; const thread = new TestThread(room) as TestThread & Thread; thread.replyToEvent = makeEvent("First reply"); @@ -868,7 +871,7 @@ describe("ThreadMessagePreviewViewModel", () => { it("falls back to the sender id when event sender profile data is missing", async () => { const mxEvent = makeEvent("Missing sender profile"); mxEvent.sender = null; - jest.spyOn(mxEvent, "getSender").mockReturnValue("@fallback:example.org"); + vi.spyOn(mxEvent, "getSender").mockReturnValue("@fallback:example.org"); const { vm } = makePreviewVm({ thread: Object.assign(new TestThread(new TestRoom() as TestRoom & Room), { replyToEvent: mxEvent, diff --git a/apps/web/test/viewmodels/message-body/DecryptionFailureBodyViewModel-test.ts b/apps/web/src/viewmodels/room/timeline/event-tile/body/DecryptionFailureBodyViewModel.test.ts similarity index 96% rename from apps/web/test/viewmodels/message-body/DecryptionFailureBodyViewModel-test.ts rename to apps/web/src/viewmodels/room/timeline/event-tile/body/DecryptionFailureBodyViewModel.test.ts index 3597e25fb1..432f68c8b6 100644 --- a/apps/web/test/viewmodels/message-body/DecryptionFailureBodyViewModel-test.ts +++ b/apps/web/src/viewmodels/room/timeline/event-tile/body/DecryptionFailureBodyViewModel.test.ts @@ -7,8 +7,9 @@ import { DecryptionFailureCode } from "matrix-js-sdk/src/crypto-api"; import { DecryptionFailureReason } from "@element-hq/web-shared-components"; +import { describe, it, expect } from "vitest"; -import { DecryptionFailureBodyViewModel } from "../../../src/viewmodels/room/timeline/event-tile/body/DecryptionFailureBodyViewModel"; +import { DecryptionFailureBodyViewModel } from "./DecryptionFailureBodyViewModel"; describe("DecryptionFailureBodyViewModel", () => { it("should return the snapshot", () => { diff --git a/apps/web/test/viewmodels/message-body/HiddenBodyViewModel-test.ts b/apps/web/src/viewmodels/room/timeline/event-tile/body/HiddenBodyViewModel.test.ts similarity index 89% rename from apps/web/test/viewmodels/message-body/HiddenBodyViewModel-test.ts rename to apps/web/src/viewmodels/room/timeline/event-tile/body/HiddenBodyViewModel.test.ts index e8d961f6ec..db1f9bced7 100644 --- a/apps/web/test/viewmodels/message-body/HiddenBodyViewModel-test.ts +++ b/apps/web/src/viewmodels/room/timeline/event-tile/body/HiddenBodyViewModel.test.ts @@ -6,13 +6,14 @@ */ import { type MatrixEvent } from "matrix-js-sdk/src/matrix"; +import { vi, describe, it, expect } from "vitest"; -import { HiddenBodyViewModel } from "../../../src/viewmodels/room/timeline/event-tile/body/HiddenBodyViewModel"; +import { HiddenBodyViewModel } from "./HiddenBodyViewModel"; describe("HiddenBodyViewModel", () => { const createEvent = (visible: boolean, reason?: string | null): MatrixEvent => ({ - messageVisibility: jest.fn().mockReturnValue({ + messageVisibility: vi.fn().mockReturnValue({ visible, reason, }), @@ -53,7 +54,7 @@ describe("HiddenBodyViewModel", () => { it("does not emit when setEvent receives the current event", () => { const event = createEvent(false, "spam"); const vm = new HiddenBodyViewModel({ mxEvent: event }); - const listener = jest.fn(); + const listener = vi.fn(); vm.subscribe(listener); vm.setEvent(event); diff --git a/apps/web/test/viewmodels/message-body/MjolnirBodyViewModel-test.ts b/apps/web/src/viewmodels/room/timeline/event-tile/body/MjolnirBodyViewModel.test.ts similarity index 74% rename from apps/web/test/viewmodels/message-body/MjolnirBodyViewModel-test.ts rename to apps/web/src/viewmodels/room/timeline/event-tile/body/MjolnirBodyViewModel.test.ts index 5d22deb4d4..3ce8efa4eb 100644 --- a/apps/web/test/viewmodels/message-body/MjolnirBodyViewModel-test.ts +++ b/apps/web/src/viewmodels/room/timeline/event-tile/body/MjolnirBodyViewModel.test.ts @@ -5,17 +5,19 @@ * Please see LICENSE files in the repository root for full details. */ -import { MjolnirBodyViewModel } from "../../../src/viewmodels/room/timeline/event-tile/body/MjolnirBodyViewModel"; +import { vi, describe, it, expect } from "vitest"; + +import { MjolnirBodyViewModel } from "./MjolnirBodyViewModel"; describe("MjolnirBodyViewModel", () => { it("has an empty snapshot", () => { - const vm = new MjolnirBodyViewModel({ onAllow: jest.fn() }); + const vm = new MjolnirBodyViewModel({ onAllow: vi.fn() }); expect(vm.getSnapshot()).toEqual({}); }); it("forwards the allow action", () => { - const onAllow = jest.fn(); + const onAllow = vi.fn(); const vm = new MjolnirBodyViewModel({ onAllow }); vm.onAllow(); @@ -24,8 +26,8 @@ describe("MjolnirBodyViewModel", () => { }); it("uses the updated action", () => { - const oldAction = jest.fn(); - const newAction = jest.fn(); + const oldAction = vi.fn(); + const newAction = vi.fn(); const vm = new MjolnirBodyViewModel({ onAllow: oldAction }); vm.setProps({ onAllow: newAction }); @@ -36,8 +38,8 @@ describe("MjolnirBodyViewModel", () => { }); it("does not emit snapshot updates for unchanged action inputs", () => { - const props = { onAllow: jest.fn() }; - const listener = jest.fn(); + const props = { onAllow: vi.fn() }; + const listener = vi.fn(); const vm = new MjolnirBodyViewModel(props); vm.subscribe(listener); diff --git a/apps/web/test/viewmodels/message-body/TextualBodyViewModel-test.ts b/apps/web/src/viewmodels/room/timeline/event-tile/body/TextualBodyViewModel.test.ts similarity index 78% rename from apps/web/test/viewmodels/message-body/TextualBodyViewModel-test.ts rename to apps/web/src/viewmodels/room/timeline/event-tile/body/TextualBodyViewModel.test.ts index 7de8d414bd..20bcc7110b 100644 --- a/apps/web/test/viewmodels/message-body/TextualBodyViewModel-test.ts +++ b/apps/web/src/viewmodels/room/timeline/event-tile/body/TextualBodyViewModel.test.ts @@ -5,23 +5,26 @@ * Please see LICENSE files in the repository root for full details. */ +// @vitest-environment happy-dom + import { LINKIFIED_DATA_ATTRIBUTE, TextualBodyViewBodyWrapperKind, TextualBodyViewKind, } from "@element-hq/web-shared-components"; import { MsgType, type MatrixEvent } from "matrix-js-sdk/src/matrix"; +import { vi, describe, it, expect, afterEach } from "vitest"; +import { flushPromises, mkEvent } from "test-utils"; -import { flushPromises, mkEvent } from "../../test-utils"; -import { TimelineRenderingType } from "../../../src/contexts/RoomContext"; -import { TextualBodyViewModel } from "../../../src/viewmodels/room/timeline/event-tile/body/TextualBodyViewModel"; -import Modal from "../../../src/Modal"; -import dispatcher from "../../../src/dispatcher/dispatcher"; -import { Action } from "../../../src/dispatcher/actions"; -import { IntegrationManagers } from "../../../src/integrations/IntegrationManagers"; -import * as permalinkUtils from "../../../src/utils/permalinks/Permalinks"; -import QuestionDialog from "../../../src/components/views/dialogs/QuestionDialog"; -import MessageEditHistoryDialog from "../../../src/components/views/dialogs/MessageEditHistoryDialog"; +import { TimelineRenderingType } from "../../../../../contexts/RoomContext"; +import { TextualBodyViewModel } from "./TextualBodyViewModel"; +import Modal from "../../../../../Modal"; +import dispatcher from "../../../../../dispatcher/dispatcher"; +import { Action } from "../../../../../dispatcher/actions"; +import { IntegrationManagers } from "../../../../../integrations/IntegrationManagers"; +import * as permalinkUtils from "../../../../../utils/permalinks/Permalinks"; +import QuestionDialog from "../../../../../components/views/dialogs/QuestionDialog"; +import MessageEditHistoryDialog from "../../../../../components/views/dialogs/MessageEditHistoryDialog"; describe("TextualBodyViewModel", () => { const createEvent = ( @@ -49,7 +52,7 @@ describe("TextualBodyViewModel", () => { }); afterEach(() => { - jest.restoreAllMocks(); + vi.restoreAllMocks(); window.location.hash = ""; }); @@ -58,8 +61,8 @@ describe("TextualBodyViewModel", () => { body: "Caption", msgtype: MsgType.Image, }); - jest.spyOn(event, "replacingEventDate").mockReturnValue(new Date(1993, 7, 3)); - jest.spyOn(event, "messageVisibility").mockReturnValue({ + vi.spyOn(event, "replacingEventDate").mockReturnValue(new Date(1993, 7, 3)); + vi.spyOn(event, "messageVisibility").mockReturnValue({ visible: false, reason: "copyright", } as ReturnType); @@ -144,7 +147,7 @@ describe("TextualBodyViewModel", () => { body: "hidden", msgtype: MsgType.Text, }); - jest.spyOn(hiddenEvent, "messageVisibility").mockReturnValue({ + vi.spyOn(hiddenEvent, "messageVisibility").mockReturnValue({ visible: false, reason: "spam", } as ReturnType); @@ -162,7 +165,7 @@ describe("TextualBodyViewModel", () => { body: "edited", msgtype: MsgType.Text, }); - jest.spyOn(event, "replacingEventDate").mockReturnValue(new Date(1993, 7, 3)); + vi.spyOn(event, "replacingEventDate").mockReturnValue(new Date(1993, 7, 3)); const vm = createVm({ mxEvent: event }); vm.setId("updated-id"); @@ -183,7 +186,7 @@ describe("TextualBodyViewModel", () => { body: "hidden", msgtype: MsgType.Text, }); - jest.spyOn(hiddenEvent, "messageVisibility").mockReturnValue({ + vi.spyOn(hiddenEvent, "messageVisibility").mockReturnValue({ visible: false, reason: null, } as ReturnType); @@ -201,7 +204,7 @@ describe("TextualBodyViewModel", () => { body: "visible", msgtype: MsgType.Text, }); - jest.spyOn(visibleEvent, "messageVisibility").mockReturnValue({ + vi.spyOn(visibleEvent, "messageVisibility").mockReturnValue({ visible: true, } as ReturnType); @@ -215,8 +218,8 @@ describe("TextualBodyViewModel", () => { it("rewrites linkified permalink clicks to local hashes", () => { const vm = createVm(); - const preventDefault = jest.fn(); - jest.spyOn(permalinkUtils, "tryTransformPermalinkToLocalHref").mockReturnValue("#/room/#room:example.org"); + const preventDefault = vi.fn(); + vi.spyOn(permalinkUtils, "tryTransformPermalinkToLocalHref").mockReturnValue("#/room/#room:example.org"); vm.onRootClick({ preventDefault, @@ -235,7 +238,7 @@ describe("TextualBodyViewModel", () => { it("leaves linkified ordinary links alone", () => { const vm = createVm(); - const preventDefault = jest.fn(); + const preventDefault = vi.fn(); vm.onRootClick({ preventDefault, @@ -254,15 +257,15 @@ describe("TextualBodyViewModel", () => { it("rewrites permalink clicks to local hashes", () => { const vm = createVm(); - const preventDefault = jest.fn(); + const preventDefault = vi.fn(); const anchor = { href: "https://element.example/#/room/!room:example.org", nodeName: "A" }; - jest.spyOn(permalinkUtils, "tryTransformPermalinkToLocalHref").mockReturnValue("#/room/!room:example.org"); + vi.spyOn(permalinkUtils, "tryTransformPermalinkToLocalHref").mockReturnValue("#/room/!room:example.org"); vm.onRootClick({ preventDefault, target: { nodeName: "SPAN", - closest: jest.fn().mockReturnValue(anchor), + closest: vi.fn().mockReturnValue(anchor), }, } as any); @@ -272,9 +275,9 @@ describe("TextualBodyViewModel", () => { it("leaves external root clicks alone when no local permalink is found", () => { const vm = createVm(); - const preventDefault = jest.fn(); + const preventDefault = vi.fn(); const href = "https://example.org"; - jest.spyOn(permalinkUtils, "tryTransformPermalinkToLocalHref").mockReturnValue(href); + vi.spyOn(permalinkUtils, "tryTransformPermalinkToLocalHref").mockReturnValue(href); vm.onRootClick({ preventDefault, @@ -290,8 +293,8 @@ describe("TextualBodyViewModel", () => { it("does nothing for body actions without a starter link", () => { const vm = createVm(); - const preventDefault = jest.fn(); - const hasManagerSpy = jest.spyOn(IntegrationManagers.sharedInstance(), "hasManager"); + const preventDefault = vi.fn(); + const hasManagerSpy = vi.spyOn(IntegrationManagers.sharedInstance(), "hasManager"); vm.onBodyActionClick({ preventDefault } as any); @@ -309,10 +312,10 @@ describe("TextualBodyViewModel", () => { }, }), }); - const preventDefault = jest.fn(); + const preventDefault = vi.fn(); const managers = IntegrationManagers.sharedInstance(); - jest.spyOn(managers, "hasManager").mockReturnValue(false); - const openNoManagerDialogSpy = jest.spyOn(managers, "openNoManagerDialog").mockImplementation(() => {}); + vi.spyOn(managers, "hasManager").mockReturnValue(false); + const openNoManagerDialogSpy = vi.spyOn(managers, "openNoManagerDialog").mockImplementation(() => {}); vm.onBodyActionClick({ preventDefault } as any); @@ -330,24 +333,24 @@ describe("TextualBodyViewModel", () => { }, }), }); - const preventDefault = jest.fn(); + const preventDefault = vi.fn(); const managers = IntegrationManagers.sharedInstance(); - const connect = jest.fn().mockResolvedValue(undefined); - const getStarterLink = jest.fn().mockReturnValue("https://scalar.example/complete"); + const connect = vi.fn().mockResolvedValue(undefined); + const getStarterLink = vi.fn().mockReturnValue("https://scalar.example/complete"); const scalarClient = { connect, getStarterLink }; const integrationManager = { - getScalarClient: jest.fn().mockReturnValue(scalarClient), + getScalarClient: vi.fn().mockReturnValue(scalarClient), uiUrl: "https://scalar.example/ui", }; const popup = { opener: "initial" }; - jest.spyOn(managers, "hasManager").mockReturnValue(true); - jest.spyOn(managers, "getPrimaryManager").mockReturnValue(integrationManager as any); - jest.spyOn(Modal, "createDialog").mockReturnValue({ - close: jest.fn(), + vi.spyOn(managers, "hasManager").mockReturnValue(true); + vi.spyOn(managers, "getPrimaryManager").mockReturnValue(integrationManager as any); + vi.spyOn(Modal, "createDialog").mockReturnValue({ + close: vi.fn(), finished: Promise.resolve([true]), } as any); - const openSpy = jest.spyOn(window, "open").mockImplementation(() => popup as any); + const openSpy = vi.spyOn(window, "open").mockImplementation(() => popup as any); vm.onBodyActionClick({ preventDefault } as any); await flushPromises(); @@ -380,22 +383,22 @@ describe("TextualBodyViewModel", () => { }); const managers = IntegrationManagers.sharedInstance(); const scalarClient = { - connect: jest.fn().mockResolvedValue(undefined), - getStarterLink: jest.fn().mockReturnValue("https://scalar.example/complete"), + connect: vi.fn().mockResolvedValue(undefined), + getStarterLink: vi.fn().mockReturnValue("https://scalar.example/complete"), }; - jest.spyOn(managers, "hasManager").mockReturnValue(true); - jest.spyOn(managers, "getPrimaryManager").mockReturnValue({ - getScalarClient: jest.fn().mockReturnValue(scalarClient), + vi.spyOn(managers, "hasManager").mockReturnValue(true); + vi.spyOn(managers, "getPrimaryManager").mockReturnValue({ + getScalarClient: vi.fn().mockReturnValue(scalarClient), uiUrl: "https://scalar.example/ui", } as any); - jest.spyOn(Modal, "createDialog").mockReturnValue({ - close: jest.fn(), + vi.spyOn(Modal, "createDialog").mockReturnValue({ + close: vi.fn(), finished: Promise.resolve([false]), } as any); - const openSpy = jest.spyOn(window, "open").mockImplementation(() => ({ opener: "initial" }) as any); + const openSpy = vi.spyOn(window, "open").mockImplementation(() => ({ opener: "initial" }) as any); - vm.onBodyActionClick({ preventDefault: jest.fn() } as any); + vm.onBodyActionClick({ preventDefault: vi.fn() } as any); await flushPromises(); expect(openSpy).not.toHaveBeenCalled(); @@ -407,9 +410,7 @@ describe("TextualBodyViewModel", () => { msgtype: MsgType.Text, }); const vm = createVm({ mxEvent: event }); - const createDialogSpy = jest - .spyOn(Modal, "createDialog") - .mockImplementation(() => ({ close: jest.fn() }) as any); + const createDialogSpy = vi.spyOn(Modal, "createDialog").mockImplementation(() => ({ close: vi.fn() }) as any); vm.onEditedMarkerClick(); @@ -422,7 +423,7 @@ describe("TextualBodyViewModel", () => { msgtype: MsgType.Emote, }); const vm = createVm({ mxEvent: event }); - const dispatchSpy = jest.spyOn(dispatcher, "dispatch").mockImplementation(() => {}); + const dispatchSpy = vi.spyOn(dispatcher, "dispatch").mockImplementation(() => {}); vm.setTimelineRenderingType(TimelineRenderingType.Thread); vm.onEmoteSenderClick(); @@ -440,7 +441,7 @@ describe("TextualBodyViewModel", () => { msgtype: MsgType.Text, }); const vm = createVm({ mxEvent }); - const listener = jest.fn(); + const listener = vi.fn(); vm.subscribe(listener); vm.setId(undefined); diff --git a/apps/web/test/viewmodels/message-body/ViewSourceEventViewModel-test.ts b/apps/web/src/viewmodels/room/timeline/event-tile/body/ViewSourceEventViewModel.test.ts similarity index 87% rename from apps/web/test/viewmodels/message-body/ViewSourceEventViewModel-test.ts rename to apps/web/src/viewmodels/room/timeline/event-tile/body/ViewSourceEventViewModel.test.ts index 6b0ee8e6f6..e76f9fd07b 100644 --- a/apps/web/test/viewmodels/message-body/ViewSourceEventViewModel-test.ts +++ b/apps/web/src/viewmodels/room/timeline/event-tile/body/ViewSourceEventViewModel.test.ts @@ -9,13 +9,14 @@ Please see LICENSE files in the repository root for full details. import { type MouseEvent } from "react"; import { type MatrixClient, MatrixEvent, MatrixEventEvent } from "matrix-js-sdk/src/matrix"; +import { vi, describe, it, expect } from "vitest"; -import { ViewSourceEventViewModel } from "../../../src/viewmodels/room/timeline/event-tile/body/ViewSourceEventViewModel"; +import { ViewSourceEventViewModel } from "./ViewSourceEventViewModel"; describe("ViewSourceEventViewModel", () => { const createClient = (): MatrixClient => ({ - decryptEventIfNeeded: jest.fn().mockResolvedValue(undefined), + decryptEventIfNeeded: vi.fn().mockResolvedValue(undefined), }) as unknown as MatrixClient; const createEvent = (type = "m.room.message", content: Record = {}): MatrixEvent => @@ -28,7 +29,7 @@ describe("ViewSourceEventViewModel", () => { const createClickEvent = (): MouseEvent => ({ - preventDefault: jest.fn(), + preventDefault: vi.fn(), }) as unknown as MouseEvent; it("creates a collapsed event source snapshot and requests decryption", () => { @@ -80,8 +81,8 @@ describe("ViewSourceEventViewModel", () => { it("removes the previous decryption listener when the event changes", () => { const oldEvent = createEvent("m.room.encrypted"); - jest.spyOn(oldEvent, "isBeingDecrypted").mockReturnValue(true); - const offSpy = jest.spyOn(oldEvent, "off"); + vi.spyOn(oldEvent, "isBeingDecrypted").mockReturnValue(true); + const offSpy = vi.spyOn(oldEvent, "off"); const vm = new ViewSourceEventViewModel({ cli: createClient(), mxEvent: oldEvent }); vm.setProps({ mxEvent: createEvent("m.room.message") }); @@ -94,7 +95,7 @@ describe("ViewSourceEventViewModel", () => { const newClient = createClient(); const mxEvent = createEvent(); const vm = new ViewSourceEventViewModel({ cli: oldClient, mxEvent }); - const listener = jest.fn(); + const listener = vi.fn(); vm.subscribe(listener); vm.setProps({ cli: newClient }); @@ -107,7 +108,7 @@ describe("ViewSourceEventViewModel", () => { const cli = createClient(); const mxEvent = createEvent(); const vm = new ViewSourceEventViewModel({ cli, mxEvent }); - const listener = jest.fn(); + const listener = vi.fn(); vm.subscribe(listener); vm.setProps({ cli, mxEvent }); @@ -117,10 +118,10 @@ describe("ViewSourceEventViewModel", () => { it("updates the source after decryption completes", () => { const mxEvent = createEvent("m.room.encrypted", { ciphertext: "encrypted" }); - jest.spyOn(mxEvent, "isBeingDecrypted").mockReturnValue(true); + vi.spyOn(mxEvent, "isBeingDecrypted").mockReturnValue(true); const vm = new ViewSourceEventViewModel({ cli: createClient(), mxEvent }); vm.onToggle(createClickEvent()); - const listener = jest.fn(); + const listener = vi.fn(); vm.subscribe(listener); mxEvent.getContent().body = "decrypted"; @@ -132,8 +133,8 @@ describe("ViewSourceEventViewModel", () => { it("removes decryption listeners on dispose", () => { const mxEvent = createEvent("m.room.encrypted"); - jest.spyOn(mxEvent, "isBeingDecrypted").mockReturnValue(true); - const offSpy = jest.spyOn(mxEvent, "off"); + vi.spyOn(mxEvent, "isBeingDecrypted").mockReturnValue(true); + const offSpy = vi.spyOn(mxEvent, "off"); const vm = new ViewSourceEventViewModel({ cli: createClient(), mxEvent }); vm.dispose(); diff --git a/apps/web/test/viewmodels/event-tiles/EventTileReactionState-test.ts b/apps/web/src/viewmodels/room/timeline/event-tile/reactions/EventTileReactionState.test.ts similarity index 85% rename from apps/web/test/viewmodels/event-tiles/EventTileReactionState-test.ts rename to apps/web/src/viewmodels/room/timeline/event-tile/reactions/EventTileReactionState.test.ts index 559c5597d5..2fa4afdcf6 100644 --- a/apps/web/test/viewmodels/event-tiles/EventTileReactionState-test.ts +++ b/apps/web/src/viewmodels/room/timeline/event-tile/reactions/EventTileReactionState.test.ts @@ -5,16 +5,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. */ -import { EventType, type MatrixEvent, type Relations, MsgType, RelationType } from "matrix-js-sdk/src/matrix"; +// @vitest-environment happy-dom + +import { EventType, type MatrixEvent, type Relations, MsgType, RelationType } from "matrix-js-sdk/src/matrix"; +import { vi, describe, it, expect, type MockedFunction } from "vitest"; +import { mkEvent } from "test-utils"; -import { mkEvent } from "../../test-utils"; import { EVENT_TILE_REACTION_EVENT_TYPE, EVENT_TILE_REACTION_RELATION_TYPE, getEventTileReactionRelations, isEventTileReactionRelation, type GetRelationsForEvent, -} from "../../../src/viewmodels/room/timeline/event-tile/reactions/EventTileReactionState"; +} from "./EventTileReactionState"; const roomId = "!room:example.org"; const userId = "@alice:example.org"; @@ -36,7 +39,7 @@ function makeEvent(): MatrixEvent { describe("EventTileReactionState", () => { it("gets annotation reaction relations when reactions are enabled", () => { const relations = {} as Relations; - const getRelationsForEvent: jest.MockedFunction = jest.fn().mockReturnValue(relations); + const getRelationsForEvent: MockedFunction = vi.fn().mockReturnValue(relations); expect( getEventTileReactionRelations({ @@ -53,7 +56,7 @@ describe("EventTileReactionState", () => { }); it("does not get relations when reactions are disabled", () => { - const getRelationsForEvent: jest.MockedFunction = jest.fn(); + const getRelationsForEvent: MockedFunction = vi.fn(); expect( getEventTileReactionRelations({ @@ -75,7 +78,7 @@ describe("EventTileReactionState", () => { }); it("normalizes missing relations to null", () => { - const getRelationsForEvent: jest.MockedFunction = jest.fn().mockReturnValue(undefined); + const getRelationsForEvent: MockedFunction = vi.fn().mockReturnValue(undefined); expect( getEventTileReactionRelations({ diff --git a/apps/web/test/viewmodels/message-body/ReactionsRowButtonTooltipViewModel-test.ts b/apps/web/src/viewmodels/room/timeline/event-tile/reactions/ReactionsRowButtonTooltipViewModel.test.ts similarity index 82% rename from apps/web/test/viewmodels/message-body/ReactionsRowButtonTooltipViewModel-test.ts rename to apps/web/src/viewmodels/room/timeline/event-tile/reactions/ReactionsRowButtonTooltipViewModel.test.ts index 129c4a40fe..c232e61ad3 100644 --- a/apps/web/test/viewmodels/message-body/ReactionsRowButtonTooltipViewModel-test.ts +++ b/apps/web/src/viewmodels/room/timeline/event-tile/reactions/ReactionsRowButtonTooltipViewModel.test.ts @@ -5,21 +5,24 @@ * Please see LICENSE files in the repository root for full details. */ +// @vitest-environment happy-dom + import { type MatrixClient, type MatrixEvent, type Room, type RoomMember } from "matrix-js-sdk/src/matrix"; +import { vi, describe, it, expect, beforeEach, afterEach } from "vitest"; +import { stubClient, mkStubRoom, mkEvent } from "test-utils"; import { ReactionsRowButtonTooltipViewModel, type ReactionsRowButtonTooltipViewModelProps, -} from "../../../src/viewmodels/room/timeline/event-tile/reactions/ReactionsRowButtonTooltipViewModel"; -import { stubClient, mkStubRoom, mkEvent } from "../../test-utils"; -import { unicodeToShortcode } from "../../../src/HtmlUtils"; +} from "./ReactionsRowButtonTooltipViewModel"; +import { unicodeToShortcode } from "../../../../../HtmlUtils"; -jest.mock("../../../src/HtmlUtils", () => ({ - ...jest.requireActual("../../../src/HtmlUtils"), - unicodeToShortcode: jest.fn(), +vi.mock("../../../../../HtmlUtils", async () => ({ + ...(await vi.importActual("../../../../../HtmlUtils")), + unicodeToShortcode: vi.fn(), })); -const mockedUnicodeToShortcode = jest.mocked(unicodeToShortcode); +const mockedUnicodeToShortcode = vi.mocked(unicodeToShortcode); describe("ReactionsRowButtonTooltipViewModel", () => { let client: MatrixClient; @@ -53,7 +56,7 @@ describe("ReactionsRowButtonTooltipViewModel", () => { beforeEach(() => { client = stubClient(); room = mkStubRoom("!room:example.org", "Test Room", client); - jest.spyOn(client, "getRoom").mockReturnValue(room); + vi.spyOn(client, "getRoom").mockReturnValue(room); mxEvent = mkEvent({ event: true, @@ -70,12 +73,12 @@ describe("ReactionsRowButtonTooltipViewModel", () => { }); afterEach(() => { - jest.restoreAllMocks(); + vi.restoreAllMocks(); mockedUnicodeToShortcode.mockReset(); }); it("should return undefined snapshot when room is not found", () => { - jest.spyOn(client, "getRoom").mockReturnValue(null); + vi.spyOn(client, "getRoom").mockReturnValue(null); const vm = new ReactionsRowButtonTooltipViewModel(createProps()); const snapshot = vm.getSnapshot(); @@ -94,7 +97,7 @@ describe("ReactionsRowButtonTooltipViewModel", () => { it("should compute formattedSenders and caption from reaction events", () => { const reactionEvent = createReactionEvent("@alice:example.org"); - jest.spyOn(room, "getMember").mockReturnValue({ name: "Alice", userId: "@alice:example.org" } as RoomMember); + vi.spyOn(room, "getMember").mockReturnValue({ name: "Alice", userId: "@alice:example.org" } as RoomMember); const vm = new ReactionsRowButtonTooltipViewModel(createProps({ reactionEvents: [reactionEvent] })); const snapshot = vm.getSnapshot(); @@ -105,7 +108,7 @@ describe("ReactionsRowButtonTooltipViewModel", () => { it("should fall back to sender ID when member is not found", () => { const reactionEvent = createReactionEvent("@unknown:example.org"); - jest.spyOn(room, "getMember").mockReturnValue(null); + vi.spyOn(room, "getMember").mockReturnValue(null); const vm = new ReactionsRowButtonTooltipViewModel(createProps({ reactionEvents: [reactionEvent] })); @@ -117,7 +120,7 @@ describe("ReactionsRowButtonTooltipViewModel", () => { const reactionEvent = createReactionEvent("@alice:example.org", { "com.beeper.reaction.shortcode": "custom_emoji", }); - jest.spyOn(room, "getMember").mockReturnValue({ name: "Alice", userId: "@alice:example.org" } as RoomMember); + vi.spyOn(room, "getMember").mockReturnValue({ name: "Alice", userId: "@alice:example.org" } as RoomMember); const vm = new ReactionsRowButtonTooltipViewModel( createProps({ @@ -135,7 +138,7 @@ describe("ReactionsRowButtonTooltipViewModel", () => { const reactionEvent = createReactionEvent("@alice:example.org", { "com.beeper.reaction.shortcode": "custom_emoji", }); - jest.spyOn(room, "getMember").mockReturnValue({ name: "Alice", userId: "@alice:example.org" } as RoomMember); + vi.spyOn(room, "getMember").mockReturnValue({ name: "Alice", userId: "@alice:example.org" } as RoomMember); const vm = new ReactionsRowButtonTooltipViewModel( createProps({ @@ -152,7 +155,7 @@ describe("ReactionsRowButtonTooltipViewModel", () => { const aliceReaction = createReactionEvent("@alice:example.org"); const bobReaction = createReactionEvent("@bob:example.org"); - jest.spyOn(room, "getMember").mockImplementation((userId) => { + vi.spyOn(room, "getMember").mockImplementation((userId) => { const names: Record = { "@alice:example.org": "Alice", "@bob:example.org": "Bob" }; return names[userId!] ? ({ name: names[userId!], userId } as RoomMember) : null; }); @@ -160,7 +163,7 @@ describe("ReactionsRowButtonTooltipViewModel", () => { const vm = new ReactionsRowButtonTooltipViewModel(createProps({ reactionEvents: [aliceReaction] })); expect(vm.getSnapshot().formattedSenders).toBe("Alice"); - const subscriber = jest.fn(); + const subscriber = vi.fn(); vm.subscribe(subscriber); vm.setProps({ reactionEvents: [aliceReaction, bobReaction] }); diff --git a/apps/web/test/viewmodels/message-body/ReactionsRowButtonViewModel-test.ts b/apps/web/src/viewmodels/room/timeline/event-tile/reactions/ReactionsRowButtonViewModel.test.ts similarity index 84% rename from apps/web/test/viewmodels/message-body/ReactionsRowButtonViewModel-test.ts rename to apps/web/src/viewmodels/room/timeline/event-tile/reactions/ReactionsRowButtonViewModel.test.ts index e12b97d43e..eebae8a236 100644 --- a/apps/web/test/viewmodels/message-body/ReactionsRowButtonViewModel-test.ts +++ b/apps/web/src/viewmodels/room/timeline/event-tile/reactions/ReactionsRowButtonViewModel.test.ts @@ -5,19 +5,19 @@ * Please see LICENSE files in the repository root for full details. */ +// @vitest-environment happy-dom + import { EventType, type MatrixClient, type MatrixEvent, RelationType, type Room } from "matrix-js-sdk/src/matrix"; +import { vi, describe, it, expect, beforeEach } from "vitest"; +import { createTestClient, mkEvent, mkStubRoom } from "test-utils"; -import { - ReactionsRowButtonViewModel, - type ReactionsRowButtonViewModelProps, -} from "../../../src/viewmodels/room/timeline/event-tile/reactions/ReactionsRowButtonViewModel"; -import { type ReactionsRowButtonTooltipViewModel } from "../../../src/viewmodels/room/timeline/event-tile/reactions/ReactionsRowButtonTooltipViewModel"; -import { createTestClient, mkEvent, mkStubRoom } from "../../test-utils"; -import dis from "../../../src/dispatcher/dispatcher"; +import { ReactionsRowButtonViewModel, type ReactionsRowButtonViewModelProps } from "./ReactionsRowButtonViewModel"; +import { type ReactionsRowButtonTooltipViewModel } from "./ReactionsRowButtonTooltipViewModel"; +import dis from "../../../../../dispatcher/dispatcher"; -jest.mock("../../../src/dispatcher/dispatcher"); -jest.mock("../../../src/customisations/Media", () => ({ - mediaFromMxc: jest.fn(() => ({ srcHttp: "https://example.org/_matrix/media/reaction.png" })), +vi.mock("../../../../../dispatcher/dispatcher"); +vi.mock("../../../../../customisations/Media", () => ({ + mediaFromMxc: vi.fn(() => ({ srcHttp: "https://example.org/_matrix/media/reaction.png" })), })); describe("ReactionsRowButtonViewModel", () => { @@ -58,10 +58,10 @@ describe("ReactionsRowButtonViewModel", () => { (vm.getSnapshot() as { ariaLabel?: string }).ariaLabel; beforeEach(() => { - jest.clearAllMocks(); + vi.clearAllMocks(); client = createTestClient(); room = mkStubRoom("!room:example.org", "Test Room", client); - jest.spyOn(client, "getRoom").mockReturnValue(room); + vi.spyOn(client, "getRoom").mockReturnValue(room); mxEvent = mkEvent({ event: true, type: "m.room.message", @@ -73,8 +73,8 @@ describe("ReactionsRowButtonViewModel", () => { it("updates count with merge and does not touch tooltip props", () => { const vm = new ReactionsRowButtonViewModel(createProps()); - const tooltipSetPropsSpy = jest.spyOn(getTooltipVm(vm), "setProps"); - const listener = jest.fn(); + const tooltipSetPropsSpy = vi.spyOn(getTooltipVm(vm), "setProps"); + const listener = vi.fn(); vm.subscribe(listener); vm.setCount(5); @@ -95,7 +95,7 @@ describe("ReactionsRowButtonViewModel", () => { }); it("falls back when no room is available", () => { - jest.spyOn(client, "getRoom").mockReturnValue(null); + vi.spyOn(client, "getRoom").mockReturnValue(null); const vm = new ReactionsRowButtonViewModel(createProps()); @@ -125,8 +125,8 @@ describe("ReactionsRowButtonViewModel", () => { it("updates selected state with myReactionEvent without touching tooltip props", () => { const vm = new ReactionsRowButtonViewModel(createProps()); - const tooltipSetPropsSpy = jest.spyOn(getTooltipVm(vm), "setProps"); - const listener = jest.fn(); + const tooltipSetPropsSpy = vi.spyOn(getTooltipVm(vm), "setProps"); + const listener = vi.fn(); vm.subscribe(listener); const myReactionEvent = createReactionEvent("@me:example.org"); @@ -139,7 +139,7 @@ describe("ReactionsRowButtonViewModel", () => { it("updates disabled state without touching tooltip props", () => { const vm = new ReactionsRowButtonViewModel(createProps({ disabled: false })); - const tooltipSetPropsSpy = jest.spyOn(getTooltipVm(vm), "setProps"); + const tooltipSetPropsSpy = vi.spyOn(getTooltipVm(vm), "setProps"); vm.setDisabled(true); @@ -149,7 +149,7 @@ describe("ReactionsRowButtonViewModel", () => { it("setReactionData forwards to tooltip via setProps and updates snapshot content", () => { const vm = new ReactionsRowButtonViewModel(createProps()); - const tooltipSetPropsSpy = jest.spyOn(getTooltipVm(vm), "setProps"); + const tooltipSetPropsSpy = vi.spyOn(getTooltipVm(vm), "setProps"); const reactionEvents = [createReactionEvent("@carol:example.org", "👎")]; vm.setReactionData("👎", reactionEvents, false); diff --git a/apps/web/test/viewmodels/message-body/ReactionsRowViewModel-test.ts b/apps/web/src/viewmodels/room/timeline/event-tile/reactions/ReactionsRowViewModel.test.ts similarity index 90% rename from apps/web/test/viewmodels/message-body/ReactionsRowViewModel-test.ts rename to apps/web/src/viewmodels/room/timeline/event-tile/reactions/ReactionsRowViewModel.test.ts index 6e74504ac1..89aabc2a06 100644 --- a/apps/web/test/viewmodels/message-body/ReactionsRowViewModel-test.ts +++ b/apps/web/src/viewmodels/room/timeline/event-tile/reactions/ReactionsRowViewModel.test.ts @@ -5,9 +5,12 @@ * Please see LICENSE files in the repository root for full details. */ -import { type MouseEvent } from "react"; +// @vitest-environment happy-dom -import { ReactionsRowViewModel } from "../../../src/viewmodels/room/timeline/event-tile/reactions/ReactionsRowViewModel"; +import { type MouseEvent } from "react"; +import { vi, describe, it, expect } from "vitest"; + +import { ReactionsRowViewModel } from "./ReactionsRowViewModel"; describe("ReactionsRowViewModel", () => { const createVm = ( @@ -33,7 +36,7 @@ describe("ReactionsRowViewModel", () => { it("hides show-all after onShowAllClick", () => { const vm = createVm(); - const listener = jest.fn(); + const listener = vi.fn(); vm.subscribe(listener); vm.onShowAllClick(); @@ -68,8 +71,8 @@ describe("ReactionsRowViewModel", () => { it("forwards add-reaction handlers", () => { const vm = createVm(); - const onAddReactionClick = jest.fn(); - const onAddReactionContextMenu = jest.fn(); + const onAddReactionClick = vi.fn(); + const onAddReactionContextMenu = vi.fn(); vm.setAddReactionHandlers({ onAddReactionClick, @@ -89,7 +92,7 @@ describe("ReactionsRowViewModel", () => { it("doesn't emit only setters that always merge when values are unchanged", () => { const vm = createVm(); const previousSnapshot = vm.getSnapshot(); - const listener = jest.fn(); + const listener = vi.fn(); vm.subscribe(listener); vm.setCanReact(true); diff --git a/apps/web/test/viewmodels/message-body/MessageTimestampViewModel-test.ts b/apps/web/src/viewmodels/room/timeline/event-tile/timestamp/MessageTimestampViewModel.test.ts similarity index 84% rename from apps/web/test/viewmodels/message-body/MessageTimestampViewModel-test.ts rename to apps/web/src/viewmodels/room/timeline/event-tile/timestamp/MessageTimestampViewModel.test.ts index 8e58d9911c..af33c50706 100644 --- a/apps/web/test/viewmodels/message-body/MessageTimestampViewModel-test.ts +++ b/apps/web/src/viewmodels/room/timeline/event-tile/timestamp/MessageTimestampViewModel.test.ts @@ -5,10 +5,12 @@ * Please see LICENSE files in the repository root for full details. */ -import * as DateUtils from "../../../src/DateUtils"; -import { MessageTimestampViewModel } from "../../../src/viewmodels/room/timeline/event-tile/timestamp/MessageTimestampViewModel"; +import { vi, describe, it, expect, afterEach } from "vitest"; -jest.mock("../../../src/settings/SettingsStore"); +import * as DateUtils from "../../../../../DateUtils"; +import { MessageTimestampViewModel } from "./MessageTimestampViewModel"; + +vi.mock("../../../../../settings/SettingsStore"); describe("MessageTimestampViewModel", () => { // Friday Dec 17 2021, 9:09am @@ -17,7 +19,7 @@ describe("MessageTimestampViewModel", () => { const DAY_MS = HOUR_MS * 24; afterEach(() => { - jest.restoreAllMocks(); + vi.restoreAllMocks(); }); it("should return the snapshot", () => { @@ -53,8 +55,8 @@ describe("MessageTimestampViewModel", () => { }); it("should use formatRelativeTime when showRelative is true", () => { - jest.spyOn(DateUtils, "formatFullDate").mockReturnValue("SENT_AT"); - const formatRelativeTimeSpy = jest.spyOn(DateUtils, "formatRelativeTime").mockReturnValue("RELATIVE"); + vi.spyOn(DateUtils, "formatFullDate").mockReturnValue("SENT_AT"); + const formatRelativeTimeSpy = vi.spyOn(DateUtils, "formatRelativeTime").mockReturnValue("RELATIVE"); const vm = new MessageTimestampViewModel({ ts: nowDate.getTime(), @@ -70,7 +72,7 @@ describe("MessageTimestampViewModel", () => { }); it("should use full date when showFullDate is true and respect showSeconds", () => { - const formatFullDateSpy = jest + const formatFullDateSpy = vi .spyOn(DateUtils, "formatFullDate") .mockImplementation((_date, _showTwelveHour, showSeconds) => showSeconds === false ? "FULL_NO_SECONDS" : "SENT_AT", @@ -90,9 +92,9 @@ describe("MessageTimestampViewModel", () => { }); it("should use full time when showSeconds is true without full date", () => { - jest.spyOn(DateUtils, "formatFullDate").mockReturnValue("SENT_AT"); - const formatFullTimeSpy = jest.spyOn(DateUtils, "formatFullTime").mockReturnValue("FULL_TIME"); - const formatTimeSpy = jest.spyOn(DateUtils, "formatTime").mockReturnValue("TIME"); + vi.spyOn(DateUtils, "formatFullDate").mockReturnValue("SENT_AT"); + const formatFullTimeSpy = vi.spyOn(DateUtils, "formatFullTime").mockReturnValue("FULL_TIME"); + const formatTimeSpy = vi.spyOn(DateUtils, "formatTime").mockReturnValue("TIME"); const vm = new MessageTimestampViewModel({ ts: nowDate.getTime(), @@ -121,12 +123,12 @@ describe("MessageTimestampViewModel", () => { }); it("updates all props in one batch", () => { - const onClick = jest.fn(); - const onContextMenu = jest.fn(); + const onClick = vi.fn(); + const onContextMenu = vi.fn(); const vm = new MessageTimestampViewModel({ ts: nowDate.getTime(), }); - const listener = jest.fn(); + const listener = vi.fn(); vm.subscribe(listener); vm.setProps({ @@ -152,8 +154,8 @@ describe("MessageTimestampViewModel", () => { }); it("replaces props and clears omitted optional values", () => { - const onClick = jest.fn(); - const onContextMenu = jest.fn(); + const onClick = vi.fn(); + const onContextMenu = vi.fn(); const vm = new MessageTimestampViewModel({ ts: nowDate.getTime(), receivedTs: nowDate.getTime() + DAY_MS, @@ -184,7 +186,7 @@ describe("MessageTimestampViewModel", () => { href: "https://example.test/event", }; const vm = new MessageTimestampViewModel(props); - const listener = jest.fn(); + const listener = vi.fn(); vm.subscribe(listener); vm.setProps(props);