|
| 1 | +/* |
| 2 | + * Copyright 2025 New Vector Ltd. |
| 3 | + * |
| 4 | + * SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial |
| 5 | + * Please see LICENSE files in the repository root for full details. |
| 6 | + */ |
| 7 | + |
| 8 | +import { renderHook, waitFor } from "jest-matrix-react"; |
| 9 | +import { type Room } from "matrix-js-sdk/src/matrix"; |
| 10 | + |
| 11 | +import { createTestClient, mkStubRoom } from "../../../../test-utils"; |
| 12 | +import { type MessagePreview, MessagePreviewStore } from "../../../../../src/stores/room-list/MessagePreviewStore"; |
| 13 | +import { useMessagePreviewViewModel } from "../../../../../src/components/viewmodels/roomlist/MessagePreviewViewModel"; |
| 14 | + |
| 15 | +describe("MessagePreviewViewModel", () => { |
| 16 | + let room: Room; |
| 17 | + |
| 18 | + beforeEach(() => { |
| 19 | + const matrixClient = createTestClient(); |
| 20 | + room = mkStubRoom("roomId", "roomName", matrixClient); |
| 21 | + }); |
| 22 | + |
| 23 | + it("should do an initial fetch of the message preview", async () => { |
| 24 | + // Mock the store to return some text. |
| 25 | + jest.spyOn(MessagePreviewStore.instance, "getPreviewForRoom").mockImplementation(async (room) => { |
| 26 | + return { text: "Hello world!" } as MessagePreview; |
| 27 | + }); |
| 28 | + |
| 29 | + const { result: vm } = renderHook(() => useMessagePreviewViewModel(room)); |
| 30 | + |
| 31 | + // Eventually, vm.message should have the text from the store. |
| 32 | + await waitFor(() => { |
| 33 | + expect(vm.current.message).toEqual("Hello world!"); |
| 34 | + }); |
| 35 | + }); |
| 36 | + |
| 37 | + it("should fetch message preview again on update from store", async () => { |
| 38 | + // Mock the store to return the text in variable message. |
| 39 | + let message = "Hello World!"; |
| 40 | + jest.spyOn(MessagePreviewStore.instance, "getPreviewForRoom").mockImplementation(async (room) => { |
| 41 | + return { text: message } as MessagePreview; |
| 42 | + }); |
| 43 | + jest.spyOn(MessagePreviewStore, "getPreviewChangedEventName").mockImplementation((room) => { |
| 44 | + return "UPDATE"; |
| 45 | + }); |
| 46 | + |
| 47 | + const { result: vm } = renderHook(() => useMessagePreviewViewModel(room)); |
| 48 | + |
| 49 | + // Let's assume the message changed. |
| 50 | + message = "New message!"; |
| 51 | + MessagePreviewStore.instance.emit("UPDATE"); |
| 52 | + |
| 53 | + /// vm.message should be the updated message. |
| 54 | + await waitFor(() => { |
| 55 | + expect(vm.current.message).toEqual(message); |
| 56 | + }); |
| 57 | + }); |
| 58 | +}); |
0 commit comments