Merge matrix-react-sdk into element-web
Merge remote-tracking branch 'repomerge/t3chguy/repomerge' into t3chguy/repo-merge Signed-off-by: Michael Telatynski <7t3chguy@gmail.com>
This commit is contained in:
commit
f0ee7f7905
3265 changed files with 484599 additions and 699 deletions
53
test/unit-tests/stores/AccountPasswordStore-test.ts
Normal file
53
test/unit-tests/stores/AccountPasswordStore-test.ts
Normal file
|
@ -0,0 +1,53 @@
|
|||
/*
|
||||
Copyright 2024 New Vector Ltd.
|
||||
Copyright 2023 The Matrix.org Foundation C.I.C.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { AccountPasswordStore } from "../../../src/stores/AccountPasswordStore";
|
||||
|
||||
jest.useFakeTimers();
|
||||
|
||||
describe("AccountPasswordStore", () => {
|
||||
let accountPasswordStore: AccountPasswordStore;
|
||||
|
||||
beforeEach(() => {
|
||||
accountPasswordStore = new AccountPasswordStore();
|
||||
});
|
||||
|
||||
it("should not have a password by default", () => {
|
||||
expect(accountPasswordStore.getPassword()).toBeUndefined();
|
||||
});
|
||||
|
||||
describe("when setting a password", () => {
|
||||
beforeEach(() => {
|
||||
accountPasswordStore.setPassword("pass1");
|
||||
});
|
||||
|
||||
it("should return the password", () => {
|
||||
expect(accountPasswordStore.getPassword()).toBe("pass1");
|
||||
});
|
||||
|
||||
describe("and the password timeout exceed", () => {
|
||||
beforeEach(() => {
|
||||
jest.advanceTimersToNextTimer();
|
||||
});
|
||||
|
||||
it("should clear the password", () => {
|
||||
expect(accountPasswordStore.getPassword()).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("and setting another password", () => {
|
||||
beforeEach(() => {
|
||||
accountPasswordStore.setPassword("pass2");
|
||||
});
|
||||
|
||||
it("should return the other password", () => {
|
||||
expect(accountPasswordStore.getPassword()).toBe("pass2");
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
45
test/unit-tests/stores/ActiveWidgetStore-test.ts
Normal file
45
test/unit-tests/stores/ActiveWidgetStore-test.ts
Normal file
|
@ -0,0 +1,45 @@
|
|||
/*
|
||||
Copyright 2024 New Vector Ltd.
|
||||
Copyright 2022 The Matrix.org Foundation C.I.C.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import ActiveWidgetStore from "../../../src/stores/ActiveWidgetStore";
|
||||
|
||||
describe("ActiveWidgetStore", () => {
|
||||
const store = ActiveWidgetStore.instance;
|
||||
|
||||
it("tracks docked and live tiles correctly", () => {
|
||||
expect(store.isDocked("1", "r1")).toEqual(false);
|
||||
expect(store.isLive("1", "r1")).toEqual(false);
|
||||
|
||||
// Try undocking the widget before it gets docked
|
||||
store.undockWidget("1", "r1");
|
||||
expect(store.isDocked("1", "r1")).toEqual(false);
|
||||
expect(store.isLive("1", "r1")).toEqual(false);
|
||||
|
||||
store.dockWidget("1", "r1");
|
||||
expect(store.isDocked("1", "r1")).toEqual(true);
|
||||
expect(store.isLive("1", "r1")).toEqual(true);
|
||||
|
||||
store.dockWidget("1", "r1");
|
||||
expect(store.isDocked("1", "r1")).toEqual(true);
|
||||
expect(store.isLive("1", "r1")).toEqual(true);
|
||||
|
||||
store.undockWidget("1", "r1");
|
||||
expect(store.isDocked("1", "r1")).toEqual(true);
|
||||
expect(store.isLive("1", "r1")).toEqual(true);
|
||||
|
||||
// Ensure that persistent widgets remain live even while undocked
|
||||
store.setWidgetPersistence("1", "r1", true);
|
||||
store.undockWidget("1", "r1");
|
||||
expect(store.isDocked("1", "r1")).toEqual(false);
|
||||
expect(store.isLive("1", "r1")).toEqual(true);
|
||||
|
||||
store.setWidgetPersistence("1", "r1", false);
|
||||
expect(store.isDocked("1", "r1")).toEqual(false);
|
||||
expect(store.isLive("1", "r1")).toEqual(false);
|
||||
});
|
||||
});
|
107
test/unit-tests/stores/AutoRageshakeStore-test.ts
Normal file
107
test/unit-tests/stores/AutoRageshakeStore-test.ts
Normal file
|
@ -0,0 +1,107 @@
|
|||
/*
|
||||
Copyright 2024 New Vector Ltd.
|
||||
Copyright 2023 The Matrix.org Foundation C.I.C.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { mocked } from "jest-mock";
|
||||
import {
|
||||
ClientEvent,
|
||||
EventType,
|
||||
MatrixClient,
|
||||
MatrixEvent,
|
||||
MatrixEventEvent,
|
||||
SyncState,
|
||||
} from "matrix-js-sdk/src/matrix";
|
||||
|
||||
import SettingsStore from "../../../src/settings/SettingsStore";
|
||||
import AutoRageshakeStore from "../../../src/stores/AutoRageshakeStore";
|
||||
import { mkEvent, stubClient } from "../../test-utils";
|
||||
|
||||
jest.mock("../../../src/rageshake/submit-rageshake");
|
||||
jest.mock("../../../src/stores/WidgetStore");
|
||||
jest.mock("../../../src/stores/widgets/WidgetLayoutStore");
|
||||
|
||||
const TEST_SENDER = "@sender@example.com";
|
||||
|
||||
describe("AutoRageshakeStore", () => {
|
||||
const roomId = "!room:example.com";
|
||||
let client: MatrixClient;
|
||||
let utdEvent: MatrixEvent;
|
||||
let autoRageshakeStore: AutoRageshakeStore;
|
||||
|
||||
beforeAll(() => {
|
||||
jest.useFakeTimers();
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
jest.spyOn(SettingsStore, "getValue").mockReturnValue(true);
|
||||
|
||||
client = stubClient();
|
||||
|
||||
// @ts-ignore bypass private ctor for tests
|
||||
autoRageshakeStore = new AutoRageshakeStore();
|
||||
autoRageshakeStore.start();
|
||||
|
||||
utdEvent = mkEvent({
|
||||
event: true,
|
||||
content: {},
|
||||
room: roomId,
|
||||
user: TEST_SENDER,
|
||||
type: EventType.RoomMessage,
|
||||
});
|
||||
jest.spyOn(utdEvent, "isDecryptionFailure").mockReturnValue(true);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("when the initial sync completed", () => {
|
||||
beforeEach(() => {
|
||||
client.emit(ClientEvent.Sync, SyncState.Syncing, SyncState.Stopped, { nextSyncToken: "abc123" });
|
||||
});
|
||||
|
||||
describe("and an undecryptable event occurs", () => {
|
||||
beforeEach(() => {
|
||||
client.emit(MatrixEventEvent.Decrypted, utdEvent);
|
||||
// simulate event grace period
|
||||
jest.advanceTimersByTime(5500);
|
||||
});
|
||||
|
||||
it("should send a to-device message", () => {
|
||||
expect(mocked(client).sendToDevice.mock.calls).toEqual([
|
||||
[
|
||||
"im.vector.auto_rs_request",
|
||||
new Map([
|
||||
[
|
||||
TEST_SENDER,
|
||||
new Map([
|
||||
[
|
||||
undefined,
|
||||
{
|
||||
"device_id": undefined,
|
||||
"event_id": utdEvent.getId(),
|
||||
"org.matrix.msgid": expect.any(String),
|
||||
"recipient_rageshake": undefined,
|
||||
"room_id": "!room:example.com",
|
||||
"sender_key": undefined,
|
||||
"session_id": undefined,
|
||||
"user_id": TEST_SENDER,
|
||||
},
|
||||
],
|
||||
]),
|
||||
],
|
||||
]),
|
||||
],
|
||||
]);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
175
test/unit-tests/stores/BreadcrumbsStore-test.ts
Normal file
175
test/unit-tests/stores/BreadcrumbsStore-test.ts
Normal file
|
@ -0,0 +1,175 @@
|
|||
/*
|
||||
Copyright 2024 New Vector Ltd.
|
||||
Copyright 2023 The Matrix.org Foundation C.I.C.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { mocked } from "jest-mock";
|
||||
import { MatrixClient, Room } from "matrix-js-sdk/src/matrix";
|
||||
|
||||
import { createTestClient, flushPromises, setupAsyncStoreWithClient } from "../../test-utils";
|
||||
import SettingsStore from "../../../src/settings/SettingsStore";
|
||||
import { BreadcrumbsStore } from "../../../src/stores/BreadcrumbsStore";
|
||||
import { Action } from "../../../src/dispatcher/actions";
|
||||
import { defaultDispatcher } from "../../../src/dispatcher/dispatcher";
|
||||
|
||||
describe("BreadcrumbsStore", () => {
|
||||
let store: BreadcrumbsStore;
|
||||
const client: MatrixClient = createTestClient();
|
||||
|
||||
beforeEach(() => {
|
||||
jest.resetAllMocks();
|
||||
store = BreadcrumbsStore.instance;
|
||||
setupAsyncStoreWithClient(store, client);
|
||||
jest.spyOn(SettingsStore, "setValue").mockImplementation(() => Promise.resolve());
|
||||
jest.spyOn(SettingsStore, "getValue").mockReturnValue(false);
|
||||
});
|
||||
|
||||
it("does not meet room requirements if there are not enough rooms", () => {
|
||||
// We don't have enough rooms, so we don't meet requirements
|
||||
mocked(client.getVisibleRooms).mockReturnValue(fakeRooms(2));
|
||||
expect(store.meetsRoomRequirement).toBe(false);
|
||||
});
|
||||
|
||||
it("meets room requirements if there are enough rooms", () => {
|
||||
// We do have enough rooms to show breadcrumbs
|
||||
mocked(client.getVisibleRooms).mockReturnValue(fakeRooms(25));
|
||||
expect(store.meetsRoomRequirement).toBe(true);
|
||||
});
|
||||
|
||||
describe("And the feature_dynamic_room_predecessors is enabled", () => {
|
||||
beforeEach(() => {
|
||||
// Turn on feature_dynamic_room_predecessors setting
|
||||
jest.spyOn(SettingsStore, "getValue").mockImplementation(
|
||||
(settingName) => settingName === "feature_dynamic_room_predecessors",
|
||||
);
|
||||
});
|
||||
|
||||
it("passes through the dynamic room precessors flag", () => {
|
||||
mocked(client.getVisibleRooms).mockReturnValue(fakeRooms(25));
|
||||
store.meetsRoomRequirement;
|
||||
expect(client.getVisibleRooms).toHaveBeenCalledWith(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("And the feature_dynamic_room_predecessors is not enabled", () => {
|
||||
it("passes through the dynamic room precessors flag", () => {
|
||||
mocked(client.getVisibleRooms).mockReturnValue(fakeRooms(25));
|
||||
store.meetsRoomRequirement;
|
||||
expect(client.getVisibleRooms).toHaveBeenCalledWith(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("If the feature_dynamic_room_predecessors is not enabled", () => {
|
||||
beforeEach(() => {
|
||||
jest.spyOn(SettingsStore, "getValue").mockReturnValue(false);
|
||||
});
|
||||
|
||||
it("Appends a room when you join", async () => {
|
||||
// Sanity: no rooms initially
|
||||
expect(store.rooms).toEqual([]);
|
||||
|
||||
// Given a room
|
||||
const room = fakeRoom();
|
||||
mocked(client.getRoom).mockReturnValue(room);
|
||||
mocked(client.getRoomUpgradeHistory).mockReturnValue([]);
|
||||
|
||||
// When we hear that we have joined it
|
||||
await dispatchJoinRoom(room.roomId);
|
||||
|
||||
// It is stored in the store's room list
|
||||
expect(store.rooms.map((r) => r.roomId)).toEqual([room.roomId]);
|
||||
});
|
||||
|
||||
it("Replaces the old room when a newer one joins", async () => {
|
||||
// Given an old room and a new room
|
||||
const oldRoom = fakeRoom();
|
||||
const newRoom = fakeRoom();
|
||||
mocked(client.getRoom).mockImplementation((roomId) => {
|
||||
if (roomId === oldRoom.roomId) return oldRoom;
|
||||
return newRoom;
|
||||
});
|
||||
// Where the new one is a predecessor of the old one
|
||||
mocked(client.getRoomUpgradeHistory).mockReturnValue([oldRoom, newRoom]);
|
||||
|
||||
// When we hear that we joined the old room, then the new one
|
||||
await dispatchJoinRoom(oldRoom.roomId);
|
||||
await dispatchJoinRoom(newRoom.roomId);
|
||||
|
||||
// The store only has the new one
|
||||
expect(store.rooms.map((r) => r.roomId)).toEqual([newRoom.roomId]);
|
||||
});
|
||||
|
||||
it("Passes through the dynamic predecessor setting", async () => {
|
||||
// Given a room
|
||||
const room = fakeRoom();
|
||||
mocked(client.getRoom).mockReturnValue(room);
|
||||
mocked(client.getRoomUpgradeHistory).mockReturnValue([]);
|
||||
|
||||
// When we signal that we have joined
|
||||
await dispatchJoinRoom(room.roomId);
|
||||
|
||||
// We pass the value of the dynamic predecessor setting through
|
||||
expect(client.getRoomUpgradeHistory).toHaveBeenCalledWith(room.roomId, false, false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("If the feature_dynamic_room_predecessors is enabled", () => {
|
||||
beforeEach(() => {
|
||||
// Turn on feature_dynamic_room_predecessors setting
|
||||
jest.spyOn(SettingsStore, "getValue").mockImplementation(
|
||||
(settingName) => settingName === "feature_dynamic_room_predecessors",
|
||||
);
|
||||
});
|
||||
|
||||
it("Passes through the dynamic predecessor setting", async () => {
|
||||
// Given a room
|
||||
const room = fakeRoom();
|
||||
mocked(client.getRoom).mockReturnValue(room);
|
||||
mocked(client.getRoomUpgradeHistory).mockReturnValue([]);
|
||||
|
||||
// When we signal that we have joined
|
||||
await dispatchJoinRoom(room.roomId);
|
||||
|
||||
// We pass the value of the dynamic predecessor setting through
|
||||
expect(client.getRoomUpgradeHistory).toHaveBeenCalledWith(room.roomId, false, true);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Send a JoinRoom event via the dispatcher, and wait for it to process.
|
||||
*/
|
||||
async function dispatchJoinRoom(roomId: string) {
|
||||
defaultDispatcher.dispatch(
|
||||
{
|
||||
action: Action.JoinRoom,
|
||||
roomId,
|
||||
metricsTrigger: null,
|
||||
},
|
||||
true, // synchronous dispatch
|
||||
);
|
||||
|
||||
// Wait for event dispatch to happen
|
||||
await flushPromises();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create as many fake rooms in an array as you ask for.
|
||||
*/
|
||||
function fakeRooms(howMany: number): Room[] {
|
||||
const ret: Room[] = [];
|
||||
for (let i = 0; i < howMany; i++) {
|
||||
ret.push(fakeRoom());
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
let roomIdx = 0;
|
||||
|
||||
function fakeRoom(): Room {
|
||||
roomIdx++;
|
||||
return new Room(`room${roomIdx}`, client, "@user:example.com");
|
||||
}
|
||||
});
|
79
test/unit-tests/stores/LifecycleStore-test.ts
Normal file
79
test/unit-tests/stores/LifecycleStore-test.ts
Normal file
|
@ -0,0 +1,79 @@
|
|||
/*
|
||||
Copyright 2024 New Vector Ltd.
|
||||
Copyright 2024 The Matrix.org Foundation C.I.C.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { mocked } from "jest-mock";
|
||||
import { SyncState } from "matrix-js-sdk/src/matrix";
|
||||
import { sleep } from "matrix-js-sdk/src/utils";
|
||||
|
||||
import { MatrixClientPeg } from "../../../src/MatrixClientPeg";
|
||||
import ToastStore from "../../../src/stores/ToastStore";
|
||||
import { stubClient } from "../../test-utils";
|
||||
import LifecycleStore from "../../../src/stores/LifecycleStore";
|
||||
|
||||
describe("LifecycleStore", () => {
|
||||
stubClient();
|
||||
const client = MatrixClientPeg.safeGet();
|
||||
let addOrReplaceToast: jest.SpyInstance;
|
||||
|
||||
beforeEach(() => {
|
||||
addOrReplaceToast = jest.spyOn(ToastStore.sharedInstance(), "addOrReplaceToast");
|
||||
});
|
||||
|
||||
it("should do nothing if the matrix server version is supported", async () => {
|
||||
mocked(client).isVersionSupported.mockResolvedValue(true);
|
||||
|
||||
(LifecycleStore as any).onDispatch({
|
||||
action: "MatrixActions.sync",
|
||||
state: SyncState.Syncing,
|
||||
prevState: SyncState.Prepared,
|
||||
});
|
||||
|
||||
await sleep(0);
|
||||
|
||||
expect(addOrReplaceToast).not.toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
title: "Your server is unsupported",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("should show a toast if the matrix server version is unsupported", async () => {
|
||||
mocked(client).isVersionSupported.mockResolvedValue(false);
|
||||
|
||||
(LifecycleStore as any).onDispatch({
|
||||
action: "MatrixActions.sync",
|
||||
state: SyncState.Syncing,
|
||||
prevState: SyncState.Prepared,
|
||||
});
|
||||
|
||||
await sleep(0);
|
||||
|
||||
expect(addOrReplaceToast).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
title: "Your server is unsupported",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("dismisses toast on accept button", async () => {
|
||||
const dismissToast = jest.spyOn(ToastStore.sharedInstance(), "dismissToast");
|
||||
mocked(client).isVersionSupported.mockResolvedValue(false);
|
||||
|
||||
(LifecycleStore as any).onDispatch({
|
||||
action: "MatrixActions.sync",
|
||||
state: SyncState.Syncing,
|
||||
prevState: SyncState.Prepared,
|
||||
});
|
||||
|
||||
await sleep(0);
|
||||
|
||||
addOrReplaceToast.mock.calls[0][0].props.onPrimaryClick();
|
||||
|
||||
expect(dismissToast).toHaveBeenCalledWith(addOrReplaceToast.mock.calls[0][0].key);
|
||||
});
|
||||
});
|
237
test/unit-tests/stores/MemberListStore-test.ts
Normal file
237
test/unit-tests/stores/MemberListStore-test.ts
Normal file
|
@ -0,0 +1,237 @@
|
|||
/*
|
||||
Copyright 2024 New Vector Ltd.
|
||||
Copyright 2022 The Matrix.org Foundation C.I.C.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { mocked } from "jest-mock";
|
||||
import { EventType, IContent, MatrixClient, MatrixEvent, Room } from "matrix-js-sdk/src/matrix";
|
||||
import { KnownMembership } from "matrix-js-sdk/src/types";
|
||||
|
||||
import SdkConfig from "../../../src/SdkConfig";
|
||||
import SettingsStore from "../../../src/settings/SettingsStore";
|
||||
import { MemberListStore } from "../../../src/stores/MemberListStore";
|
||||
import { stubClient } from "../../test-utils";
|
||||
import { TestSdkContext } from "../TestSdkContext";
|
||||
|
||||
describe("MemberListStore", () => {
|
||||
const alice = "@alice:bar";
|
||||
const bob = "@bob:bar";
|
||||
const charlie = "@charlie:bar";
|
||||
const roomId = "!foo:bar";
|
||||
let store: MemberListStore;
|
||||
let client: MatrixClient;
|
||||
let room: Room;
|
||||
|
||||
beforeEach(() => {
|
||||
const context = new TestSdkContext();
|
||||
client = stubClient();
|
||||
client.baseUrl = "https://invalid.base.url.here";
|
||||
context.client = client;
|
||||
store = new MemberListStore(context);
|
||||
// alice is joined to the room.
|
||||
room = new Room(roomId, client, client.getUserId()!);
|
||||
room.currentState.setStateEvents([
|
||||
new MatrixEvent({
|
||||
type: EventType.RoomCreate,
|
||||
state_key: "",
|
||||
content: {
|
||||
creator: alice,
|
||||
},
|
||||
sender: alice,
|
||||
room_id: roomId,
|
||||
event_id: "$1",
|
||||
}),
|
||||
new MatrixEvent({
|
||||
type: EventType.RoomMember,
|
||||
state_key: alice,
|
||||
content: {
|
||||
membership: KnownMembership.Join,
|
||||
},
|
||||
sender: alice,
|
||||
room_id: roomId,
|
||||
event_id: "$2",
|
||||
}),
|
||||
]);
|
||||
room.recalculate();
|
||||
mocked(client.getRoom).mockImplementation((r: string): Room | null => {
|
||||
if (r === roomId) {
|
||||
return room;
|
||||
}
|
||||
return null;
|
||||
});
|
||||
SdkConfig.put({
|
||||
enable_presence_by_hs_url: {
|
||||
[client.baseUrl]: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("loads members in a room", async () => {
|
||||
addMember(room, bob, KnownMembership.Invite);
|
||||
addMember(room, charlie, KnownMembership.Leave);
|
||||
|
||||
const { invited, joined } = await store.loadMemberList(roomId);
|
||||
expect(invited).toEqual([room.getMember(bob)]);
|
||||
expect(joined).toEqual([room.getMember(alice)]);
|
||||
});
|
||||
|
||||
it("fails gracefully for invalid rooms", async () => {
|
||||
const { invited, joined } = await store.loadMemberList("!idontexist:bar");
|
||||
expect(invited).toEqual([]);
|
||||
expect(joined).toEqual([]);
|
||||
});
|
||||
|
||||
it("sorts by power level", async () => {
|
||||
addMember(room, bob, KnownMembership.Join);
|
||||
addMember(room, charlie, KnownMembership.Join);
|
||||
setPowerLevels(room, {
|
||||
users: {
|
||||
[alice]: 100,
|
||||
[charlie]: 50,
|
||||
},
|
||||
users_default: 10,
|
||||
});
|
||||
|
||||
const { invited, joined } = await store.loadMemberList(roomId);
|
||||
expect(invited).toEqual([]);
|
||||
expect(joined).toEqual([room.getMember(alice), room.getMember(charlie), room.getMember(bob)]);
|
||||
});
|
||||
|
||||
it("sorts by name if power level is equal", async () => {
|
||||
const doris = "@doris:bar";
|
||||
addMember(room, bob, KnownMembership.Join);
|
||||
addMember(room, charlie, KnownMembership.Join);
|
||||
setPowerLevels(room, {
|
||||
users_default: 10,
|
||||
});
|
||||
|
||||
let { invited, joined } = await store.loadMemberList(roomId);
|
||||
expect(invited).toEqual([]);
|
||||
expect(joined).toEqual([room.getMember(alice), room.getMember(bob), room.getMember(charlie)]);
|
||||
|
||||
// Ensure it sorts by display name if they are set
|
||||
addMember(room, doris, KnownMembership.Join, "AAAAA");
|
||||
({ invited, joined } = await store.loadMemberList(roomId));
|
||||
expect(invited).toEqual([]);
|
||||
expect(joined).toEqual([
|
||||
room.getMember(doris),
|
||||
room.getMember(alice),
|
||||
room.getMember(bob),
|
||||
room.getMember(charlie),
|
||||
]);
|
||||
});
|
||||
|
||||
it("filters based on a search query", async () => {
|
||||
const mice = "@mice:bar";
|
||||
const zorro = "@zorro:bar";
|
||||
addMember(room, bob, KnownMembership.Join);
|
||||
addMember(room, mice, KnownMembership.Join);
|
||||
|
||||
let { invited, joined } = await store.loadMemberList(roomId, "ice");
|
||||
expect(invited).toEqual([]);
|
||||
expect(joined).toEqual([room.getMember(alice), room.getMember(mice)]);
|
||||
|
||||
// Ensure it filters by display name if they are set
|
||||
addMember(room, zorro, KnownMembership.Join, "ice ice baby");
|
||||
({ invited, joined } = await store.loadMemberList(roomId, "ice"));
|
||||
expect(invited).toEqual([]);
|
||||
expect(joined).toEqual([room.getMember(alice), room.getMember(zorro), room.getMember(mice)]);
|
||||
});
|
||||
|
||||
describe("lazy loading", () => {
|
||||
beforeEach(() => {
|
||||
mocked(client.hasLazyLoadMembersEnabled).mockReturnValue(true);
|
||||
room.loadMembersIfNeeded = jest.fn();
|
||||
mocked(room.loadMembersIfNeeded).mockResolvedValue(true);
|
||||
});
|
||||
|
||||
it("calls Room.loadMembersIfNeeded once when enabled", async () => {
|
||||
let { joined } = await store.loadMemberList(roomId);
|
||||
expect(joined).toEqual([room.getMember(alice)]);
|
||||
expect(room.loadMembersIfNeeded).toHaveBeenCalledTimes(1);
|
||||
({ joined } = await store.loadMemberList(roomId));
|
||||
expect(joined).toEqual([room.getMember(alice)]);
|
||||
expect(room.loadMembersIfNeeded).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sliding sync", () => {
|
||||
beforeEach(() => {
|
||||
jest.spyOn(SettingsStore, "getValue").mockImplementation((settingName, roomId, value) => {
|
||||
return settingName === "feature_sliding_sync"; // this is enabled, everything else is disabled.
|
||||
});
|
||||
client.members = jest.fn();
|
||||
});
|
||||
|
||||
it("calls /members when lazy loading", async () => {
|
||||
mocked(client.members).mockResolvedValue({
|
||||
chunk: [
|
||||
{
|
||||
type: EventType.RoomMember,
|
||||
state_key: bob,
|
||||
content: {
|
||||
membership: KnownMembership.Join,
|
||||
displayname: "Bob",
|
||||
},
|
||||
sender: bob,
|
||||
room_id: room.roomId,
|
||||
event_id: "$" + Math.random(),
|
||||
origin_server_ts: 2,
|
||||
},
|
||||
],
|
||||
});
|
||||
const { joined } = await store.loadMemberList(roomId);
|
||||
expect(joined).toEqual([room.getMember(alice), room.getMember(bob)]);
|
||||
expect(client.members).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not use lazy loading on encrypted rooms", async () => {
|
||||
client.isRoomEncrypted = jest.fn();
|
||||
mocked(client.isRoomEncrypted).mockReturnValue(true);
|
||||
|
||||
const { joined } = await store.loadMemberList(roomId);
|
||||
expect(joined).toEqual([room.getMember(alice)]);
|
||||
expect(client.members).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
function addEventToRoom(room: Room, ev: MatrixEvent) {
|
||||
room.getLiveTimeline().addEvent(ev, {
|
||||
toStartOfTimeline: false,
|
||||
});
|
||||
}
|
||||
|
||||
function setPowerLevels(room: Room, pl: IContent) {
|
||||
addEventToRoom(
|
||||
room,
|
||||
new MatrixEvent({
|
||||
type: EventType.RoomPowerLevels,
|
||||
state_key: "",
|
||||
content: pl,
|
||||
sender: room.getCreator()!,
|
||||
room_id: room.roomId,
|
||||
event_id: "$" + Math.random(),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function addMember(room: Room, userId: string, membership: string, displayName?: string) {
|
||||
addEventToRoom(
|
||||
room,
|
||||
new MatrixEvent({
|
||||
type: EventType.RoomMember,
|
||||
state_key: userId,
|
||||
content: {
|
||||
membership: membership,
|
||||
displayname: displayName,
|
||||
},
|
||||
sender: userId,
|
||||
room_id: room.roomId,
|
||||
event_id: "$" + Math.random(),
|
||||
}),
|
||||
);
|
||||
}
|
1243
test/unit-tests/stores/OwnBeaconStore-test.ts
Normal file
1243
test/unit-tests/stores/OwnBeaconStore-test.ts
Normal file
File diff suppressed because it is too large
Load diff
79
test/unit-tests/stores/OwnProfileStore-test.ts
Normal file
79
test/unit-tests/stores/OwnProfileStore-test.ts
Normal file
|
@ -0,0 +1,79 @@
|
|||
/*
|
||||
Copyright 2024 New Vector Ltd.
|
||||
Copyright 2023 The Matrix.org Foundation C.I.C.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { MatrixClient, MatrixError } from "matrix-js-sdk/src/matrix";
|
||||
import { MockedObject, mocked } from "jest-mock";
|
||||
|
||||
import { stubClient } from "../../test-utils";
|
||||
import { OwnProfileStore } from "../../../src/stores/OwnProfileStore";
|
||||
import { UPDATE_EVENT } from "../../../src/stores/AsyncStore";
|
||||
|
||||
describe("OwnProfileStore", () => {
|
||||
let client: MockedObject<MatrixClient>;
|
||||
let ownProfileStore: OwnProfileStore;
|
||||
let onUpdate: ReturnType<typeof jest.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
client = mocked(stubClient());
|
||||
onUpdate = jest.fn();
|
||||
ownProfileStore = new OwnProfileStore();
|
||||
ownProfileStore.addListener(UPDATE_EVENT, onUpdate);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
ownProfileStore.removeListener(UPDATE_EVENT, onUpdate);
|
||||
});
|
||||
|
||||
it("if the client has not yet been started, the displayname and avatar should be null", () => {
|
||||
expect(onUpdate).not.toHaveBeenCalled();
|
||||
expect(ownProfileStore.displayName).toBeNull();
|
||||
expect(ownProfileStore.avatarMxc).toBeNull();
|
||||
});
|
||||
|
||||
it("if the client has been started and there is a profile, it should return the profile display name and avatar", async () => {
|
||||
client.getProfileInfo.mockResolvedValue({
|
||||
displayname: "Display Name",
|
||||
avatar_url: "mxc://example.com/abc123",
|
||||
});
|
||||
await ownProfileStore.start();
|
||||
|
||||
expect(onUpdate).toHaveBeenCalled();
|
||||
expect(ownProfileStore.displayName).toBe("Display Name");
|
||||
expect(ownProfileStore.avatarMxc).toBe("mxc://example.com/abc123");
|
||||
});
|
||||
|
||||
it("if there is a M_NOT_FOUND error, it should report ready, displayname = MXID and avatar = null", async () => {
|
||||
client.getProfileInfo.mockRejectedValue(
|
||||
new MatrixError({
|
||||
error: "Not found",
|
||||
errcode: "M_NOT_FOUND",
|
||||
}),
|
||||
);
|
||||
await ownProfileStore.start();
|
||||
|
||||
expect(onUpdate).toHaveBeenCalled();
|
||||
expect(ownProfileStore.displayName).toBe(client.getSafeUserId());
|
||||
expect(ownProfileStore.avatarMxc).toBeNull();
|
||||
});
|
||||
|
||||
it("if there is any other error, it should not report ready, displayname = MXID and avatar = null", async () => {
|
||||
client.getProfileInfo.mockRejectedValue(
|
||||
new MatrixError({
|
||||
error: "Forbidden",
|
||||
errcode: "M_FORBIDDEN",
|
||||
}),
|
||||
);
|
||||
try {
|
||||
await ownProfileStore.start();
|
||||
} catch (ignore) {}
|
||||
|
||||
expect(onUpdate).not.toHaveBeenCalled();
|
||||
expect(ownProfileStore.displayName).toBe(client.getSafeUserId());
|
||||
expect(ownProfileStore.avatarMxc).toBeNull();
|
||||
});
|
||||
});
|
120
test/unit-tests/stores/ReleaseAnnouncementStore-test.tsx
Normal file
120
test/unit-tests/stores/ReleaseAnnouncementStore-test.tsx
Normal file
|
@ -0,0 +1,120 @@
|
|||
/*
|
||||
* Copyright 2024 New Vector Ltd.
|
||||
* Copyright 2024 The Matrix.org Foundation C.I.C.
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
||||
* Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { mocked } from "jest-mock";
|
||||
|
||||
import SettingsStore, { CallbackFn } from "../../../src/settings/SettingsStore";
|
||||
import { Feature, ReleaseAnnouncementStore } from "../../../src/stores/ReleaseAnnouncementStore";
|
||||
import { SettingLevel } from "../../../src/settings/SettingLevel";
|
||||
|
||||
jest.mock("../../../src/settings/SettingsStore");
|
||||
|
||||
describe("ReleaseAnnouncementStore", () => {
|
||||
let releaseAnnouncementStore: ReleaseAnnouncementStore;
|
||||
// Local settings
|
||||
// Instead of using the real SettingsStore, we use a local settings object
|
||||
// to avoid side effects between tests
|
||||
let settings: Record<string, any> = {};
|
||||
|
||||
beforeEach(() => {
|
||||
// Default settings
|
||||
settings = {
|
||||
feature_release_announcement: true,
|
||||
releaseAnnouncementData: {},
|
||||
};
|
||||
const watchCallbacks: Array<CallbackFn> = [];
|
||||
|
||||
mocked(SettingsStore.getValue).mockImplementation((setting: string) => {
|
||||
return settings[setting];
|
||||
});
|
||||
mocked(SettingsStore.setValue).mockImplementation(
|
||||
(settingName: string, roomId: string | null, level: SettingLevel, value: any): Promise<void> => {
|
||||
settings[settingName] = value;
|
||||
// we don't care about the parameters, just call the callbacks
|
||||
// @ts-ignore
|
||||
watchCallbacks.forEach((cb) => cb());
|
||||
return Promise.resolve();
|
||||
},
|
||||
);
|
||||
mocked(SettingsStore.isLevelSupported).mockReturnValue(true);
|
||||
mocked(SettingsStore.canSetValue).mockReturnValue(true);
|
||||
mocked(SettingsStore.watchSetting).mockImplementation((settingName: string, roomId: null, callback: any) => {
|
||||
watchCallbacks.push(callback);
|
||||
return "watcherId";
|
||||
});
|
||||
|
||||
releaseAnnouncementStore = new ReleaseAnnouncementStore();
|
||||
});
|
||||
|
||||
/**
|
||||
* Disables the release announcement feature.
|
||||
*/
|
||||
function disableReleaseAnnouncement() {
|
||||
settings["feature_release_announcement"] = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Listens to the next release announcement change event.
|
||||
*/
|
||||
function listenReleaseAnnouncementChanged() {
|
||||
return new Promise<Feature | null>((resolve) =>
|
||||
releaseAnnouncementStore.once("releaseAnnouncementChanged", resolve),
|
||||
);
|
||||
}
|
||||
|
||||
it("should be a singleton", () => {
|
||||
expect(ReleaseAnnouncementStore.instance).toBeDefined();
|
||||
});
|
||||
|
||||
it("should return null when the release announcement is disabled", async () => {
|
||||
disableReleaseAnnouncement();
|
||||
|
||||
expect(releaseAnnouncementStore.getReleaseAnnouncement()).toBeNull();
|
||||
|
||||
// Wait for the next release announcement change event
|
||||
const promise = listenReleaseAnnouncementChanged();
|
||||
// Call the next release announcement
|
||||
// because the release announcement is disabled, the next release announcement should be null
|
||||
await releaseAnnouncementStore.nextReleaseAnnouncement();
|
||||
expect(await promise).toBeNull();
|
||||
expect(releaseAnnouncementStore.getReleaseAnnouncement()).toBeNull();
|
||||
});
|
||||
|
||||
it("should return the next feature when the next release announcement is called", async () => {
|
||||
// Sanity check
|
||||
expect(releaseAnnouncementStore.getReleaseAnnouncement()).toBe("threadsActivityCentre");
|
||||
|
||||
let promise = listenReleaseAnnouncementChanged();
|
||||
await releaseAnnouncementStore.nextReleaseAnnouncement();
|
||||
|
||||
expect(await promise).toBe("pinningMessageList");
|
||||
expect(releaseAnnouncementStore.getReleaseAnnouncement()).toBe("pinningMessageList");
|
||||
|
||||
promise = listenReleaseAnnouncementChanged();
|
||||
await releaseAnnouncementStore.nextReleaseAnnouncement();
|
||||
|
||||
expect(await promise).toBeNull();
|
||||
expect(releaseAnnouncementStore.getReleaseAnnouncement()).toBeNull();
|
||||
|
||||
const secondStore = new ReleaseAnnouncementStore();
|
||||
// All the release announcements have been viewed, so it should be updated in the store account
|
||||
// The release announcement viewing states should be share among all instances (devices in the same account)
|
||||
expect(secondStore.getReleaseAnnouncement()).toBeNull();
|
||||
});
|
||||
|
||||
it("should listen to release announcement data changes in the store", async () => {
|
||||
const secondStore = new ReleaseAnnouncementStore();
|
||||
expect(secondStore.getReleaseAnnouncement()).toBe("threadsActivityCentre");
|
||||
|
||||
const promise = listenReleaseAnnouncementChanged();
|
||||
await secondStore.nextReleaseAnnouncement();
|
||||
|
||||
expect(await promise).toBe("pinningMessageList");
|
||||
expect(releaseAnnouncementStore.getReleaseAnnouncement()).toBe("pinningMessageList");
|
||||
});
|
||||
});
|
123
test/unit-tests/stores/RoomNotificationStateStore-test.ts
Normal file
123
test/unit-tests/stores/RoomNotificationStateStore-test.ts
Normal file
|
@ -0,0 +1,123 @@
|
|||
/*
|
||||
Copyright 2024 New Vector Ltd.
|
||||
Copyright 2023 The Matrix.org Foundation C.I.C.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { mocked } from "jest-mock";
|
||||
import { ClientEvent, MatrixClient, Room, SyncState } from "matrix-js-sdk/src/matrix";
|
||||
|
||||
import { createTestClient, setupAsyncStoreWithClient } from "../../test-utils";
|
||||
import {
|
||||
RoomNotificationStateStore,
|
||||
UPDATE_STATUS_INDICATOR,
|
||||
} from "../../../src/stores/notifications/RoomNotificationStateStore";
|
||||
import SettingsStore from "../../../src/settings/SettingsStore";
|
||||
import { MatrixDispatcher } from "../../../src/dispatcher/dispatcher";
|
||||
|
||||
describe("RoomNotificationStateStore", function () {
|
||||
let store: RoomNotificationStateStore;
|
||||
let client: MatrixClient;
|
||||
let dis: MatrixDispatcher;
|
||||
|
||||
beforeEach(() => {
|
||||
client = createTestClient();
|
||||
dis = new MatrixDispatcher();
|
||||
jest.resetAllMocks();
|
||||
store = RoomNotificationStateStore.testInstance(dis);
|
||||
store.emit = jest.fn();
|
||||
setupAsyncStoreWithClient(store, client);
|
||||
});
|
||||
|
||||
it("Emits no event when a room has no unreads", async () => {
|
||||
// Given a room with 0 unread messages
|
||||
const room = fakeRoom(0);
|
||||
|
||||
// When we sync and the room is visible
|
||||
mocked(client.getVisibleRooms).mockReturnValue([room]);
|
||||
client.emit(ClientEvent.Sync, SyncState.Syncing, SyncState.Syncing);
|
||||
|
||||
// Then we emit an event from the store
|
||||
expect(store.emit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("Emits an event when a room has unreads", async () => {
|
||||
// Given a room with 2 unread messages
|
||||
const room = fakeRoom(2);
|
||||
|
||||
// When we sync and the room is visible
|
||||
mocked(client.getVisibleRooms).mockReturnValue([room]);
|
||||
client.emit(ClientEvent.Sync, SyncState.Syncing, SyncState.Syncing);
|
||||
|
||||
// Then we emit an event from the store
|
||||
expect(store.emit).toHaveBeenCalledWith(UPDATE_STATUS_INDICATOR, expect.anything(), "SYNCING");
|
||||
});
|
||||
|
||||
it("Emits an event when a feature flag changes notification state", async () => {
|
||||
// Given we have synced already
|
||||
let room = fakeRoom(0);
|
||||
mocked(store.emit).mockReset();
|
||||
mocked(client.getVisibleRooms).mockReturnValue([room]);
|
||||
client.emit(ClientEvent.Sync, SyncState.Syncing, SyncState.Syncing);
|
||||
expect(store.emit).not.toHaveBeenCalled();
|
||||
|
||||
// When we update the feature flag and it makes us have a notification
|
||||
room = fakeRoom(2);
|
||||
mocked(client.getVisibleRooms).mockReturnValue([room]);
|
||||
jest.spyOn(SettingsStore, "getValue").mockReturnValue(true);
|
||||
store.emitUpdateIfStateChanged(SyncState.Syncing, false);
|
||||
|
||||
// Then we get notified
|
||||
expect(store.emit).toHaveBeenCalledWith(UPDATE_STATUS_INDICATOR, expect.anything(), "SYNCING");
|
||||
});
|
||||
|
||||
describe("If the feature_dynamic_room_predecessors is not enabled", () => {
|
||||
beforeEach(() => {
|
||||
// Turn off feature_dynamic_room_predecessors setting
|
||||
jest.spyOn(SettingsStore, "getValue").mockReturnValue(false);
|
||||
});
|
||||
|
||||
it("Passes the dynamic predecessor flag to getVisibleRooms", async () => {
|
||||
// When we sync
|
||||
mocked(client.getVisibleRooms).mockReturnValue([]);
|
||||
client.emit(ClientEvent.Sync, SyncState.Syncing, SyncState.Syncing);
|
||||
|
||||
// Then we check visible rooms, using the dynamic predecessor flag
|
||||
expect(client.getVisibleRooms).toHaveBeenCalledWith(false);
|
||||
expect(client.getVisibleRooms).not.toHaveBeenCalledWith(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("If the feature_dynamic_room_predecessors is enabled", () => {
|
||||
beforeEach(() => {
|
||||
// Turn on feature_dynamic_room_predecessors setting
|
||||
jest.spyOn(SettingsStore, "getValue").mockImplementation(
|
||||
(settingName) => settingName === "feature_dynamic_room_predecessors",
|
||||
);
|
||||
});
|
||||
|
||||
it("Passes the dynamic predecessor flag to getVisibleRooms", async () => {
|
||||
// When we sync
|
||||
mocked(client.getVisibleRooms).mockReturnValue([]);
|
||||
client.emit(ClientEvent.Sync, SyncState.Syncing, SyncState.Syncing);
|
||||
|
||||
// Then we check visible rooms, using the dynamic predecessor flag
|
||||
expect(client.getVisibleRooms).toHaveBeenCalledWith(true);
|
||||
expect(client.getVisibleRooms).not.toHaveBeenCalledWith(false);
|
||||
});
|
||||
});
|
||||
|
||||
let roomIdx = 0;
|
||||
|
||||
function fakeRoom(numUnreads: number): Room {
|
||||
roomIdx++;
|
||||
const ret = new Room(`room${roomIdx}`, client, "@user:example.com");
|
||||
ret.getPendingEvents = jest.fn().mockReturnValue([]);
|
||||
ret.isSpaceRoom = jest.fn().mockReturnValue(false);
|
||||
ret.getUnreadNotificationCount = jest.fn().mockReturnValue(numUnreads);
|
||||
ret.getRoomUnreadNotificationCount = jest.fn().mockReturnValue(numUnreads);
|
||||
return ret;
|
||||
}
|
||||
});
|
612
test/unit-tests/stores/RoomViewStore-test.ts
Normal file
612
test/unit-tests/stores/RoomViewStore-test.ts
Normal file
|
@ -0,0 +1,612 @@
|
|||
/*
|
||||
Copyright 2024 New Vector Ltd.
|
||||
Copyright 2017-2022 The Matrix.org Foundation C.I.C.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { mocked } from "jest-mock";
|
||||
import { MatrixError, Room } from "matrix-js-sdk/src/matrix";
|
||||
import { sleep } from "matrix-js-sdk/src/utils";
|
||||
import { RoomViewLifecycle, ViewRoomOpts } from "@matrix-org/react-sdk-module-api/lib/lifecycles/RoomViewLifecycle";
|
||||
|
||||
import { RoomViewStore } from "../../../src/stores/RoomViewStore";
|
||||
import { Action } from "../../../src/dispatcher/actions";
|
||||
import { getMockClientWithEventEmitter, untilDispatch, untilEmission } from "../../test-utils";
|
||||
import SettingsStore from "../../../src/settings/SettingsStore";
|
||||
import { SlidingSyncManager } from "../../../src/SlidingSyncManager";
|
||||
import { PosthogAnalytics } from "../../../src/PosthogAnalytics";
|
||||
import { TimelineRenderingType } from "../../../src/contexts/RoomContext";
|
||||
import { MatrixDispatcher } from "../../../src/dispatcher/dispatcher";
|
||||
import { UPDATE_EVENT } from "../../../src/stores/AsyncStore";
|
||||
import { ActiveRoomChangedPayload } from "../../../src/dispatcher/payloads/ActiveRoomChangedPayload";
|
||||
import { SpaceStoreClass } from "../../../src/stores/spaces/SpaceStore";
|
||||
import { TestSdkContext } from "../TestSdkContext";
|
||||
import { ViewRoomPayload } from "../../../src/dispatcher/payloads/ViewRoomPayload";
|
||||
import {
|
||||
VoiceBroadcastInfoState,
|
||||
VoiceBroadcastPlayback,
|
||||
VoiceBroadcastPlaybacksStore,
|
||||
VoiceBroadcastRecording,
|
||||
} from "../../../src/voice-broadcast";
|
||||
import { mkVoiceBroadcastInfoStateEvent } from "../voice-broadcast/utils/test-utils";
|
||||
import Modal from "../../../src/Modal";
|
||||
import ErrorDialog from "../../../src/components/views/dialogs/ErrorDialog";
|
||||
import { CancelAskToJoinPayload } from "../../../src/dispatcher/payloads/CancelAskToJoinPayload";
|
||||
import { JoinRoomErrorPayload } from "../../../src/dispatcher/payloads/JoinRoomErrorPayload";
|
||||
import { SubmitAskToJoinPayload } from "../../../src/dispatcher/payloads/SubmitAskToJoinPayload";
|
||||
import { ModuleRunner } from "../../../src/modules/ModuleRunner";
|
||||
|
||||
jest.mock("../../../src/Modal");
|
||||
|
||||
// mock out the injected classes
|
||||
jest.mock("../../../src/PosthogAnalytics");
|
||||
const MockPosthogAnalytics = <jest.Mock<PosthogAnalytics>>(<unknown>PosthogAnalytics);
|
||||
jest.mock("../../../src/SlidingSyncManager");
|
||||
const MockSlidingSyncManager = <jest.Mock<SlidingSyncManager>>(<unknown>SlidingSyncManager);
|
||||
jest.mock("../../../src/stores/spaces/SpaceStore");
|
||||
const MockSpaceStore = <jest.Mock<SpaceStoreClass>>(<unknown>SpaceStoreClass);
|
||||
|
||||
// mock VoiceRecording because it contains all the audio APIs
|
||||
jest.mock("../../../src/audio/VoiceRecording", () => ({
|
||||
VoiceRecording: jest.fn().mockReturnValue({
|
||||
disableMaxLength: jest.fn(),
|
||||
liveData: {
|
||||
onUpdate: jest.fn(),
|
||||
},
|
||||
off: jest.fn(),
|
||||
on: jest.fn(),
|
||||
start: jest.fn(),
|
||||
stop: jest.fn(),
|
||||
destroy: jest.fn(),
|
||||
contentType: "audio/ogg",
|
||||
}),
|
||||
}));
|
||||
|
||||
jest.mock("../../../src/utils/DMRoomMap", () => {
|
||||
const mock = {
|
||||
getUserIdForRoomId: jest.fn(),
|
||||
getDMRoomsForUserId: jest.fn(),
|
||||
};
|
||||
|
||||
return {
|
||||
shared: jest.fn().mockReturnValue(mock),
|
||||
sharedInstance: mock,
|
||||
};
|
||||
});
|
||||
|
||||
jest.mock("../../../src/stores/WidgetStore");
|
||||
jest.mock("../../../src/stores/widgets/WidgetLayoutStore");
|
||||
|
||||
describe("RoomViewStore", function () {
|
||||
const userId = "@alice:server";
|
||||
const roomId = "!randomcharacters:aser.ver";
|
||||
const roomId2 = "!room2:example.com";
|
||||
// we need to change the alias to ensure cache misses as the cache exists
|
||||
// through all tests.
|
||||
let alias = "#somealias2:aser.ver";
|
||||
const mockClient = getMockClientWithEventEmitter({
|
||||
joinRoom: jest.fn(),
|
||||
getRoom: jest.fn(),
|
||||
getRoomIdForAlias: jest.fn(),
|
||||
isGuest: jest.fn(),
|
||||
getUserId: jest.fn().mockReturnValue(userId),
|
||||
getSafeUserId: jest.fn().mockReturnValue(userId),
|
||||
getDeviceId: jest.fn().mockReturnValue("ABC123"),
|
||||
sendStateEvent: jest.fn().mockResolvedValue({}),
|
||||
supportsThreads: jest.fn(),
|
||||
isInitialSyncComplete: jest.fn().mockResolvedValue(false),
|
||||
relations: jest.fn(),
|
||||
knockRoom: jest.fn(),
|
||||
leave: jest.fn(),
|
||||
setRoomAccountData: jest.fn(),
|
||||
});
|
||||
const room = new Room(roomId, mockClient, userId);
|
||||
const room2 = new Room(roomId2, mockClient, userId);
|
||||
|
||||
const viewCall = async (): Promise<void> => {
|
||||
dis.dispatch<ViewRoomPayload>({
|
||||
action: Action.ViewRoom,
|
||||
room_id: roomId,
|
||||
view_call: true,
|
||||
metricsTrigger: undefined,
|
||||
});
|
||||
await untilDispatch(Action.ViewRoom, dis);
|
||||
};
|
||||
|
||||
const dispatchPromptAskToJoin = async () => {
|
||||
dis.dispatch({ action: Action.PromptAskToJoin });
|
||||
await untilDispatch(Action.PromptAskToJoin, dis);
|
||||
};
|
||||
|
||||
const dispatchSubmitAskToJoin = async (roomId: string, reason?: string) => {
|
||||
dis.dispatch<SubmitAskToJoinPayload>({ action: Action.SubmitAskToJoin, roomId, opts: { reason } });
|
||||
await untilDispatch(Action.SubmitAskToJoin, dis);
|
||||
};
|
||||
|
||||
const dispatchCancelAskToJoin = async (roomId: string) => {
|
||||
dis.dispatch<CancelAskToJoinPayload>({ action: Action.CancelAskToJoin, roomId });
|
||||
await untilDispatch(Action.CancelAskToJoin, dis);
|
||||
};
|
||||
|
||||
const dispatchRoomLoaded = async () => {
|
||||
dis.dispatch({ action: Action.RoomLoaded });
|
||||
await untilDispatch(Action.RoomLoaded, dis);
|
||||
};
|
||||
|
||||
let roomViewStore: RoomViewStore;
|
||||
let slidingSyncManager: SlidingSyncManager;
|
||||
let dis: MatrixDispatcher;
|
||||
let stores: TestSdkContext;
|
||||
|
||||
beforeEach(function () {
|
||||
jest.clearAllMocks();
|
||||
mockClient.credentials = { userId: userId };
|
||||
mockClient.joinRoom.mockResolvedValue(room);
|
||||
mockClient.getRoom.mockImplementation((roomId: string): Room | null => {
|
||||
if (roomId === room.roomId) return room;
|
||||
if (roomId === room2.roomId) return room2;
|
||||
return null;
|
||||
});
|
||||
mockClient.isGuest.mockReturnValue(false);
|
||||
mockClient.getSafeUserId.mockReturnValue(userId);
|
||||
|
||||
// Make the RVS to test
|
||||
dis = new MatrixDispatcher();
|
||||
slidingSyncManager = new MockSlidingSyncManager();
|
||||
stores = new TestSdkContext();
|
||||
stores.client = mockClient;
|
||||
stores._SlidingSyncManager = slidingSyncManager;
|
||||
stores._PosthogAnalytics = new MockPosthogAnalytics();
|
||||
stores._SpaceStore = new MockSpaceStore();
|
||||
stores._VoiceBroadcastPlaybacksStore = new VoiceBroadcastPlaybacksStore(stores.voiceBroadcastRecordingsStore);
|
||||
roomViewStore = new RoomViewStore(dis, stores);
|
||||
stores._RoomViewStore = roomViewStore;
|
||||
});
|
||||
|
||||
it("can be used to view a room by ID and join", async () => {
|
||||
dis.dispatch({ action: Action.ViewRoom, room_id: roomId });
|
||||
dis.dispatch({ action: Action.JoinRoom });
|
||||
await untilDispatch(Action.JoinRoomReady, dis);
|
||||
expect(mockClient.joinRoom).toHaveBeenCalledWith(roomId, { viaServers: [] });
|
||||
expect(roomViewStore.isJoining()).toBe(true);
|
||||
});
|
||||
|
||||
it("can auto-join a room", async () => {
|
||||
dis.dispatch({ action: Action.ViewRoom, room_id: roomId, auto_join: true });
|
||||
await untilDispatch(Action.JoinRoomReady, dis);
|
||||
expect(mockClient.joinRoom).toHaveBeenCalledWith(roomId, { viaServers: [] });
|
||||
expect(roomViewStore.isJoining()).toBe(true);
|
||||
});
|
||||
|
||||
it("emits ActiveRoomChanged when the viewed room changes", async () => {
|
||||
dis.dispatch({ action: Action.ViewRoom, room_id: roomId });
|
||||
let payload = (await untilDispatch(Action.ActiveRoomChanged, dis)) as ActiveRoomChangedPayload;
|
||||
expect(payload.newRoomId).toEqual(roomId);
|
||||
expect(payload.oldRoomId).toEqual(null);
|
||||
|
||||
dis.dispatch({ action: Action.ViewRoom, room_id: roomId2 });
|
||||
payload = (await untilDispatch(Action.ActiveRoomChanged, dis)) as ActiveRoomChangedPayload;
|
||||
expect(payload.newRoomId).toEqual(roomId2);
|
||||
expect(payload.oldRoomId).toEqual(roomId);
|
||||
});
|
||||
|
||||
it("invokes room activity listeners when the viewed room changes", async () => {
|
||||
const callback = jest.fn();
|
||||
roomViewStore.addRoomListener(roomId, callback);
|
||||
dis.dispatch({ action: Action.ViewRoom, room_id: roomId });
|
||||
(await untilDispatch(Action.ActiveRoomChanged, dis)) as ActiveRoomChangedPayload;
|
||||
expect(callback).toHaveBeenCalledWith(true);
|
||||
expect(callback).not.toHaveBeenCalledWith(false);
|
||||
|
||||
dis.dispatch({ action: Action.ViewRoom, room_id: roomId2 });
|
||||
(await untilDispatch(Action.ActiveRoomChanged, dis)) as ActiveRoomChangedPayload;
|
||||
expect(callback).toHaveBeenCalledWith(false);
|
||||
});
|
||||
|
||||
it("can be used to view a room by alias and join", async () => {
|
||||
mockClient.getRoomIdForAlias.mockResolvedValue({ room_id: roomId, servers: [] });
|
||||
dis.dispatch({ action: Action.ViewRoom, room_alias: alias });
|
||||
await untilDispatch((p) => {
|
||||
// wait for the re-dispatch with the room ID
|
||||
return p.action === Action.ViewRoom && p.room_id === roomId;
|
||||
}, dis);
|
||||
|
||||
// roomId is set to id of the room alias
|
||||
expect(roomViewStore.getRoomId()).toBe(roomId);
|
||||
|
||||
// join the room
|
||||
dis.dispatch({ action: Action.JoinRoom }, true);
|
||||
|
||||
await untilDispatch(Action.JoinRoomReady, dis);
|
||||
|
||||
expect(roomViewStore.isJoining()).toBeTruthy();
|
||||
expect(mockClient.joinRoom).toHaveBeenCalledWith(alias, { viaServers: [] });
|
||||
});
|
||||
|
||||
it("emits ViewRoomError if the alias lookup fails", async () => {
|
||||
alias = "#something-different:to-ensure-cache-miss";
|
||||
mockClient.getRoomIdForAlias.mockRejectedValue(new Error("network error or something"));
|
||||
dis.dispatch({ action: Action.ViewRoom, room_alias: alias });
|
||||
const payload = await untilDispatch(Action.ViewRoomError, dis);
|
||||
expect(payload.room_id).toBeNull();
|
||||
expect(payload.room_alias).toEqual(alias);
|
||||
expect(roomViewStore.getRoomAlias()).toEqual(alias);
|
||||
});
|
||||
|
||||
it("emits JoinRoomError if joining the room fails", async () => {
|
||||
const joinErr = new Error("network error or something");
|
||||
mockClient.joinRoom.mockRejectedValue(joinErr);
|
||||
dis.dispatch({ action: Action.ViewRoom, room_id: roomId });
|
||||
dis.dispatch({ action: Action.JoinRoom });
|
||||
await untilDispatch(Action.JoinRoomError, dis);
|
||||
expect(roomViewStore.isJoining()).toBe(false);
|
||||
expect(roomViewStore.getJoinError()).toEqual(joinErr);
|
||||
});
|
||||
|
||||
it("remembers the event being replied to when swapping rooms", async () => {
|
||||
dis.dispatch({ action: Action.ViewRoom, room_id: roomId });
|
||||
await untilDispatch(Action.ActiveRoomChanged, dis);
|
||||
const replyToEvent = {
|
||||
getRoomId: () => roomId,
|
||||
};
|
||||
dis.dispatch({ action: "reply_to_event", event: replyToEvent, context: TimelineRenderingType.Room });
|
||||
await untilEmission(roomViewStore, UPDATE_EVENT);
|
||||
expect(roomViewStore.getQuotingEvent()).toEqual(replyToEvent);
|
||||
// view the same room, should remember the event.
|
||||
// set the highlighed flag to make sure there is a state change so we get an update event
|
||||
dis.dispatch({ action: Action.ViewRoom, room_id: roomId, highlighted: true });
|
||||
await untilEmission(roomViewStore, UPDATE_EVENT);
|
||||
expect(roomViewStore.getQuotingEvent()).toEqual(replyToEvent);
|
||||
});
|
||||
|
||||
it("swaps to the replied event room if it is not the current room", async () => {
|
||||
dis.dispatch({ action: Action.ViewRoom, room_id: roomId });
|
||||
await untilDispatch(Action.ActiveRoomChanged, dis);
|
||||
const replyToEvent = {
|
||||
getRoomId: () => roomId2,
|
||||
};
|
||||
dis.dispatch({ action: "reply_to_event", event: replyToEvent, context: TimelineRenderingType.Room });
|
||||
await untilDispatch(Action.ViewRoom, dis);
|
||||
expect(roomViewStore.getQuotingEvent()).toEqual(replyToEvent);
|
||||
expect(roomViewStore.getRoomId()).toEqual(roomId2);
|
||||
});
|
||||
|
||||
it("should ignore reply_to_event for Thread panels", async () => {
|
||||
expect(roomViewStore.getQuotingEvent()).toBeFalsy();
|
||||
const replyToEvent = {
|
||||
getRoomId: () => roomId2,
|
||||
};
|
||||
dis.dispatch({ action: "reply_to_event", event: replyToEvent, context: TimelineRenderingType.Thread });
|
||||
await sleep(100);
|
||||
expect(roomViewStore.getQuotingEvent()).toBeFalsy();
|
||||
});
|
||||
|
||||
it.each([TimelineRenderingType.Room, TimelineRenderingType.File, TimelineRenderingType.Notification])(
|
||||
"Should respect reply_to_event for %s rendering context",
|
||||
async (context) => {
|
||||
const replyToEvent = {
|
||||
getRoomId: () => roomId,
|
||||
};
|
||||
dis.dispatch({ action: "reply_to_event", event: replyToEvent, context });
|
||||
await untilDispatch(Action.ViewRoom, dis);
|
||||
expect(roomViewStore.getQuotingEvent()).toEqual(replyToEvent);
|
||||
},
|
||||
);
|
||||
|
||||
it("removes the roomId on ViewHomePage", async () => {
|
||||
dis.dispatch({ action: Action.ViewRoom, room_id: roomId });
|
||||
await untilDispatch(Action.ActiveRoomChanged, dis);
|
||||
expect(roomViewStore.getRoomId()).toEqual(roomId);
|
||||
|
||||
dis.dispatch({ action: Action.ViewHomePage });
|
||||
await untilEmission(roomViewStore, UPDATE_EVENT);
|
||||
expect(roomViewStore.getRoomId()).toBeNull();
|
||||
});
|
||||
|
||||
it("when viewing a call without a broadcast, it should not raise an error", async () => {
|
||||
await viewCall();
|
||||
});
|
||||
|
||||
it("should display an error message when the room is unreachable via the roomId", async () => {
|
||||
// When
|
||||
// View and wait for the room
|
||||
dis.dispatch({ action: Action.ViewRoom, room_id: roomId });
|
||||
await untilDispatch(Action.ActiveRoomChanged, dis);
|
||||
// Generate error to display the expected error message
|
||||
const error = new MatrixError(undefined, 404);
|
||||
roomViewStore.showJoinRoomError(error, roomId);
|
||||
|
||||
// Check the modal props
|
||||
expect(mocked(Modal).createDialog.mock.calls[0][1]).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it("should display the generic error message when the roomId doesnt match", async () => {
|
||||
// When
|
||||
// Generate error to display the expected error message
|
||||
const error = new MatrixError({ error: "my 404 error" }, 404);
|
||||
roomViewStore.showJoinRoomError(error, roomId);
|
||||
|
||||
// Check the modal props
|
||||
expect(mocked(Modal).createDialog.mock.calls[0][1]).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it("clears the unread flag when viewing a room", async () => {
|
||||
room.getAccountData = jest.fn().mockReturnValue({
|
||||
getContent: jest.fn().mockReturnValue({ unread: true }),
|
||||
});
|
||||
dis.dispatch({ action: Action.ViewRoom, room_id: roomId });
|
||||
await untilDispatch(Action.ActiveRoomChanged, dis);
|
||||
expect(mockClient.setRoomAccountData).toHaveBeenCalledWith(roomId, "com.famedly.marked_unread", {
|
||||
unread: false,
|
||||
});
|
||||
});
|
||||
|
||||
describe("when listening to a voice broadcast", () => {
|
||||
let voiceBroadcastPlayback: VoiceBroadcastPlayback;
|
||||
|
||||
beforeEach(() => {
|
||||
voiceBroadcastPlayback = new VoiceBroadcastPlayback(
|
||||
mkVoiceBroadcastInfoStateEvent(
|
||||
roomId,
|
||||
VoiceBroadcastInfoState.Started,
|
||||
mockClient.getSafeUserId(),
|
||||
"d42",
|
||||
),
|
||||
mockClient,
|
||||
stores.voiceBroadcastRecordingsStore,
|
||||
);
|
||||
stores.voiceBroadcastPlaybacksStore.setCurrent(voiceBroadcastPlayback);
|
||||
jest.spyOn(voiceBroadcastPlayback, "pause").mockImplementation();
|
||||
});
|
||||
|
||||
it("and viewing a call it should pause the current broadcast", async () => {
|
||||
await viewCall();
|
||||
expect(voiceBroadcastPlayback.pause).toHaveBeenCalled();
|
||||
expect(roomViewStore.isViewingCall()).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("when recording a voice broadcast", () => {
|
||||
beforeEach(() => {
|
||||
stores.voiceBroadcastRecordingsStore.setCurrent(
|
||||
new VoiceBroadcastRecording(
|
||||
mkVoiceBroadcastInfoStateEvent(
|
||||
roomId,
|
||||
VoiceBroadcastInfoState.Started,
|
||||
mockClient.getSafeUserId(),
|
||||
"d42",
|
||||
),
|
||||
mockClient,
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it("and trying to view a call, it should not actually view it and show the info dialog", async () => {
|
||||
await viewCall();
|
||||
expect(Modal.createDialog).toMatchSnapshot();
|
||||
expect(roomViewStore.isViewingCall()).toBe(false);
|
||||
});
|
||||
|
||||
describe("and viewing a room with a broadcast", () => {
|
||||
beforeEach(async () => {
|
||||
const broadcastEvent = mkVoiceBroadcastInfoStateEvent(
|
||||
roomId2,
|
||||
VoiceBroadcastInfoState.Started,
|
||||
mockClient.getSafeUserId(),
|
||||
"ABC123",
|
||||
);
|
||||
room2.addLiveEvents([broadcastEvent]);
|
||||
|
||||
stores.voiceBroadcastPlaybacksStore.getByInfoEvent(broadcastEvent, mockClient);
|
||||
dis.dispatch({ action: Action.ViewRoom, room_id: roomId2 });
|
||||
await untilDispatch(Action.ActiveRoomChanged, dis);
|
||||
});
|
||||
|
||||
it("should continue recording", () => {
|
||||
expect(stores.voiceBroadcastPlaybacksStore.getCurrent()).toBeNull();
|
||||
expect(stores.voiceBroadcastRecordingsStore.getCurrent()?.getState()).toBe(
|
||||
VoiceBroadcastInfoState.Started,
|
||||
);
|
||||
});
|
||||
|
||||
describe("and stopping the recording", () => {
|
||||
beforeEach(async () => {
|
||||
await stores.voiceBroadcastRecordingsStore.getCurrent()?.stop();
|
||||
// check test precondition
|
||||
expect(stores.voiceBroadcastRecordingsStore.getCurrent()).toBeNull();
|
||||
});
|
||||
|
||||
it("should view the broadcast", () => {
|
||||
expect(stores.voiceBroadcastPlaybacksStore.getCurrent()?.infoEvent.getRoomId()).toBe(roomId2);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Sliding Sync", function () {
|
||||
beforeEach(() => {
|
||||
jest.spyOn(SettingsStore, "getValue").mockImplementation((settingName, roomId, value) => {
|
||||
return settingName === "feature_sliding_sync"; // this is enabled, everything else is disabled.
|
||||
});
|
||||
});
|
||||
|
||||
it("subscribes to the room", async () => {
|
||||
const setRoomVisible = jest
|
||||
.spyOn(slidingSyncManager, "setRoomVisible")
|
||||
.mockReturnValue(Promise.resolve(""));
|
||||
const subscribedRoomId = "!sub1:localhost";
|
||||
dis.dispatch({ action: Action.ViewRoom, room_id: subscribedRoomId });
|
||||
await untilDispatch(Action.ActiveRoomChanged, dis);
|
||||
expect(roomViewStore.getRoomId()).toBe(subscribedRoomId);
|
||||
expect(setRoomVisible).toHaveBeenCalledWith(subscribedRoomId, true);
|
||||
});
|
||||
|
||||
// Regression test for an in-the-wild bug where rooms would rapidly switch forever in sliding sync mode
|
||||
it("doesn't get stuck in a loop if you view rooms quickly", async () => {
|
||||
const setRoomVisible = jest
|
||||
.spyOn(slidingSyncManager, "setRoomVisible")
|
||||
.mockReturnValue(Promise.resolve(""));
|
||||
const subscribedRoomId = "!sub1:localhost";
|
||||
const subscribedRoomId2 = "!sub2:localhost";
|
||||
dis.dispatch({ action: Action.ViewRoom, room_id: subscribedRoomId }, true);
|
||||
dis.dispatch({ action: Action.ViewRoom, room_id: subscribedRoomId2 }, true);
|
||||
await untilDispatch(Action.ActiveRoomChanged, dis);
|
||||
// sub(1) then unsub(1) sub(2), unsub(1)
|
||||
const wantCalls = [
|
||||
[subscribedRoomId, true],
|
||||
[subscribedRoomId, false],
|
||||
[subscribedRoomId2, true],
|
||||
[subscribedRoomId, false],
|
||||
];
|
||||
expect(setRoomVisible).toHaveBeenCalledTimes(wantCalls.length);
|
||||
wantCalls.forEach((v, i) => {
|
||||
try {
|
||||
expect(setRoomVisible.mock.calls[i][0]).toEqual(v[0]);
|
||||
expect(setRoomVisible.mock.calls[i][1]).toEqual(v[1]);
|
||||
} catch (err) {
|
||||
throw new Error(`i=${i} got ${setRoomVisible.mock.calls[i]} want ${v}`);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Action.JoinRoom", () => {
|
||||
it("dispatches Action.JoinRoomError and Action.AskToJoin when the join fails", async () => {
|
||||
const err = new MatrixError();
|
||||
|
||||
jest.spyOn(dis, "dispatch");
|
||||
jest.spyOn(mockClient, "joinRoom").mockRejectedValueOnce(err);
|
||||
|
||||
dis.dispatch({ action: Action.JoinRoom, canAskToJoin: true });
|
||||
await untilDispatch(Action.PromptAskToJoin, dis);
|
||||
|
||||
expect(mocked(dis.dispatch).mock.calls[0][0]).toEqual({ action: "join_room", canAskToJoin: true });
|
||||
expect(mocked(dis.dispatch).mock.calls[1][0]).toEqual({
|
||||
action: "join_room_error",
|
||||
roomId: null,
|
||||
err,
|
||||
canAskToJoin: true,
|
||||
});
|
||||
expect(mocked(dis.dispatch).mock.calls[2][0]).toEqual({ action: "prompt_ask_to_join" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("Action.JoinRoomError", () => {
|
||||
const err = new MatrixError();
|
||||
beforeEach(() => jest.spyOn(roomViewStore, "showJoinRoomError"));
|
||||
|
||||
it("calls showJoinRoomError()", async () => {
|
||||
dis.dispatch<JoinRoomErrorPayload>({ action: Action.JoinRoomError, roomId, err });
|
||||
await untilDispatch(Action.JoinRoomError, dis);
|
||||
expect(roomViewStore.showJoinRoomError).toHaveBeenCalledWith(err, roomId);
|
||||
});
|
||||
|
||||
it("does not call showJoinRoomError() when canAskToJoin is true", async () => {
|
||||
dis.dispatch<JoinRoomErrorPayload>({ action: Action.JoinRoomError, roomId, err, canAskToJoin: true });
|
||||
await untilDispatch(Action.JoinRoomError, dis);
|
||||
expect(roomViewStore.showJoinRoomError).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("askToJoin()", () => {
|
||||
it("returns false", () => {
|
||||
expect(roomViewStore.promptAskToJoin()).toBe(false);
|
||||
});
|
||||
|
||||
it("returns true", async () => {
|
||||
await dispatchPromptAskToJoin();
|
||||
expect(roomViewStore.promptAskToJoin()).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Action.SubmitAskToJoin", () => {
|
||||
const reason = "some reason";
|
||||
beforeEach(async () => await dispatchPromptAskToJoin());
|
||||
|
||||
it("calls knockRoom() and sets promptAskToJoin state to false", async () => {
|
||||
jest.spyOn(mockClient, "knockRoom").mockResolvedValue({ room_id: roomId });
|
||||
await dispatchSubmitAskToJoin(roomId, reason);
|
||||
|
||||
expect(mockClient.knockRoom).toHaveBeenCalledWith(roomId, { reason, viaServers: [] });
|
||||
expect(roomViewStore.promptAskToJoin()).toBe(false);
|
||||
});
|
||||
|
||||
it("calls knockRoom(), sets promptAskToJoin state to false and shows an error dialog", async () => {
|
||||
const error = new MatrixError(undefined, 403);
|
||||
jest.spyOn(mockClient, "knockRoom").mockRejectedValue(error);
|
||||
await dispatchSubmitAskToJoin(roomId, reason);
|
||||
|
||||
expect(mockClient.knockRoom).toHaveBeenCalledWith(roomId, { reason, viaServers: [] });
|
||||
expect(roomViewStore.promptAskToJoin()).toBe(false);
|
||||
expect(Modal.createDialog).toHaveBeenCalledWith(ErrorDialog, {
|
||||
description: "You need an invite to access this room.",
|
||||
title: "Failed to join",
|
||||
});
|
||||
});
|
||||
|
||||
it("shows an error dialog with a generic error message", async () => {
|
||||
const error = new MatrixError();
|
||||
jest.spyOn(mockClient, "knockRoom").mockRejectedValue(error);
|
||||
await dispatchSubmitAskToJoin(roomId);
|
||||
|
||||
expect(Modal.createDialog).toHaveBeenCalledWith(ErrorDialog, {
|
||||
description: error.message,
|
||||
title: "Failed to join",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Action.CancelAskToJoin", () => {
|
||||
beforeEach(async () => {
|
||||
jest.spyOn(mockClient, "knockRoom").mockResolvedValue({ room_id: roomId });
|
||||
await dispatchSubmitAskToJoin(roomId);
|
||||
});
|
||||
|
||||
it("calls leave()", async () => {
|
||||
jest.spyOn(mockClient, "leave").mockResolvedValue({});
|
||||
await dispatchCancelAskToJoin(roomId);
|
||||
|
||||
expect(mockClient.leave).toHaveBeenCalledWith(roomId);
|
||||
});
|
||||
|
||||
it("calls leave() and shows an error dialog", async () => {
|
||||
const error = new MatrixError();
|
||||
jest.spyOn(mockClient, "leave").mockRejectedValue(error);
|
||||
await dispatchCancelAskToJoin(roomId);
|
||||
|
||||
expect(mockClient.leave).toHaveBeenCalledWith(roomId);
|
||||
expect(Modal.createDialog).toHaveBeenCalledWith(ErrorDialog, {
|
||||
description: error.message,
|
||||
title: "Failed to cancel",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("getViewRoomOpts", () => {
|
||||
it("returns viewRoomOpts", () => {
|
||||
expect(roomViewStore.getViewRoomOpts()).toEqual({ buttons: [] });
|
||||
});
|
||||
});
|
||||
|
||||
describe("Action.RoomLoaded", () => {
|
||||
it("updates viewRoomOpts", async () => {
|
||||
const buttons: ViewRoomOpts["buttons"] = [
|
||||
{
|
||||
icon: "test-icon",
|
||||
id: "test-id",
|
||||
label: () => "test-label",
|
||||
onClick: () => {},
|
||||
},
|
||||
];
|
||||
jest.spyOn(ModuleRunner.instance, "invoke").mockImplementation((lifecycleEvent, opts) => {
|
||||
if (lifecycleEvent === RoomViewLifecycle.ViewRoom) {
|
||||
opts.buttons = buttons;
|
||||
}
|
||||
});
|
||||
await dispatchRoomLoaded();
|
||||
expect(roomViewStore.getViewRoomOpts()).toEqual({ buttons });
|
||||
});
|
||||
});
|
||||
});
|
208
test/unit-tests/stores/SetupEncryptionStore-test.ts
Normal file
208
test/unit-tests/stores/SetupEncryptionStore-test.ts
Normal file
|
@ -0,0 +1,208 @@
|
|||
/*
|
||||
Copyright 2024 New Vector Ltd.
|
||||
Copyright 2023 The Matrix.org Foundation C.I.C.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { mocked, Mocked } from "jest-mock";
|
||||
import { IBootstrapCrossSigningOpts } from "matrix-js-sdk/src/crypto";
|
||||
import { MatrixClient, Device } from "matrix-js-sdk/src/matrix";
|
||||
import { SecretStorageKeyDescriptionAesV1, ServerSideSecretStorage } from "matrix-js-sdk/src/secret-storage";
|
||||
import { IDehydratedDevice } from "matrix-js-sdk/src/crypto/dehydration";
|
||||
import { CryptoApi, DeviceVerificationStatus } from "matrix-js-sdk/src/crypto-api";
|
||||
|
||||
import { SdkContextClass } from "../../../src/contexts/SDKContext";
|
||||
import { accessSecretStorage } from "../../../src/SecurityManager";
|
||||
import { SetupEncryptionStore } from "../../../src/stores/SetupEncryptionStore";
|
||||
import { emitPromise, stubClient } from "../../test-utils";
|
||||
|
||||
jest.mock("../../../src/SecurityManager", () => ({
|
||||
accessSecretStorage: jest.fn(),
|
||||
}));
|
||||
|
||||
describe("SetupEncryptionStore", () => {
|
||||
const cachedPassword = "p4assword";
|
||||
let client: Mocked<MatrixClient>;
|
||||
let mockCrypto: Mocked<CryptoApi>;
|
||||
let mockSecretStorage: Mocked<ServerSideSecretStorage>;
|
||||
let setupEncryptionStore: SetupEncryptionStore;
|
||||
|
||||
beforeEach(() => {
|
||||
client = mocked(stubClient());
|
||||
mockCrypto = {
|
||||
bootstrapCrossSigning: jest.fn(),
|
||||
getCrossSigningKeyId: jest.fn(),
|
||||
getVerificationRequestsToDeviceInProgress: jest.fn().mockReturnValue([]),
|
||||
getUserDeviceInfo: jest.fn(),
|
||||
getDeviceVerificationStatus: jest.fn(),
|
||||
isDehydrationSupported: jest.fn().mockResolvedValue(false),
|
||||
startDehydration: jest.fn(),
|
||||
} as unknown as Mocked<CryptoApi>;
|
||||
client.getCrypto.mockReturnValue(mockCrypto);
|
||||
|
||||
mockSecretStorage = {
|
||||
isStored: jest.fn(),
|
||||
} as unknown as Mocked<ServerSideSecretStorage>;
|
||||
Object.defineProperty(client, "secretStorage", { value: mockSecretStorage });
|
||||
|
||||
setupEncryptionStore = new SetupEncryptionStore();
|
||||
SdkContextClass.instance.accountPasswordStore.setPassword(cachedPassword);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
SdkContextClass.instance.accountPasswordStore.clearPassword();
|
||||
});
|
||||
|
||||
describe("start", () => {
|
||||
it("should fetch cross-signing and device info", async () => {
|
||||
const fakeKey = {} as SecretStorageKeyDescriptionAesV1;
|
||||
mockSecretStorage.isStored.mockResolvedValue({ sskeyid: fakeKey });
|
||||
|
||||
const fakeDevice = new Device({ deviceId: "deviceId", userId: "", algorithms: [], keys: new Map() });
|
||||
mockCrypto.getUserDeviceInfo.mockResolvedValue(
|
||||
new Map([[client.getSafeUserId(), new Map([[fakeDevice.deviceId, fakeDevice]])]]),
|
||||
);
|
||||
|
||||
setupEncryptionStore.start();
|
||||
await emitPromise(setupEncryptionStore, "update");
|
||||
|
||||
// our fake device is not signed, so we can't verify against it
|
||||
expect(setupEncryptionStore.hasDevicesToVerifyAgainst).toBe(false);
|
||||
|
||||
expect(setupEncryptionStore.keyId).toEqual("sskeyid");
|
||||
expect(setupEncryptionStore.keyInfo).toBe(fakeKey);
|
||||
});
|
||||
|
||||
it("should spot a signed device", async () => {
|
||||
mockSecretStorage.isStored.mockResolvedValue({ sskeyid: {} as SecretStorageKeyDescriptionAesV1 });
|
||||
|
||||
const fakeDevice = new Device({
|
||||
deviceId: "deviceId",
|
||||
userId: "",
|
||||
algorithms: [],
|
||||
keys: new Map([["curve25519:deviceId", "identityKey"]]),
|
||||
});
|
||||
mockCrypto.getUserDeviceInfo.mockResolvedValue(
|
||||
new Map([[client.getSafeUserId(), new Map([[fakeDevice.deviceId, fakeDevice]])]]),
|
||||
);
|
||||
mockCrypto.getDeviceVerificationStatus.mockResolvedValue(
|
||||
new DeviceVerificationStatus({ signedByOwner: true }),
|
||||
);
|
||||
|
||||
setupEncryptionStore.start();
|
||||
await emitPromise(setupEncryptionStore, "update");
|
||||
|
||||
expect(setupEncryptionStore.hasDevicesToVerifyAgainst).toBe(true);
|
||||
});
|
||||
|
||||
it("should ignore the MSC2697 dehydrated device", async () => {
|
||||
mockSecretStorage.isStored.mockResolvedValue({ sskeyid: {} as SecretStorageKeyDescriptionAesV1 });
|
||||
|
||||
client.getDehydratedDevice.mockResolvedValue({ device_id: "dehydrated" } as IDehydratedDevice);
|
||||
|
||||
const fakeDevice = new Device({
|
||||
deviceId: "dehydrated",
|
||||
userId: "",
|
||||
algorithms: [],
|
||||
keys: new Map([["curve25519:dehydrated", "identityKey"]]),
|
||||
});
|
||||
mockCrypto.getUserDeviceInfo.mockResolvedValue(
|
||||
new Map([[client.getSafeUserId(), new Map([[fakeDevice.deviceId, fakeDevice]])]]),
|
||||
);
|
||||
|
||||
setupEncryptionStore.start();
|
||||
await emitPromise(setupEncryptionStore, "update");
|
||||
|
||||
expect(setupEncryptionStore.hasDevicesToVerifyAgainst).toBe(false);
|
||||
expect(mockCrypto.getDeviceVerificationStatus).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should ignore the MSC3812 dehydrated device", async () => {
|
||||
mockSecretStorage.isStored.mockResolvedValue({ sskeyid: {} as SecretStorageKeyDescriptionAesV1 });
|
||||
|
||||
const fakeDevice = new Device({
|
||||
deviceId: "dehydrated",
|
||||
userId: "",
|
||||
algorithms: [],
|
||||
keys: new Map([["curve25519:dehydrated", "identityKey"]]),
|
||||
dehydrated: true,
|
||||
});
|
||||
mockCrypto.getUserDeviceInfo.mockResolvedValue(
|
||||
new Map([[client.getSafeUserId(), new Map([[fakeDevice.deviceId, fakeDevice]])]]),
|
||||
);
|
||||
|
||||
setupEncryptionStore.start();
|
||||
await emitPromise(setupEncryptionStore, "update");
|
||||
|
||||
expect(setupEncryptionStore.hasDevicesToVerifyAgainst).toBe(false);
|
||||
expect(mockCrypto.getDeviceVerificationStatus).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should correctly handle getUserDeviceInfo() returning an empty map", async () => {
|
||||
mockSecretStorage.isStored.mockResolvedValue({ sskeyid: {} as SecretStorageKeyDescriptionAesV1 });
|
||||
mockCrypto.getUserDeviceInfo.mockResolvedValue(new Map());
|
||||
|
||||
setupEncryptionStore.start();
|
||||
await emitPromise(setupEncryptionStore, "update");
|
||||
expect(setupEncryptionStore.hasDevicesToVerifyAgainst).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("usePassPhrase", () => {
|
||||
it("should use dehydration when enabled", async () => {
|
||||
// mocks for cross-signing and secret storage
|
||||
mockSecretStorage.isStored.mockResolvedValue({ sskeyid: {} as SecretStorageKeyDescriptionAesV1 });
|
||||
mockCrypto.getUserDeviceInfo.mockResolvedValue(new Map());
|
||||
mockCrypto.getDeviceVerificationStatus.mockResolvedValue(
|
||||
new DeviceVerificationStatus({ signedByOwner: true }),
|
||||
);
|
||||
mocked(accessSecretStorage).mockImplementation(async (func?: () => Promise<void>) => {
|
||||
await func!();
|
||||
});
|
||||
|
||||
// mocks for dehydration
|
||||
mockCrypto.isDehydrationSupported.mockResolvedValue(true);
|
||||
const dehydrationPromise = new Promise<void>((resolve) => {
|
||||
// Dehydration gets processed in the background, after
|
||||
// `usePassPhrase` returns, so we need to use a promise to make
|
||||
// sure that it is called.
|
||||
mockCrypto.startDehydration.mockImplementation(async () => {
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
client.waitForClientWellKnown.mockResolvedValue({ "org.matrix.msc3814": true });
|
||||
|
||||
setupEncryptionStore.start();
|
||||
await emitPromise(setupEncryptionStore, "update");
|
||||
|
||||
await setupEncryptionStore.usePassPhrase();
|
||||
|
||||
await dehydrationPromise;
|
||||
});
|
||||
});
|
||||
|
||||
it("resetConfirm should work with a cached account password", async () => {
|
||||
const makeRequest = jest.fn();
|
||||
mockCrypto.bootstrapCrossSigning.mockImplementation(async (opts: IBootstrapCrossSigningOpts) => {
|
||||
await opts?.authUploadDeviceSigningKeys?.(makeRequest);
|
||||
});
|
||||
mocked(accessSecretStorage).mockImplementation(async (func?: () => Promise<void>) => {
|
||||
await func!();
|
||||
});
|
||||
|
||||
await setupEncryptionStore.resetConfirm();
|
||||
|
||||
expect(mocked(accessSecretStorage)).toHaveBeenCalledWith(expect.any(Function), true);
|
||||
expect(makeRequest).toHaveBeenCalledWith({
|
||||
identifier: {
|
||||
type: "m.id.user",
|
||||
user: "@userId:matrix.org",
|
||||
},
|
||||
password: cachedPassword,
|
||||
type: "m.login.password",
|
||||
user: "@userId:matrix.org",
|
||||
});
|
||||
});
|
||||
});
|
1516
test/unit-tests/stores/SpaceStore-test.ts
Normal file
1516
test/unit-tests/stores/SpaceStore-test.ts
Normal file
File diff suppressed because it is too large
Load diff
138
test/unit-tests/stores/ToastStore-test.ts
Normal file
138
test/unit-tests/stores/ToastStore-test.ts
Normal file
|
@ -0,0 +1,138 @@
|
|||
/*
|
||||
Copyright 2024 New Vector Ltd.
|
||||
Copyright 2022 The Matrix.org Foundation C.I.C.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import GenericToast from "../../../src/components/views/toasts/GenericToast";
|
||||
import ToastStore, { IToast } from "../../../src/stores/ToastStore";
|
||||
|
||||
describe("ToastStore", () => {
|
||||
const makeToast = (priority: number, key?: string): IToast<typeof GenericToast> => ({
|
||||
key: key ?? `toast-${priority}`,
|
||||
title: "Test toast",
|
||||
component: GenericToast,
|
||||
priority,
|
||||
});
|
||||
|
||||
it("sets instance on window when doesnt exist", () => {
|
||||
const sharedInstance = ToastStore.sharedInstance();
|
||||
expect(sharedInstance).toBeTruthy();
|
||||
// using same instance
|
||||
expect(ToastStore.sharedInstance()).toBe(sharedInstance);
|
||||
});
|
||||
|
||||
describe("addOrReplaceToast()", () => {
|
||||
it("adds a toast to an empty store", () => {
|
||||
const toast = makeToast(1);
|
||||
const store = new ToastStore();
|
||||
const emitSpy = jest.spyOn(store, "emit");
|
||||
store.addOrReplaceToast(toast);
|
||||
expect(emitSpy).toHaveBeenCalledWith("update");
|
||||
expect(store.getToasts()).toEqual([toast]);
|
||||
});
|
||||
|
||||
it("inserts toast according to priority", () => {
|
||||
const toast1 = makeToast(1);
|
||||
const toast3a = makeToast(3, "a");
|
||||
const toast3b = makeToast(3, "b");
|
||||
const toast99 = makeToast(99);
|
||||
const store = new ToastStore();
|
||||
store.addOrReplaceToast(toast1);
|
||||
store.addOrReplaceToast(toast99);
|
||||
store.addOrReplaceToast(toast3a);
|
||||
store.addOrReplaceToast(toast3b);
|
||||
// ascending order, newest toast of given priority first
|
||||
expect(store.getToasts()).toEqual([toast99, toast3a, toast3b, toast1]);
|
||||
});
|
||||
|
||||
it("replaces toasts by key without changing order", () => {
|
||||
const toastA = makeToast(1, "a");
|
||||
const toastB = makeToast(3, "b");
|
||||
const toastC = makeToast(99, "c");
|
||||
const store = new ToastStore();
|
||||
store.addOrReplaceToast(toastA);
|
||||
store.addOrReplaceToast(toastC);
|
||||
store.addOrReplaceToast(toastB);
|
||||
expect(store.getToasts()).toEqual([toastC, toastB, toastA]);
|
||||
|
||||
const toastBNew = makeToast(5, "b");
|
||||
store.addOrReplaceToast(toastBNew);
|
||||
expect(store.getToasts()).toEqual([toastC, toastBNew, toastA]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("dismissToast()", () => {
|
||||
it("does nothing when there are no toasts", () => {
|
||||
const store = new ToastStore();
|
||||
const emitSpy = jest.spyOn(store, "emit");
|
||||
|
||||
store.dismissToast("whatever");
|
||||
|
||||
expect(store.getCountSeen()).toEqual(0);
|
||||
expect(emitSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("removes toast and emits", () => {
|
||||
const store = new ToastStore();
|
||||
const toastA = makeToast(1, "a");
|
||||
const toastB = makeToast(3, "b");
|
||||
store.addOrReplaceToast(toastA);
|
||||
store.addOrReplaceToast(toastB);
|
||||
const emitSpy = jest.spyOn(store, "emit");
|
||||
|
||||
store.dismissToast(toastA.key);
|
||||
|
||||
expect(store.getCountSeen()).toEqual(0);
|
||||
expect(emitSpy).toHaveBeenCalledWith("update");
|
||||
expect(store.getToasts()).toEqual([toastB]);
|
||||
});
|
||||
|
||||
it("increments countSeen when toast has bottom priority", () => {
|
||||
const store = new ToastStore();
|
||||
const toastA = makeToast(1, "a");
|
||||
const toastB = makeToast(3, "b");
|
||||
const toastC = makeToast(99, "c");
|
||||
store.addOrReplaceToast(toastA);
|
||||
store.addOrReplaceToast(toastC);
|
||||
store.addOrReplaceToast(toastB);
|
||||
const emitSpy = jest.spyOn(store, "emit");
|
||||
|
||||
store.dismissToast(toastC.key);
|
||||
|
||||
expect(store.getCountSeen()).toEqual(1);
|
||||
expect(emitSpy).toHaveBeenCalledWith("update");
|
||||
});
|
||||
|
||||
it("resets countSeen when no toasts remain", () => {
|
||||
const store = new ToastStore();
|
||||
const toastA = makeToast(1, "a");
|
||||
const toastB = makeToast(3, "b");
|
||||
store.addOrReplaceToast(toastA);
|
||||
store.addOrReplaceToast(toastB);
|
||||
|
||||
store.dismissToast(toastB.key);
|
||||
expect(store.getCountSeen()).toEqual(1);
|
||||
store.dismissToast(toastA.key);
|
||||
expect(store.getCountSeen()).toEqual(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("reset()", () => {
|
||||
it("clears countseen and toasts", () => {
|
||||
const store = new ToastStore();
|
||||
const toastA = makeToast(1, "a");
|
||||
const toastB = makeToast(3, "b");
|
||||
store.addOrReplaceToast(toastA);
|
||||
store.addOrReplaceToast(toastB);
|
||||
// increment count seen
|
||||
store.dismissToast(toastB.key);
|
||||
|
||||
store.reset();
|
||||
expect(store.getCountSeen()).toEqual(0);
|
||||
expect(store.getToasts()).toEqual([]);
|
||||
});
|
||||
});
|
||||
});
|
78
test/unit-tests/stores/TypingStore-test.ts
Normal file
78
test/unit-tests/stores/TypingStore-test.ts
Normal file
|
@ -0,0 +1,78 @@
|
|||
/*
|
||||
Copyright 2024 New Vector Ltd.
|
||||
Copyright 2022 The Matrix.org Foundation C.I.C.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { MatrixClient } from "matrix-js-sdk/src/matrix";
|
||||
|
||||
import TypingStore from "../../../src/stores/TypingStore";
|
||||
import { LOCAL_ROOM_ID_PREFIX } from "../../../src/models/LocalRoom";
|
||||
import SettingsStore from "../../../src/settings/SettingsStore";
|
||||
import { TestSdkContext } from "../TestSdkContext";
|
||||
|
||||
jest.mock("../../../src/settings/SettingsStore", () => ({
|
||||
getValue: jest.fn(),
|
||||
monitorSetting: jest.fn(),
|
||||
watchSetting: jest.fn(),
|
||||
}));
|
||||
|
||||
describe("TypingStore", () => {
|
||||
let typingStore: TypingStore;
|
||||
let mockClient: MatrixClient;
|
||||
const roomId = "!test:example.com";
|
||||
const localRoomId = LOCAL_ROOM_ID_PREFIX + "test";
|
||||
|
||||
beforeEach(() => {
|
||||
mockClient = {
|
||||
sendTyping: jest.fn(),
|
||||
} as unknown as MatrixClient;
|
||||
const context = new TestSdkContext();
|
||||
context.client = mockClient;
|
||||
typingStore = new TypingStore(context);
|
||||
jest.spyOn(SettingsStore, "getValue").mockImplementation((name: string) => {
|
||||
return name === "sendTypingNotifications";
|
||||
});
|
||||
});
|
||||
|
||||
describe("setSelfTyping", () => {
|
||||
it("shouldn't do anything for a local room", () => {
|
||||
typingStore.setSelfTyping(localRoomId, null, true);
|
||||
expect(mockClient.sendTyping).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
describe("in typing state true", () => {
|
||||
beforeEach(() => {
|
||||
typingStore.setSelfTyping(roomId, null, true);
|
||||
});
|
||||
|
||||
it("should change to false when setting false", () => {
|
||||
typingStore.setSelfTyping(roomId, null, false);
|
||||
expect(mockClient.sendTyping).toHaveBeenCalledWith(roomId, false, 30000);
|
||||
});
|
||||
|
||||
it("should change to true when setting true", () => {
|
||||
typingStore.setSelfTyping(roomId, null, true);
|
||||
expect(mockClient.sendTyping).toHaveBeenCalledWith(roomId, true, 30000);
|
||||
});
|
||||
});
|
||||
|
||||
describe("in typing state false", () => {
|
||||
beforeEach(() => {
|
||||
typingStore.setSelfTyping(roomId, null, false);
|
||||
});
|
||||
|
||||
it("shouldn't change when setting false", () => {
|
||||
typingStore.setSelfTyping(roomId, null, false);
|
||||
expect(mockClient.sendTyping).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should change to true when setting true", () => {
|
||||
typingStore.setSelfTyping(roomId, null, true);
|
||||
expect(mockClient.sendTyping).toHaveBeenCalledWith(roomId, true, 30000);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
201
test/unit-tests/stores/UserProfilesStore-test.ts
Normal file
201
test/unit-tests/stores/UserProfilesStore-test.ts
Normal file
|
@ -0,0 +1,201 @@
|
|||
/*
|
||||
Copyright 2024 New Vector Ltd.
|
||||
Copyright 2023 The Matrix.org Foundation C.I.C.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { mocked, Mocked } from "jest-mock";
|
||||
import {
|
||||
IMatrixProfile,
|
||||
MatrixClient,
|
||||
MatrixError,
|
||||
MatrixEvent,
|
||||
Room,
|
||||
RoomMemberEvent,
|
||||
} from "matrix-js-sdk/src/matrix";
|
||||
|
||||
import { UserProfilesStore } from "../../../src/stores/UserProfilesStore";
|
||||
import { filterConsole, mkRoomMember, mkRoomMemberJoinEvent, stubClient } from "../../test-utils";
|
||||
|
||||
describe("UserProfilesStore", () => {
|
||||
const userIdDoesNotExist = "@unknown:example.com";
|
||||
const userDoesNotExistError = new MatrixError({
|
||||
errcode: "M_NOT_FOUND",
|
||||
error: "Profile not found",
|
||||
});
|
||||
|
||||
const user1Id = "@user1:example.com";
|
||||
const user1Profile: IMatrixProfile = { displayname: "User 1", avatar_url: undefined };
|
||||
const user2Id = "@user2:example.com";
|
||||
const user2Profile: IMatrixProfile = { displayname: "User 2", avatar_url: undefined };
|
||||
const user3Id = "@user3:example.com";
|
||||
let mockClient: Mocked<MatrixClient>;
|
||||
let userProfilesStore: UserProfilesStore;
|
||||
let room: Room;
|
||||
|
||||
filterConsole(
|
||||
"Error retrieving profile for userId @unknown:example.com",
|
||||
"Error retrieving profile for userId @user3:example.com",
|
||||
);
|
||||
|
||||
beforeEach(() => {
|
||||
mockClient = mocked(stubClient());
|
||||
room = new Room("!room:example.com", mockClient, mockClient.getSafeUserId());
|
||||
room.currentState.setStateEvents([
|
||||
mkRoomMemberJoinEvent(user2Id, room.roomId),
|
||||
mkRoomMemberJoinEvent(user3Id, room.roomId),
|
||||
]);
|
||||
mockClient.getRooms.mockReturnValue([room]);
|
||||
userProfilesStore = new UserProfilesStore(mockClient);
|
||||
|
||||
mockClient.getProfileInfo.mockImplementation(async (userId: string) => {
|
||||
if (userId === user1Id) return user1Profile;
|
||||
if (userId === user2Id) return user2Profile;
|
||||
|
||||
throw userDoesNotExistError;
|
||||
});
|
||||
});
|
||||
|
||||
it("getProfile should return undefined if the profile was not fetched", () => {
|
||||
expect(userProfilesStore.getProfile(user1Id)).toBeUndefined();
|
||||
});
|
||||
|
||||
describe("fetchProfile", () => {
|
||||
it("should return the profile from the API and cache it", async () => {
|
||||
const profile = await userProfilesStore.fetchProfile(user1Id);
|
||||
expect(profile).toBe(user1Profile);
|
||||
expect(userProfilesStore.getProfile(user1Id)).toBe(user1Profile);
|
||||
});
|
||||
|
||||
it("when shouldThrow = true and there is an error it should raise an error", async () => {
|
||||
await expect(userProfilesStore.fetchProfile(userIdDoesNotExist, { shouldThrow: true })).rejects.toThrow(
|
||||
userDoesNotExistError.message,
|
||||
);
|
||||
});
|
||||
|
||||
describe("when fetching a profile that does not exist", () => {
|
||||
let profile: IMatrixProfile | null | undefined;
|
||||
|
||||
beforeEach(async () => {
|
||||
profile = await userProfilesStore.fetchProfile(userIdDoesNotExist);
|
||||
});
|
||||
|
||||
it("should return null", () => {
|
||||
expect(profile).toBeNull();
|
||||
});
|
||||
|
||||
it("should cache the error and result", () => {
|
||||
expect(userProfilesStore.getProfile(userIdDoesNotExist)).toBeNull();
|
||||
expect(userProfilesStore.getProfileLookupError(userIdDoesNotExist)).toBe(userDoesNotExistError);
|
||||
});
|
||||
|
||||
describe("when the profile does not exist and fetching it again", () => {
|
||||
beforeEach(async () => {
|
||||
mockClient.getProfileInfo.mockResolvedValue(user1Profile);
|
||||
profile = await userProfilesStore.fetchProfile(userIdDoesNotExist);
|
||||
});
|
||||
|
||||
it("should return the profile", () => {
|
||||
expect(profile).toBe(user1Profile);
|
||||
});
|
||||
|
||||
it("should clear the error", () => {
|
||||
expect(userProfilesStore.getProfileLookupError(userIdDoesNotExist)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("getOrFetchProfile", () => {
|
||||
it("should return a profile from the API and cache it", async () => {
|
||||
const profile = await userProfilesStore.getOrFetchProfile(user1Id);
|
||||
expect(profile).toBe(user1Profile);
|
||||
// same method again
|
||||
expect(await userProfilesStore.getOrFetchProfile(user1Id)).toBe(user1Profile);
|
||||
// assert that the profile is cached
|
||||
expect(userProfilesStore.getProfile(user1Id)).toBe(user1Profile);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getProfileLookupError", () => {
|
||||
it("should return undefined if a profile was not fetched", () => {
|
||||
expect(userProfilesStore.getProfileLookupError(user1Id)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should return undefined if a profile was successfully fetched", async () => {
|
||||
await userProfilesStore.fetchProfile(user1Id);
|
||||
expect(userProfilesStore.getProfileLookupError(user1Id)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should return the error if there was one", async () => {
|
||||
await userProfilesStore.fetchProfile(userIdDoesNotExist);
|
||||
expect(userProfilesStore.getProfileLookupError(userIdDoesNotExist)).toBe(userDoesNotExistError);
|
||||
});
|
||||
});
|
||||
|
||||
it("getOnlyKnownProfile should return undefined if the profile was not fetched", () => {
|
||||
expect(userProfilesStore.getOnlyKnownProfile(user1Id)).toBeUndefined();
|
||||
});
|
||||
|
||||
describe("fetchOnlyKnownProfile", () => {
|
||||
it("should return undefined if no room shared with the user", async () => {
|
||||
const profile = await userProfilesStore.fetchOnlyKnownProfile(user1Id);
|
||||
expect(profile).toBeUndefined();
|
||||
expect(userProfilesStore.getOnlyKnownProfile(user1Id)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("for a known user should return the profile from the API and cache it", async () => {
|
||||
const profile = await userProfilesStore.fetchOnlyKnownProfile(user2Id);
|
||||
expect(profile).toBe(user2Profile);
|
||||
expect(userProfilesStore.getOnlyKnownProfile(user2Id)).toBe(user2Profile);
|
||||
});
|
||||
|
||||
it("for a known user not found via API should return null and cache it", async () => {
|
||||
const profile = await userProfilesStore.fetchOnlyKnownProfile(user3Id);
|
||||
expect(profile).toBeNull();
|
||||
expect(userProfilesStore.getOnlyKnownProfile(user3Id)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("when there are cached values and membership updates", () => {
|
||||
beforeEach(async () => {
|
||||
await userProfilesStore.fetchProfile(user1Id);
|
||||
await userProfilesStore.fetchOnlyKnownProfile(user2Id);
|
||||
});
|
||||
|
||||
describe("and membership events with the same values appear", () => {
|
||||
beforeEach(() => {
|
||||
const roomMember1 = mkRoomMember(room.roomId, user1Id);
|
||||
roomMember1.rawDisplayName = user1Profile.displayname!;
|
||||
roomMember1.getMxcAvatarUrl = () => undefined;
|
||||
mockClient.emit(RoomMemberEvent.Membership, {} as MatrixEvent, roomMember1);
|
||||
|
||||
const roomMember2 = mkRoomMember(room.roomId, user2Id);
|
||||
roomMember2.rawDisplayName = user2Profile.displayname!;
|
||||
roomMember2.getMxcAvatarUrl = () => undefined;
|
||||
mockClient.emit(RoomMemberEvent.Membership, {} as MatrixEvent, roomMember2);
|
||||
});
|
||||
|
||||
it("should not invalidate the cache", () => {
|
||||
expect(userProfilesStore.getProfile(user1Id)).toBe(user1Profile);
|
||||
expect(userProfilesStore.getOnlyKnownProfile(user2Id)).toBe(user2Profile);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("flush", () => {
|
||||
it("should clear profiles, known profiles and errors", async () => {
|
||||
await userProfilesStore.fetchOnlyKnownProfile(user1Id);
|
||||
await userProfilesStore.fetchProfile(user1Id);
|
||||
await userProfilesStore.fetchProfile(userIdDoesNotExist);
|
||||
|
||||
userProfilesStore.flush();
|
||||
|
||||
expect(userProfilesStore.getProfile(user1Id)).toBeUndefined();
|
||||
expect(userProfilesStore.getOnlyKnownProfile(user1Id)).toBeUndefined();
|
||||
expect(userProfilesStore.getProfileLookupError(userIdDoesNotExist)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
});
|
95
test/unit-tests/stores/VoiceRecordingStore-test.ts
Normal file
95
test/unit-tests/stores/VoiceRecordingStore-test.ts
Normal file
|
@ -0,0 +1,95 @@
|
|||
/*
|
||||
Copyright 2024 New Vector Ltd.
|
||||
Copyright 2022 The Matrix.org Foundation C.I.C.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { MatrixClient } from "matrix-js-sdk/src/matrix";
|
||||
|
||||
import { VoiceRecordingStore } from "../../../src/stores/VoiceRecordingStore";
|
||||
import { MatrixClientPeg } from "../../../src/MatrixClientPeg";
|
||||
import { flushPromises } from "../../test-utils";
|
||||
import { VoiceMessageRecording } from "../../../src/audio/VoiceMessageRecording";
|
||||
|
||||
const stubClient = {} as unknown as MatrixClient;
|
||||
jest.spyOn(MatrixClientPeg, "get").mockReturnValue(stubClient);
|
||||
|
||||
describe("VoiceRecordingStore", () => {
|
||||
const room1Id = "!room1:server.org";
|
||||
const room2Id = "!room2:server.org";
|
||||
const room3Id = "!room3:server.org";
|
||||
const room1Recording = { destroy: jest.fn() } as unknown as VoiceMessageRecording;
|
||||
const room2Recording = { destroy: jest.fn() } as unknown as VoiceMessageRecording;
|
||||
|
||||
const state: Record<string, VoiceMessageRecording | undefined> = {
|
||||
[room1Id]: room1Recording,
|
||||
[room2Id]: room2Recording,
|
||||
[room3Id]: undefined,
|
||||
};
|
||||
|
||||
const mkStore = (): VoiceRecordingStore => {
|
||||
const store = new VoiceRecordingStore();
|
||||
store.start();
|
||||
return store;
|
||||
};
|
||||
|
||||
describe("startRecording()", () => {
|
||||
it("throws when roomId is falsy", () => {
|
||||
const store = mkStore();
|
||||
expect(() => store.startRecording(undefined)).toThrow("Recording must be associated with a room");
|
||||
});
|
||||
|
||||
it("throws when room already has a recording", () => {
|
||||
const store = mkStore();
|
||||
// @ts-ignore
|
||||
store.storeState = state;
|
||||
expect(() => store.startRecording(room2Id)).toThrow("A recording is already in progress");
|
||||
});
|
||||
|
||||
it("creates and adds recording to state", async () => {
|
||||
const store = mkStore();
|
||||
const result = store.startRecording(room2Id);
|
||||
|
||||
await flushPromises();
|
||||
|
||||
expect(result).toBeInstanceOf(VoiceMessageRecording);
|
||||
expect(store.getActiveRecording(room2Id)).toEqual(result);
|
||||
});
|
||||
});
|
||||
|
||||
describe("disposeRecording()", () => {
|
||||
it("destroys recording for a room if it exists in state", async () => {
|
||||
const store = mkStore();
|
||||
// @ts-ignore
|
||||
store.storeState = state;
|
||||
|
||||
await store.disposeRecording(room1Id);
|
||||
|
||||
expect(room1Recording.destroy).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("removes room from state when it has a recording", async () => {
|
||||
const store = mkStore();
|
||||
// @ts-ignore
|
||||
store.storeState = state;
|
||||
|
||||
await store.disposeRecording(room2Id);
|
||||
|
||||
expect(store.getActiveRecording(room2Id)).toBeFalsy();
|
||||
});
|
||||
|
||||
it("removes room from state when it has a falsy recording", async () => {
|
||||
const store = mkStore();
|
||||
// @ts-ignore
|
||||
store.storeState = state;
|
||||
|
||||
await store.disposeRecording(room3Id);
|
||||
|
||||
expect(store.getActiveRecording(room1Id)).toEqual(room1Recording);
|
||||
expect(store.getActiveRecording(room2Id)).toEqual(room2Recording);
|
||||
expect(store.getActiveRecording(room3Id)).toBeFalsy();
|
||||
});
|
||||
});
|
||||
});
|
321
test/unit-tests/stores/WidgetLayoutStore-test.ts
Normal file
321
test/unit-tests/stores/WidgetLayoutStore-test.ts
Normal file
|
@ -0,0 +1,321 @@
|
|||
/*
|
||||
Copyright 2024 New Vector Ltd.
|
||||
Copyright 2021 The Matrix.org Foundation C.I.C.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { MatrixClient, Room } from "matrix-js-sdk/src/matrix";
|
||||
import { mocked } from "jest-mock";
|
||||
|
||||
import WidgetStore, { IApp } from "../../../src/stores/WidgetStore";
|
||||
import { Container, WidgetLayoutStore } from "../../../src/stores/widgets/WidgetLayoutStore";
|
||||
import { stubClient } from "../../test-utils";
|
||||
import defaultDispatcher from "../../../src/dispatcher/dispatcher";
|
||||
import SettingsStore from "../../../src/settings/SettingsStore";
|
||||
|
||||
// setup test env values
|
||||
const roomId = "!room:server";
|
||||
|
||||
describe("WidgetLayoutStore", () => {
|
||||
let client: MatrixClient;
|
||||
let store: WidgetLayoutStore;
|
||||
let roomUpdateListener: (event: string) => void;
|
||||
let mockApps: IApp[];
|
||||
let mockRoom: Room;
|
||||
let layoutEventContent: Record<string, any> | null;
|
||||
|
||||
beforeEach(() => {
|
||||
layoutEventContent = null;
|
||||
mockRoom = <Room>{
|
||||
roomId: roomId,
|
||||
currentState: {
|
||||
getStateEvents: (_l, _x) => {
|
||||
return {
|
||||
getId: () => "$layoutEventId",
|
||||
getContent: () => layoutEventContent,
|
||||
};
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
mockApps = [
|
||||
<IApp>{ roomId: roomId, id: "1" },
|
||||
<IApp>{ roomId: roomId, id: "2" },
|
||||
<IApp>{ roomId: roomId, id: "3" },
|
||||
<IApp>{ roomId: roomId, id: "4" },
|
||||
];
|
||||
|
||||
// fake the WidgetStore.instance to just return an object with `getApps`
|
||||
jest.spyOn(WidgetStore, "instance", "get").mockReturnValue({
|
||||
on: jest.fn(),
|
||||
off: jest.fn(),
|
||||
getApps: () => mockApps,
|
||||
} as unknown as WidgetStore);
|
||||
|
||||
SettingsStore.reset();
|
||||
});
|
||||
|
||||
beforeAll(() => {
|
||||
// we need to init a client so it does not error, when asking for DeviceStorage handlers (SettingsStore.setValue("Widgets.layout"))
|
||||
client = stubClient();
|
||||
|
||||
roomUpdateListener = jest.fn();
|
||||
// @ts-ignore bypass private ctor for tests
|
||||
store = new WidgetLayoutStore();
|
||||
store.addListener(`update_${roomId}`, roomUpdateListener);
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
store.removeListener(`update_${roomId}`, roomUpdateListener);
|
||||
});
|
||||
|
||||
it("all widgets should be in the right container by default", () => {
|
||||
store.recalculateRoom(mockRoom);
|
||||
expect(store.getContainerWidgets(mockRoom, Container.Right).length).toStrictEqual(mockApps.length);
|
||||
});
|
||||
|
||||
it("add widget to top container", async () => {
|
||||
store.recalculateRoom(mockRoom);
|
||||
store.moveToContainer(mockRoom, mockApps[0], Container.Top);
|
||||
expect(store.getContainerWidgets(mockRoom, Container.Top)).toStrictEqual([mockApps[0]]);
|
||||
expect(store.getContainerHeight(mockRoom, Container.Top)).toBeNull();
|
||||
});
|
||||
|
||||
it("ordering of top container widgets should be consistent even if no index specified", async () => {
|
||||
layoutEventContent = {
|
||||
widgets: {
|
||||
"1": {
|
||||
container: "top",
|
||||
},
|
||||
"2": {
|
||||
container: "top",
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
store.recalculateRoom(mockRoom);
|
||||
expect(store.getContainerWidgets(mockRoom, Container.Top)).toStrictEqual([mockApps[0], mockApps[1]]);
|
||||
});
|
||||
|
||||
it("add three widgets to top container", async () => {
|
||||
store.recalculateRoom(mockRoom);
|
||||
store.moveToContainer(mockRoom, mockApps[0], Container.Top);
|
||||
store.moveToContainer(mockRoom, mockApps[1], Container.Top);
|
||||
store.moveToContainer(mockRoom, mockApps[2], Container.Top);
|
||||
expect(new Set(store.getContainerWidgets(mockRoom, Container.Top))).toEqual(
|
||||
new Set([mockApps[0], mockApps[1], mockApps[2]]),
|
||||
);
|
||||
});
|
||||
|
||||
it("cannot add more than three widgets to top container", async () => {
|
||||
store.recalculateRoom(mockRoom);
|
||||
store.moveToContainer(mockRoom, mockApps[0], Container.Top);
|
||||
store.moveToContainer(mockRoom, mockApps[1], Container.Top);
|
||||
store.moveToContainer(mockRoom, mockApps[2], Container.Top);
|
||||
expect(store.canAddToContainer(mockRoom, Container.Top)).toEqual(false);
|
||||
});
|
||||
|
||||
it("remove pins when maximising (other widget)", async () => {
|
||||
store.recalculateRoom(mockRoom);
|
||||
store.moveToContainer(mockRoom, mockApps[0], Container.Top);
|
||||
store.moveToContainer(mockRoom, mockApps[1], Container.Top);
|
||||
store.moveToContainer(mockRoom, mockApps[2], Container.Top);
|
||||
store.moveToContainer(mockRoom, mockApps[3], Container.Center);
|
||||
expect(store.getContainerWidgets(mockRoom, Container.Top)).toEqual([]);
|
||||
expect(new Set(store.getContainerWidgets(mockRoom, Container.Right))).toEqual(
|
||||
new Set([mockApps[0], mockApps[1], mockApps[2]]),
|
||||
);
|
||||
expect(store.getContainerWidgets(mockRoom, Container.Center)).toEqual([mockApps[3]]);
|
||||
});
|
||||
|
||||
it("remove pins when maximising (one of the pinned widgets)", async () => {
|
||||
store.recalculateRoom(mockRoom);
|
||||
store.moveToContainer(mockRoom, mockApps[0], Container.Top);
|
||||
store.moveToContainer(mockRoom, mockApps[1], Container.Top);
|
||||
store.moveToContainer(mockRoom, mockApps[2], Container.Top);
|
||||
store.moveToContainer(mockRoom, mockApps[0], Container.Center);
|
||||
expect(store.getContainerWidgets(mockRoom, Container.Top)).toEqual([]);
|
||||
expect(store.getContainerWidgets(mockRoom, Container.Center)).toEqual([mockApps[0]]);
|
||||
expect(new Set(store.getContainerWidgets(mockRoom, Container.Right))).toEqual(
|
||||
new Set([mockApps[1], mockApps[2], mockApps[3]]),
|
||||
);
|
||||
});
|
||||
|
||||
it("remove maximised when pinning (other widget)", async () => {
|
||||
store.recalculateRoom(mockRoom);
|
||||
store.moveToContainer(mockRoom, mockApps[0], Container.Center);
|
||||
store.moveToContainer(mockRoom, mockApps[1], Container.Top);
|
||||
expect(store.getContainerWidgets(mockRoom, Container.Top)).toEqual([mockApps[1]]);
|
||||
expect(store.getContainerWidgets(mockRoom, Container.Center)).toEqual([]);
|
||||
expect(new Set(store.getContainerWidgets(mockRoom, Container.Right))).toEqual(
|
||||
new Set([mockApps[2], mockApps[3], mockApps[0]]),
|
||||
);
|
||||
});
|
||||
|
||||
it("remove maximised when pinning (same widget)", async () => {
|
||||
store.recalculateRoom(mockRoom);
|
||||
store.moveToContainer(mockRoom, mockApps[0], Container.Center);
|
||||
store.moveToContainer(mockRoom, mockApps[0], Container.Top);
|
||||
expect(store.getContainerWidgets(mockRoom, Container.Top)).toEqual([mockApps[0]]);
|
||||
expect(store.getContainerWidgets(mockRoom, Container.Center)).toEqual([]);
|
||||
expect(new Set(store.getContainerWidgets(mockRoom, Container.Right))).toEqual(
|
||||
new Set([mockApps[2], mockApps[3], mockApps[1]]),
|
||||
);
|
||||
});
|
||||
|
||||
it("should recalculate all rooms when the client is ready", async () => {
|
||||
mocked(client.getVisibleRooms).mockReturnValue([mockRoom]);
|
||||
await store.start();
|
||||
|
||||
expect(roomUpdateListener).toHaveBeenCalled();
|
||||
expect(store.getContainerWidgets(mockRoom, Container.Top)).toEqual([]);
|
||||
expect(store.getContainerWidgets(mockRoom, Container.Center)).toEqual([]);
|
||||
expect(store.getContainerWidgets(mockRoom, Container.Right)).toEqual([
|
||||
mockApps[0],
|
||||
mockApps[1],
|
||||
mockApps[2],
|
||||
mockApps[3],
|
||||
]);
|
||||
});
|
||||
|
||||
it("should clear the layout and emit an update if there are no longer apps in the room", () => {
|
||||
store.recalculateRoom(mockRoom);
|
||||
mocked(roomUpdateListener).mockClear();
|
||||
|
||||
jest.spyOn(WidgetStore, "instance", "get").mockReturnValue(<WidgetStore>(
|
||||
({ getApps: (): IApp[] => [] } as unknown as WidgetStore)
|
||||
));
|
||||
store.recalculateRoom(mockRoom);
|
||||
expect(roomUpdateListener).toHaveBeenCalled();
|
||||
expect(store.getContainerWidgets(mockRoom, Container.Top)).toEqual([]);
|
||||
expect(store.getContainerWidgets(mockRoom, Container.Center)).toEqual([]);
|
||||
expect(store.getContainerWidgets(mockRoom, Container.Right)).toEqual([]);
|
||||
});
|
||||
|
||||
it("should clear the layout if the client is not viable", () => {
|
||||
store.recalculateRoom(mockRoom);
|
||||
defaultDispatcher.dispatch(
|
||||
{
|
||||
action: "on_client_not_viable",
|
||||
},
|
||||
true,
|
||||
);
|
||||
|
||||
expect(store.getContainerWidgets(mockRoom, Container.Top)).toEqual([]);
|
||||
expect(store.getContainerWidgets(mockRoom, Container.Center)).toEqual([]);
|
||||
expect(store.getContainerWidgets(mockRoom, Container.Right)).toEqual([]);
|
||||
});
|
||||
|
||||
it("should return the expected resizer distributions", () => {
|
||||
// this only works for top widgets
|
||||
store.recalculateRoom(mockRoom);
|
||||
store.moveToContainer(mockRoom, mockApps[0], Container.Top);
|
||||
store.moveToContainer(mockRoom, mockApps[1], Container.Top);
|
||||
expect(store.getResizerDistributions(mockRoom, Container.Top)).toEqual(["50.0%"]);
|
||||
});
|
||||
|
||||
it("should set and return container height", () => {
|
||||
store.recalculateRoom(mockRoom);
|
||||
store.moveToContainer(mockRoom, mockApps[0], Container.Top);
|
||||
store.moveToContainer(mockRoom, mockApps[1], Container.Top);
|
||||
store.setContainerHeight(mockRoom, Container.Top, 23);
|
||||
expect(store.getContainerHeight(mockRoom, Container.Top)).toBe(23);
|
||||
});
|
||||
|
||||
it("should move a widget within a container", () => {
|
||||
store.recalculateRoom(mockRoom);
|
||||
store.moveToContainer(mockRoom, mockApps[0], Container.Top);
|
||||
store.moveToContainer(mockRoom, mockApps[1], Container.Top);
|
||||
store.moveToContainer(mockRoom, mockApps[2], Container.Top);
|
||||
expect(store.getContainerWidgets(mockRoom, Container.Top)).toStrictEqual([
|
||||
mockApps[0],
|
||||
mockApps[1],
|
||||
mockApps[2],
|
||||
]);
|
||||
store.moveWithinContainer(mockRoom, Container.Top, mockApps[0], 1);
|
||||
expect(store.getContainerWidgets(mockRoom, Container.Top)).toStrictEqual([
|
||||
mockApps[1],
|
||||
mockApps[0],
|
||||
mockApps[2],
|
||||
]);
|
||||
});
|
||||
|
||||
it("should copy the layout to the room", async () => {
|
||||
await store.start();
|
||||
store.recalculateRoom(mockRoom);
|
||||
store.moveToContainer(mockRoom, mockApps[0], Container.Top);
|
||||
store.copyLayoutToRoom(mockRoom);
|
||||
|
||||
expect(mocked(client.sendStateEvent).mock.calls).toMatchInlineSnapshot(`
|
||||
[
|
||||
[
|
||||
"!room:server",
|
||||
"io.element.widgets.layout",
|
||||
{
|
||||
"widgets": {
|
||||
"1": {
|
||||
"container": "top",
|
||||
"height": undefined,
|
||||
"index": 0,
|
||||
"width": 100,
|
||||
},
|
||||
"2": {
|
||||
"container": "right",
|
||||
},
|
||||
"3": {
|
||||
"container": "right",
|
||||
},
|
||||
"4": {
|
||||
"container": "right",
|
||||
},
|
||||
},
|
||||
},
|
||||
"",
|
||||
],
|
||||
]
|
||||
`);
|
||||
});
|
||||
|
||||
it("Can call onNotReady before onReady has been called", () => {
|
||||
// Just to quieten SonarCloud :-(
|
||||
|
||||
// @ts-ignore bypass private ctor for tests
|
||||
const store = new WidgetLayoutStore();
|
||||
// @ts-ignore calling private method
|
||||
store.onNotReady();
|
||||
});
|
||||
|
||||
describe("when feature_dynamic_room_predecessors is not enabled", () => {
|
||||
beforeAll(() => {
|
||||
jest.spyOn(SettingsStore, "getValue").mockReturnValue(false);
|
||||
});
|
||||
|
||||
it("passes the flag in to getVisibleRooms", async () => {
|
||||
mocked(client.getVisibleRooms).mockRestore();
|
||||
mocked(client.getVisibleRooms).mockReturnValue([]);
|
||||
// @ts-ignore bypass private ctor for tests
|
||||
const store = new WidgetLayoutStore();
|
||||
await store.start();
|
||||
expect(client.getVisibleRooms).toHaveBeenCalledWith(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("when feature_dynamic_room_predecessors is enabled", () => {
|
||||
beforeAll(() => {
|
||||
jest.spyOn(SettingsStore, "getValue").mockImplementation(
|
||||
(settingName) => settingName === "feature_dynamic_room_predecessors",
|
||||
);
|
||||
});
|
||||
|
||||
it("passes the flag in to getVisibleRooms", async () => {
|
||||
mocked(client.getVisibleRooms).mockRestore();
|
||||
mocked(client.getVisibleRooms).mockReturnValue([]);
|
||||
// @ts-ignore bypass private ctor for tests
|
||||
const store = new WidgetLayoutStore();
|
||||
await store.start();
|
||||
expect(client.getVisibleRooms).toHaveBeenCalledWith(true);
|
||||
});
|
||||
});
|
||||
});
|
|
@ -0,0 +1,43 @@
|
|||
// Jest Snapshot v1, https://goo.gl/fbAQLP
|
||||
|
||||
exports[`RoomViewStore should display an error message when the room is unreachable via the roomId 1`] = `
|
||||
{
|
||||
"description": <div>
|
||||
You attempted to join using a room ID without providing a list of servers to join through. Room IDs are internal identifiers and cannot be used to join a room without additional information.
|
||||
<br />
|
||||
<br />
|
||||
If you know a room address, try joining through that instead.
|
||||
</div>,
|
||||
"title": "Failed to join",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`RoomViewStore should display the generic error message when the roomId doesnt match 1`] = `
|
||||
{
|
||||
"description": "MatrixError: [404] my 404 error",
|
||||
"title": "Failed to join",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`RoomViewStore when recording a voice broadcast and trying to view a call, it should not actually view it and show the info dialog 1`] = `
|
||||
[MockFunction] {
|
||||
"calls": [
|
||||
[
|
||||
[Function],
|
||||
{
|
||||
"description": <p>
|
||||
You can’t start a call as you are currently recording a live broadcast. Please end your live broadcast in order to start a call.
|
||||
</p>,
|
||||
"hasCloseButton": true,
|
||||
"title": "Can’t start a call",
|
||||
},
|
||||
],
|
||||
],
|
||||
"results": [
|
||||
{
|
||||
"type": "return",
|
||||
"value": undefined,
|
||||
},
|
||||
],
|
||||
}
|
||||
`;
|
|
@ -0,0 +1,26 @@
|
|||
/*
|
||||
Copyright 2024 New Vector Ltd.
|
||||
Copyright 2023 The Matrix.org Foundation C.I.C.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import {
|
||||
humanReadableNotificationLevel,
|
||||
NotificationLevel,
|
||||
} from "../../../../src/stores/notifications/NotificationLevel";
|
||||
|
||||
describe("NotificationLevel", () => {
|
||||
describe("humanReadableNotificationLevel", () => {
|
||||
it.each([
|
||||
[NotificationLevel.None, "None"],
|
||||
[NotificationLevel.Activity, "Activity"],
|
||||
[NotificationLevel.Notification, "Notification"],
|
||||
[NotificationLevel.Highlight, "Highlight"],
|
||||
[NotificationLevel.Unsent, "Unsent"],
|
||||
])("correctly maps the output", (color, output) => {
|
||||
expect(humanReadableNotificationLevel(color)).toBe(output);
|
||||
});
|
||||
});
|
||||
});
|
|
@ -0,0 +1,203 @@
|
|||
/*
|
||||
Copyright 2024 New Vector Ltd.
|
||||
Copyright 2022, 2023 The Matrix.org Foundation C.I.C.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import {
|
||||
Room,
|
||||
MatrixEventEvent,
|
||||
PendingEventOrdering,
|
||||
EventStatus,
|
||||
NotificationCountType,
|
||||
EventType,
|
||||
MatrixEvent,
|
||||
RoomEvent,
|
||||
} from "matrix-js-sdk/src/matrix";
|
||||
import { KnownMembership } from "matrix-js-sdk/src/types";
|
||||
|
||||
import type { MatrixClient } from "matrix-js-sdk/src/matrix";
|
||||
import { mkEvent, muteRoom, stubClient } from "../../../test-utils";
|
||||
import { RoomNotificationState } from "../../../../src/stores/notifications/RoomNotificationState";
|
||||
import { NotificationStateEvents } from "../../../../src/stores/notifications/NotificationState";
|
||||
import { NotificationLevel } from "../../../../src/stores/notifications/NotificationLevel";
|
||||
import { createMessageEventContent } from "../../../test-utils/events";
|
||||
|
||||
describe("RoomNotificationState", () => {
|
||||
let room: Room;
|
||||
let client: MatrixClient;
|
||||
|
||||
beforeEach(() => {
|
||||
client = stubClient();
|
||||
room = new Room("!room:example.com", client, "@user:example.org", {
|
||||
pendingEventOrdering: PendingEventOrdering.Detached,
|
||||
});
|
||||
});
|
||||
|
||||
function addThread(room: Room): void {
|
||||
const threadId = "thread_id";
|
||||
jest.spyOn(room, "eventShouldLiveIn").mockReturnValue({
|
||||
shouldLiveInRoom: true,
|
||||
shouldLiveInThread: true,
|
||||
threadId,
|
||||
});
|
||||
const thread = room.createThread(
|
||||
threadId,
|
||||
new MatrixEvent({
|
||||
room_id: room.roomId,
|
||||
event_id: "event_root_1",
|
||||
type: EventType.RoomMessage,
|
||||
sender: "userId",
|
||||
content: createMessageEventContent("RootEvent"),
|
||||
}),
|
||||
[],
|
||||
true,
|
||||
);
|
||||
for (let i = 0; i < 10; i++) {
|
||||
thread.addEvent(
|
||||
new MatrixEvent({
|
||||
room_id: room.roomId,
|
||||
event_id: "event_reply_1" + i,
|
||||
type: EventType.RoomMessage,
|
||||
sender: "userId",
|
||||
content: createMessageEventContent("ReplyEvent" + 1),
|
||||
}),
|
||||
false,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function setUnreads(room: Room, greys: number, reds: number): void {
|
||||
room.setUnreadNotificationCount(NotificationCountType.Highlight, reds);
|
||||
room.setUnreadNotificationCount(NotificationCountType.Total, greys);
|
||||
}
|
||||
|
||||
it("updates on event decryption", () => {
|
||||
const roomNotifState = new RoomNotificationState(room, true);
|
||||
const listener = jest.fn();
|
||||
roomNotifState.addListener(NotificationStateEvents.Update, listener);
|
||||
const testEvent = {
|
||||
getRoomId: () => room.roomId,
|
||||
} as unknown as MatrixEvent;
|
||||
room.getUnreadNotificationCount = jest.fn().mockReturnValue(1);
|
||||
client.emit(MatrixEventEvent.Decrypted, testEvent);
|
||||
expect(listener).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("emits an Update event on marked unread room account data", () => {
|
||||
const roomNotifState = new RoomNotificationState(room, true);
|
||||
const listener = jest.fn();
|
||||
roomNotifState.addListener(NotificationStateEvents.Update, listener);
|
||||
const accountDataEvent = {
|
||||
getType: () => "com.famedly.marked_unread",
|
||||
getContent: () => {
|
||||
return { unread: true };
|
||||
},
|
||||
} as unknown as MatrixEvent;
|
||||
room.getAccountData = jest.fn().mockReturnValue(accountDataEvent);
|
||||
room.emit(RoomEvent.AccountData, accountDataEvent, room);
|
||||
expect(listener).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not update on other account data", () => {
|
||||
const roomNotifState = new RoomNotificationState(room, true);
|
||||
const listener = jest.fn();
|
||||
roomNotifState.addListener(NotificationStateEvents.Update, listener);
|
||||
const accountDataEvent = {
|
||||
getType: () => "else.something",
|
||||
getContent: () => {
|
||||
return {};
|
||||
},
|
||||
} as unknown as MatrixEvent;
|
||||
room.getAccountData = jest.fn().mockReturnValue(accountDataEvent);
|
||||
room.emit(RoomEvent.AccountData, accountDataEvent, room);
|
||||
expect(listener).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("removes listeners", () => {
|
||||
const roomNotifState = new RoomNotificationState(room, false);
|
||||
expect(() => roomNotifState.destroy()).not.toThrow();
|
||||
});
|
||||
|
||||
it("suggests an 'unread' ! if there are unsent messages", () => {
|
||||
const roomNotifState = new RoomNotificationState(room, false);
|
||||
|
||||
const event = mkEvent({
|
||||
event: true,
|
||||
type: "m.message",
|
||||
user: "@user:example.org",
|
||||
content: {},
|
||||
});
|
||||
event.status = EventStatus.NOT_SENT;
|
||||
room.addPendingEvent(event, "txn");
|
||||
|
||||
expect(roomNotifState.level).toBe(NotificationLevel.Unsent);
|
||||
expect(roomNotifState.symbol).toBe("!");
|
||||
expect(roomNotifState.count).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("suggests nothing if the room is muted", () => {
|
||||
const roomNotifState = new RoomNotificationState(room, false);
|
||||
|
||||
muteRoom(room);
|
||||
setUnreads(room, 1234, 0);
|
||||
room.updateMyMembership(KnownMembership.Join); // emit
|
||||
|
||||
expect(roomNotifState.level).toBe(NotificationLevel.None);
|
||||
expect(roomNotifState.symbol).toBe(null);
|
||||
expect(roomNotifState.count).toBe(0);
|
||||
});
|
||||
|
||||
it("suggests a red ! if the user has been invited to a room", () => {
|
||||
const roomNotifState = new RoomNotificationState(room, false);
|
||||
|
||||
room.updateMyMembership(KnownMembership.Invite); // emit
|
||||
|
||||
expect(roomNotifState.level).toBe(NotificationLevel.Highlight);
|
||||
expect(roomNotifState.symbol).toBe("!");
|
||||
expect(roomNotifState.count).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("returns a proper count and color for regular unreads", () => {
|
||||
const roomNotifState = new RoomNotificationState(room, false);
|
||||
|
||||
setUnreads(room, 4321, 0);
|
||||
room.updateMyMembership(KnownMembership.Join); // emit
|
||||
|
||||
expect(roomNotifState.level).toBe(NotificationLevel.Notification);
|
||||
expect(roomNotifState.symbol).toBe(null);
|
||||
expect(roomNotifState.count).toBe(4321);
|
||||
});
|
||||
|
||||
it("returns a proper count and color for highlights", () => {
|
||||
const roomNotifState = new RoomNotificationState(room, false);
|
||||
|
||||
setUnreads(room, 0, 69);
|
||||
room.updateMyMembership(KnownMembership.Join); // emit
|
||||
|
||||
expect(roomNotifState.level).toBe(NotificationLevel.Highlight);
|
||||
expect(roomNotifState.symbol).toBe(null);
|
||||
expect(roomNotifState.count).toBe(69);
|
||||
});
|
||||
|
||||
it("includes threads", async () => {
|
||||
const roomNotifState = new RoomNotificationState(room, true);
|
||||
|
||||
room.timeline.push(
|
||||
new MatrixEvent({
|
||||
room_id: room.roomId,
|
||||
type: EventType.RoomMessage,
|
||||
sender: "userId",
|
||||
content: createMessageEventContent("timeline event"),
|
||||
}),
|
||||
);
|
||||
|
||||
addThread(room);
|
||||
room.updateMyMembership(KnownMembership.Join); // emit
|
||||
|
||||
expect(roomNotifState.level).toBe(NotificationLevel.Activity);
|
||||
expect(roomNotifState.symbol).toBe(null);
|
||||
});
|
||||
});
|
246
test/unit-tests/stores/oidc/OidcClientStore-test.ts
Normal file
246
test/unit-tests/stores/oidc/OidcClientStore-test.ts
Normal file
|
@ -0,0 +1,246 @@
|
|||
/*
|
||||
Copyright 2024 New Vector Ltd.
|
||||
Copyright 2023 The Matrix.org Foundation C.I.C.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import fetchMock from "fetch-mock-jest";
|
||||
import { mocked } from "jest-mock";
|
||||
import { OidcClient } from "oidc-client-ts";
|
||||
import { logger } from "matrix-js-sdk/src/logger";
|
||||
import { discoverAndValidateOIDCIssuerWellKnown } from "matrix-js-sdk/src/matrix";
|
||||
import { OidcError } from "matrix-js-sdk/src/oidc/error";
|
||||
|
||||
import { OidcClientStore } from "../../../../src/stores/oidc/OidcClientStore";
|
||||
import { flushPromises, getMockClientWithEventEmitter, mockPlatformPeg } from "../../../test-utils";
|
||||
import { mockOpenIdConfiguration } from "../../../test-utils/oidc";
|
||||
|
||||
jest.mock("matrix-js-sdk/src/matrix", () => ({
|
||||
...jest.requireActual("matrix-js-sdk/src/matrix"),
|
||||
discoverAndValidateOIDCIssuerWellKnown: jest.fn(),
|
||||
}));
|
||||
|
||||
describe("OidcClientStore", () => {
|
||||
const clientId = "test-client-id";
|
||||
const metadata = mockOpenIdConfiguration();
|
||||
const account = metadata.issuer + "account";
|
||||
|
||||
const mockClient = getMockClientWithEventEmitter({
|
||||
getAuthIssuer: jest.fn(),
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
localStorage.setItem("mx_oidc_client_id", clientId);
|
||||
localStorage.setItem("mx_oidc_token_issuer", metadata.issuer);
|
||||
|
||||
mocked(discoverAndValidateOIDCIssuerWellKnown).mockClear().mockResolvedValue({
|
||||
metadata,
|
||||
accountManagementEndpoint: account,
|
||||
authorizationEndpoint: "authorization-endpoint",
|
||||
tokenEndpoint: "token-endpoint",
|
||||
});
|
||||
jest.spyOn(logger, "error").mockClear();
|
||||
|
||||
fetchMock.get(`${metadata.issuer}.well-known/openid-configuration`, metadata);
|
||||
fetchMock.get(`${metadata.issuer}jwks`, { keys: [] });
|
||||
mockPlatformPeg();
|
||||
});
|
||||
|
||||
describe("isUserAuthenticatedWithOidc()", () => {
|
||||
it("should return true when an issuer is in session storage", () => {
|
||||
const store = new OidcClientStore(mockClient);
|
||||
|
||||
expect(store.isUserAuthenticatedWithOidc).toEqual(true);
|
||||
});
|
||||
|
||||
it("should return false when no issuer is in session storage", () => {
|
||||
localStorage.clear();
|
||||
const store = new OidcClientStore(mockClient);
|
||||
|
||||
expect(store.isUserAuthenticatedWithOidc).toEqual(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("initialising oidcClient", () => {
|
||||
it("should initialise oidc client from constructor", () => {
|
||||
const store = new OidcClientStore(mockClient);
|
||||
|
||||
// started initialising
|
||||
// @ts-ignore private property
|
||||
expect(store.initialisingOidcClientPromise).toBeTruthy();
|
||||
});
|
||||
|
||||
it("should fallback to stored issuer when no client well known is available", async () => {
|
||||
const store = new OidcClientStore(mockClient);
|
||||
|
||||
// successfully created oidc client
|
||||
// @ts-ignore private property
|
||||
expect(await store.getOidcClient()).toBeTruthy();
|
||||
});
|
||||
|
||||
it("should log and return when no clientId is found in storage", async () => {
|
||||
localStorage.removeItem("mx_oidc_client_id");
|
||||
const store = new OidcClientStore(mockClient);
|
||||
|
||||
// no oidc client
|
||||
// @ts-ignore private property
|
||||
expect(await store.getOidcClient()).toEqual(undefined);
|
||||
expect(logger.error).toHaveBeenCalledWith(
|
||||
"Failed to initialise OidcClientStore",
|
||||
new Error("Oidc client id not found in storage"),
|
||||
);
|
||||
});
|
||||
|
||||
it("should log and return when discovery and validation fails", async () => {
|
||||
mocked(discoverAndValidateOIDCIssuerWellKnown).mockRejectedValue(new Error(OidcError.OpSupport));
|
||||
const store = new OidcClientStore(mockClient);
|
||||
|
||||
await store.readyPromise;
|
||||
|
||||
expect(logger.error).toHaveBeenCalledWith(
|
||||
"Failed to initialise OidcClientStore",
|
||||
new Error(OidcError.OpSupport),
|
||||
);
|
||||
// no oidc client
|
||||
// @ts-ignore private property
|
||||
expect(await store.getOidcClient()).toEqual(undefined);
|
||||
});
|
||||
|
||||
it("should create oidc client correctly", async () => {
|
||||
const store = new OidcClientStore(mockClient);
|
||||
|
||||
// @ts-ignore private property
|
||||
const client = await store.getOidcClient();
|
||||
|
||||
expect(client?.settings.client_id).toEqual(clientId);
|
||||
expect(client?.settings.authority).toEqual(metadata.issuer);
|
||||
});
|
||||
|
||||
it("should set account management endpoint when configured", async () => {
|
||||
const store = new OidcClientStore(mockClient);
|
||||
|
||||
// @ts-ignore private property
|
||||
await store.getOidcClient();
|
||||
|
||||
expect(store.accountManagementEndpoint).toEqual(account);
|
||||
});
|
||||
|
||||
it("should set account management endpoint to issuer when not configured", async () => {
|
||||
mocked(discoverAndValidateOIDCIssuerWellKnown).mockClear().mockResolvedValue({
|
||||
metadata,
|
||||
accountManagementEndpoint: undefined,
|
||||
authorizationEndpoint: "authorization-endpoint",
|
||||
tokenEndpoint: "token-endpoint",
|
||||
});
|
||||
const store = new OidcClientStore(mockClient);
|
||||
|
||||
await store.readyPromise;
|
||||
|
||||
expect(store.accountManagementEndpoint).toEqual(metadata.issuer);
|
||||
});
|
||||
|
||||
it("should reuse initialised oidc client", async () => {
|
||||
const store = new OidcClientStore(mockClient);
|
||||
|
||||
// @ts-ignore private property
|
||||
store.getOidcClient();
|
||||
// @ts-ignore private property
|
||||
store.getOidcClient();
|
||||
|
||||
await flushPromises();
|
||||
|
||||
// finished initialising
|
||||
// @ts-ignore private property
|
||||
expect(await store.getOidcClient()).toBeTruthy();
|
||||
|
||||
// @ts-ignore private property
|
||||
store.getOidcClient();
|
||||
|
||||
// only called once for multiple calls to getOidcClient
|
||||
// before and after initialisation is complete
|
||||
expect(discoverAndValidateOIDCIssuerWellKnown).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("revokeTokens()", () => {
|
||||
const accessToken = "test-access-token";
|
||||
const refreshToken = "test-refresh-token";
|
||||
|
||||
beforeEach(() => {
|
||||
// spy and call through
|
||||
jest.spyOn(OidcClient.prototype, "revokeToken").mockClear();
|
||||
|
||||
fetchMock.resetHistory();
|
||||
fetchMock.post(
|
||||
metadata.revocation_endpoint,
|
||||
{
|
||||
status: 200,
|
||||
},
|
||||
{ sendAsJson: true },
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw when oidcClient could not be initialised", async () => {
|
||||
// make oidcClient initialisation fail
|
||||
localStorage.removeItem("mx_oidc_token_issuer");
|
||||
|
||||
const store = new OidcClientStore(mockClient);
|
||||
|
||||
await expect(() => store.revokeTokens(accessToken, refreshToken)).rejects.toThrow("No OIDC client");
|
||||
});
|
||||
|
||||
it("should revoke access and refresh tokens", async () => {
|
||||
const store = new OidcClientStore(mockClient);
|
||||
|
||||
await store.revokeTokens(accessToken, refreshToken);
|
||||
|
||||
expect(fetchMock).toHaveFetchedTimes(2, metadata.revocation_endpoint);
|
||||
expect(OidcClient.prototype.revokeToken).toHaveBeenCalledWith(accessToken, "access_token");
|
||||
expect(OidcClient.prototype.revokeToken).toHaveBeenCalledWith(refreshToken, "refresh_token");
|
||||
});
|
||||
|
||||
it("should still attempt to revoke refresh token when access token revocation fails", async () => {
|
||||
// fail once, then succeed
|
||||
fetchMock
|
||||
.postOnce(
|
||||
metadata.revocation_endpoint,
|
||||
{
|
||||
status: 404,
|
||||
},
|
||||
{ overwriteRoutes: true, sendAsJson: true },
|
||||
)
|
||||
.post(
|
||||
metadata.revocation_endpoint,
|
||||
{
|
||||
status: 200,
|
||||
},
|
||||
{ sendAsJson: true },
|
||||
);
|
||||
|
||||
const store = new OidcClientStore(mockClient);
|
||||
|
||||
await expect(() => store.revokeTokens(accessToken, refreshToken)).rejects.toThrow(
|
||||
"Failed to revoke tokens",
|
||||
);
|
||||
|
||||
expect(fetchMock).toHaveFetchedTimes(2, metadata.revocation_endpoint);
|
||||
expect(OidcClient.prototype.revokeToken).toHaveBeenCalledWith(accessToken, "access_token");
|
||||
});
|
||||
});
|
||||
|
||||
describe("OIDC Aware", () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
it("should resolve account management endpoint", async () => {
|
||||
mockClient.getAuthIssuer.mockResolvedValue({ issuer: metadata.issuer });
|
||||
const store = new OidcClientStore(mockClient);
|
||||
await store.readyPromise;
|
||||
expect(store.accountManagementEndpoint).toBe(account);
|
||||
});
|
||||
});
|
||||
});
|
220
test/unit-tests/stores/right-panel/RightPanelStore-test.ts
Normal file
220
test/unit-tests/stores/right-panel/RightPanelStore-test.ts
Normal file
|
@ -0,0 +1,220 @@
|
|||
/*
|
||||
Copyright 2024 New Vector Ltd.
|
||||
Copyright 2022 The Matrix.org Foundation C.I.C.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { mocked, MockedObject } from "jest-mock";
|
||||
import { MatrixClient, RoomMember } from "matrix-js-sdk/src/matrix";
|
||||
|
||||
import { stubClient } from "../../../test-utils";
|
||||
import { MatrixClientPeg } from "../../../../src/MatrixClientPeg";
|
||||
import DMRoomMap from "../../../../src/utils/DMRoomMap";
|
||||
import { Action } from "../../../../src/dispatcher/actions";
|
||||
import defaultDispatcher from "../../../../src/dispatcher/dispatcher";
|
||||
import { ActiveRoomChangedPayload } from "../../../../src/dispatcher/payloads/ActiveRoomChangedPayload";
|
||||
import RightPanelStore from "../../../../src/stores/right-panel/RightPanelStore";
|
||||
import { RightPanelPhases } from "../../../../src/stores/right-panel/RightPanelStorePhases";
|
||||
import SettingsStore from "../../../../src/settings/SettingsStore";
|
||||
|
||||
describe("RightPanelStore", () => {
|
||||
// Mock out the settings store so the right panel store can't persist values between tests
|
||||
jest.spyOn(SettingsStore, "setValue").mockImplementation(async () => {});
|
||||
|
||||
const store = RightPanelStore.instance;
|
||||
let cli: MockedObject<MatrixClient>;
|
||||
beforeEach(() => {
|
||||
stubClient();
|
||||
cli = mocked(MatrixClientPeg.safeGet());
|
||||
DMRoomMap.makeShared(cli);
|
||||
|
||||
// Make sure we start with a clean store
|
||||
store.reset();
|
||||
store.useUnitTestClient(cli);
|
||||
});
|
||||
|
||||
const viewRoom = async (roomId: string) => {
|
||||
const roomChanged = new Promise<void>((resolve) => {
|
||||
const ref = defaultDispatcher.register((payload) => {
|
||||
if (payload.action === Action.ActiveRoomChanged && payload.newRoomId === roomId) {
|
||||
defaultDispatcher.unregister(ref);
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
defaultDispatcher.dispatch<ActiveRoomChangedPayload>({
|
||||
action: Action.ActiveRoomChanged,
|
||||
oldRoomId: null,
|
||||
newRoomId: roomId,
|
||||
});
|
||||
|
||||
await roomChanged;
|
||||
};
|
||||
|
||||
const setCard = (roomId: string, phase: RightPanelPhases) => store.setCard({ phase }, true, roomId);
|
||||
|
||||
describe("isOpen", () => {
|
||||
it("is false if no rooms are open", () => {
|
||||
expect(store.isOpen).toEqual(false);
|
||||
});
|
||||
it("is false if a room other than the current room is open", async () => {
|
||||
await viewRoom("!1:example.org");
|
||||
setCard("!2:example.org", RightPanelPhases.RoomSummary);
|
||||
expect(store.isOpen).toEqual(false);
|
||||
});
|
||||
it("is true if the current room is open", async () => {
|
||||
await viewRoom("!1:example.org");
|
||||
setCard("!1:example.org", RightPanelPhases.RoomSummary);
|
||||
expect(store.isOpen).toEqual(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("currentCard", () => {
|
||||
it("has a phase of null if nothing is open", () => {
|
||||
expect(store.currentCard.phase).toEqual(null);
|
||||
});
|
||||
it("has a phase of null if the panel is open but in another room", async () => {
|
||||
await viewRoom("!1:example.org");
|
||||
setCard("!2:example.org", RightPanelPhases.RoomSummary);
|
||||
expect(store.currentCard.phase).toEqual(null);
|
||||
});
|
||||
it("reflects the phase of the current room", async () => {
|
||||
await viewRoom("!1:example.org");
|
||||
setCard("!1:example.org", RightPanelPhases.RoomSummary);
|
||||
expect(store.currentCard.phase).toEqual(RightPanelPhases.RoomSummary);
|
||||
});
|
||||
});
|
||||
|
||||
describe("setCard", () => {
|
||||
it("does nothing if given no room ID and not viewing a room", () => {
|
||||
store.setCard({ phase: RightPanelPhases.RoomSummary }, true);
|
||||
expect(store.isOpen).toEqual(false);
|
||||
expect(store.currentCard.phase).toEqual(null);
|
||||
});
|
||||
it("does nothing if given an invalid state", async () => {
|
||||
await viewRoom("!1:example.org");
|
||||
// Needs a member specified to be valid
|
||||
store.setCard({ phase: RightPanelPhases.RoomMemberInfo }, true, "!1:example.org");
|
||||
expect(store.roomPhaseHistory).toEqual([]);
|
||||
});
|
||||
it("only creates a single history entry if given the same card twice", async () => {
|
||||
await viewRoom("!1:example.org");
|
||||
store.setCard({ phase: RightPanelPhases.RoomSummary }, true, "!1:example.org");
|
||||
store.setCard({ phase: RightPanelPhases.RoomSummary }, true, "!1:example.org");
|
||||
expect(store.roomPhaseHistory).toEqual([{ phase: RightPanelPhases.RoomSummary, state: {} }]);
|
||||
});
|
||||
it("opens the panel in the given room with the correct phase", () => {
|
||||
store.setCard({ phase: RightPanelPhases.RoomSummary }, true, "!1:example.org");
|
||||
expect(store.isOpenForRoom("!1:example.org")).toEqual(true);
|
||||
expect(store.currentCardForRoom("!1:example.org").phase).toEqual(RightPanelPhases.RoomSummary);
|
||||
});
|
||||
it("overwrites history if changing the phase", async () => {
|
||||
await viewRoom("!1:example.org");
|
||||
store.setCard({ phase: RightPanelPhases.RoomSummary }, true, "!1:example.org");
|
||||
store.setCard({ phase: RightPanelPhases.RoomMemberList }, true, "!1:example.org");
|
||||
expect(store.roomPhaseHistory).toEqual([{ phase: RightPanelPhases.RoomMemberList, state: {} }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("setCards", () => {
|
||||
it("overwrites history", async () => {
|
||||
await viewRoom("!1:example.org");
|
||||
store.setCard({ phase: RightPanelPhases.RoomMemberList }, true, "!1:example.org");
|
||||
store.setCards(
|
||||
[{ phase: RightPanelPhases.RoomSummary }, { phase: RightPanelPhases.PinnedMessages }],
|
||||
true,
|
||||
"!1:example.org",
|
||||
);
|
||||
expect(store.roomPhaseHistory).toEqual([
|
||||
{ phase: RightPanelPhases.RoomSummary, state: {} },
|
||||
{ phase: RightPanelPhases.PinnedMessages, state: {} },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("pushCard", () => {
|
||||
it("does nothing if given no room ID and not viewing a room", () => {
|
||||
store.pushCard({ phase: RightPanelPhases.RoomSummary }, true);
|
||||
expect(store.isOpen).toEqual(false);
|
||||
expect(store.currentCard.phase).toEqual(null);
|
||||
});
|
||||
it("opens the panel in the given room with the correct phase", () => {
|
||||
store.pushCard({ phase: RightPanelPhases.RoomSummary }, true, "!1:example.org");
|
||||
expect(store.isOpenForRoom("!1:example.org")).toEqual(true);
|
||||
expect(store.currentCardForRoom("!1:example.org").phase).toEqual(RightPanelPhases.RoomSummary);
|
||||
});
|
||||
it("appends the phase to any phases that were there before", async () => {
|
||||
await viewRoom("!1:example.org");
|
||||
store.setCard({ phase: RightPanelPhases.RoomSummary }, true, "!1:example.org");
|
||||
store.pushCard({ phase: RightPanelPhases.PinnedMessages }, true, "!1:example.org");
|
||||
expect(store.roomPhaseHistory).toEqual([
|
||||
{ phase: RightPanelPhases.RoomSummary, state: {} },
|
||||
{ phase: RightPanelPhases.PinnedMessages, state: {} },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("popCard", () => {
|
||||
it("removes the most recent card", () => {
|
||||
store.setCards(
|
||||
[{ phase: RightPanelPhases.RoomSummary }, { phase: RightPanelPhases.PinnedMessages }],
|
||||
true,
|
||||
"!1:example.org",
|
||||
);
|
||||
expect(store.currentCardForRoom("!1:example.org").phase).toEqual(RightPanelPhases.PinnedMessages);
|
||||
store.popCard("!1:example.org");
|
||||
expect(store.currentCardForRoom("!1:example.org").phase).toEqual(RightPanelPhases.RoomSummary);
|
||||
});
|
||||
});
|
||||
|
||||
describe("togglePanel", () => {
|
||||
it("does nothing if the room has no phase to open to", () => {
|
||||
expect(store.isOpenForRoom("!1:example.org")).toEqual(false);
|
||||
store.togglePanel("!1:example.org");
|
||||
expect(store.isOpenForRoom("!1:example.org")).toEqual(false);
|
||||
});
|
||||
it("works if a room is specified", () => {
|
||||
store.setCard({ phase: RightPanelPhases.RoomSummary }, true, "!1:example.org");
|
||||
expect(store.isOpenForRoom("!1:example.org")).toEqual(true);
|
||||
store.togglePanel("!1:example.org");
|
||||
expect(store.isOpenForRoom("!1:example.org")).toEqual(false);
|
||||
store.togglePanel("!1:example.org");
|
||||
expect(store.isOpenForRoom("!1:example.org")).toEqual(true);
|
||||
});
|
||||
it("operates on the current room if no room is specified", async () => {
|
||||
await viewRoom("!1:example.org");
|
||||
store.setCard({ phase: RightPanelPhases.RoomSummary }, true);
|
||||
expect(store.isOpen).toEqual(true);
|
||||
store.togglePanel(null);
|
||||
expect(store.isOpen).toEqual(false);
|
||||
store.togglePanel(null);
|
||||
expect(store.isOpen).toEqual(true);
|
||||
});
|
||||
});
|
||||
|
||||
it("doesn't restore member info cards when switching back to a room", async () => {
|
||||
await viewRoom("!1:example.org");
|
||||
store.setCards(
|
||||
[
|
||||
{
|
||||
phase: RightPanelPhases.RoomMemberList,
|
||||
},
|
||||
{
|
||||
phase: RightPanelPhases.RoomMemberInfo,
|
||||
state: { member: new RoomMember("!1:example.org", "@alice:example.org") },
|
||||
},
|
||||
],
|
||||
true,
|
||||
"!1:example.org",
|
||||
);
|
||||
expect(store.currentCardForRoom("!1:example.org").phase).toEqual(RightPanelPhases.RoomMemberInfo);
|
||||
|
||||
// Switch away and back
|
||||
await viewRoom("!2:example.org");
|
||||
await viewRoom("!1:example.org");
|
||||
expect(store.currentCardForRoom("!1:example.org").phase).toEqual(RightPanelPhases.RoomMemberList);
|
||||
});
|
||||
});
|
|
@ -0,0 +1,50 @@
|
|||
/*
|
||||
Copyright 2024 New Vector Ltd.
|
||||
Copyright 2023 The Matrix.org Foundation C.I.C.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { MockedObject } from "jest-mock";
|
||||
import { EventType, MatrixEvent } from "matrix-js-sdk/src/matrix";
|
||||
|
||||
import { Action } from "../../../../../src/dispatcher/actions";
|
||||
import { onView3pidInvite } from "../../../../../src/stores/right-panel/action-handlers";
|
||||
import RightPanelStore from "../../../../../src/stores/right-panel/RightPanelStore";
|
||||
import { RightPanelPhases } from "../../../../../src/stores/right-panel/RightPanelStorePhases";
|
||||
|
||||
describe("onView3pidInvite()", () => {
|
||||
let rightPanelStore!: MockedObject<RightPanelStore>;
|
||||
|
||||
beforeEach(() => {
|
||||
rightPanelStore = {
|
||||
pushCard: jest.fn(),
|
||||
showOrHidePhase: jest.fn(),
|
||||
} as unknown as MockedObject<RightPanelStore>;
|
||||
});
|
||||
|
||||
it("should display room member list when payload has a falsy event", () => {
|
||||
const payload = {
|
||||
action: Action.View3pidInvite,
|
||||
};
|
||||
onView3pidInvite(payload, rightPanelStore);
|
||||
|
||||
expect(rightPanelStore.showOrHidePhase).toHaveBeenCalledWith(RightPanelPhases.RoomMemberList);
|
||||
expect(rightPanelStore.pushCard).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should push a 3pid member card on the right panel stack when payload has an event", () => {
|
||||
const payload = {
|
||||
action: Action.View3pidInvite,
|
||||
event: new MatrixEvent({ type: EventType.RoomThirdPartyInvite }),
|
||||
};
|
||||
onView3pidInvite(payload, rightPanelStore);
|
||||
|
||||
expect(rightPanelStore.showOrHidePhase).not.toHaveBeenCalled();
|
||||
expect(rightPanelStore.pushCard).toHaveBeenCalledWith({
|
||||
phase: RightPanelPhases.Room3pidMemberInfo,
|
||||
state: { memberInfoEvent: payload.event },
|
||||
});
|
||||
});
|
||||
});
|
376
test/unit-tests/stores/room-list/MessagePreviewStore-test.ts
Normal file
376
test/unit-tests/stores/room-list/MessagePreviewStore-test.ts
Normal file
|
@ -0,0 +1,376 @@
|
|||
/*
|
||||
Copyright 2024 New Vector Ltd.
|
||||
Copyright 2023 The Matrix.org Foundation C.I.C.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { Mocked, mocked } from "jest-mock";
|
||||
import {
|
||||
EventStatus,
|
||||
EventTimeline,
|
||||
EventType,
|
||||
MatrixClient,
|
||||
MatrixEvent,
|
||||
PendingEventOrdering,
|
||||
RelationType,
|
||||
Room,
|
||||
} from "matrix-js-sdk/src/matrix";
|
||||
|
||||
import { MessagePreviewStore } from "../../../../src/stores/room-list/MessagePreviewStore";
|
||||
import { mkEvent, mkMessage, mkReaction, setupAsyncStoreWithClient, stubClient } from "../../../test-utils";
|
||||
import { DefaultTagID } from "../../../../src/stores/room-list/models";
|
||||
import { mkThread } from "../../../test-utils/threads";
|
||||
|
||||
describe("MessagePreviewStore", () => {
|
||||
let client: Mocked<MatrixClient>;
|
||||
let room: Room;
|
||||
let nonRenderedRoom: Room;
|
||||
let store: MessagePreviewStore;
|
||||
|
||||
async function addEvent(
|
||||
store: MessagePreviewStore,
|
||||
room: Room,
|
||||
event: MatrixEvent,
|
||||
fireAction = true,
|
||||
): Promise<void> {
|
||||
room.addLiveEvents([event]);
|
||||
if (fireAction) {
|
||||
// @ts-ignore private access
|
||||
await store.onAction({
|
||||
action: "MatrixActions.Room.timeline",
|
||||
event,
|
||||
isLiveEvent: true,
|
||||
isLiveUnfilteredRoomTimelineEvent: true,
|
||||
room,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function addPendingEvent(
|
||||
store: MessagePreviewStore,
|
||||
room: Room,
|
||||
event: MatrixEvent,
|
||||
fireAction = true,
|
||||
): Promise<void> {
|
||||
room.addPendingEvent(event, "txid");
|
||||
if (fireAction) {
|
||||
// @ts-ignore private access
|
||||
await store.onLocalEchoUpdated(event, room);
|
||||
}
|
||||
}
|
||||
|
||||
async function updatePendingEvent(event: MatrixEvent, eventStatus: EventStatus, fireAction = true): Promise<void> {
|
||||
room.updatePendingEvent(event, eventStatus);
|
||||
if (fireAction) {
|
||||
// @ts-ignore private access
|
||||
await store.onLocalEchoUpdated(event, room);
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
client = mocked(stubClient());
|
||||
room = new Room("!roomId:server", client, client.getSafeUserId(), {
|
||||
pendingEventOrdering: PendingEventOrdering.Detached,
|
||||
});
|
||||
nonRenderedRoom = new Room("!roomId2:server", client, client.getSafeUserId(), {
|
||||
pendingEventOrdering: PendingEventOrdering.Detached,
|
||||
});
|
||||
mocked(client.getRoom).mockReturnValue(room);
|
||||
|
||||
store = MessagePreviewStore.testInstance();
|
||||
await store.start();
|
||||
await setupAsyncStoreWithClient(store, client);
|
||||
});
|
||||
|
||||
it("should ignore edits for events other than the latest one", async () => {
|
||||
const firstMessage = mkMessage({
|
||||
user: "@sender:server",
|
||||
event: true,
|
||||
room: room.roomId,
|
||||
msg: "First message",
|
||||
});
|
||||
await addEvent(store, room, firstMessage, false);
|
||||
|
||||
expect((await store.getPreviewForRoom(room, DefaultTagID.Untagged))?.text).toMatchInlineSnapshot(
|
||||
`"@sender:server: First message"`,
|
||||
);
|
||||
|
||||
const secondMessage = mkMessage({
|
||||
user: "@sender:server",
|
||||
event: true,
|
||||
room: room.roomId,
|
||||
msg: "Second message",
|
||||
});
|
||||
await addEvent(store, room, secondMessage);
|
||||
|
||||
expect((await store.getPreviewForRoom(room, DefaultTagID.Untagged))?.text).toMatchInlineSnapshot(
|
||||
`"@sender:server: Second message"`,
|
||||
);
|
||||
|
||||
const firstMessageEdit = mkEvent({
|
||||
event: true,
|
||||
type: EventType.RoomMessage,
|
||||
user: "@sender:server",
|
||||
room: room.roomId,
|
||||
content: {
|
||||
"body": "* First Message Edit",
|
||||
"m.new_content": {
|
||||
body: "First Message Edit",
|
||||
},
|
||||
"m.relates_to": {
|
||||
rel_type: RelationType.Replace,
|
||||
event_id: firstMessage.getId()!,
|
||||
},
|
||||
},
|
||||
});
|
||||
await addEvent(store, room, firstMessageEdit);
|
||||
|
||||
expect((await store.getPreviewForRoom(room, DefaultTagID.Untagged))?.text).toMatchInlineSnapshot(
|
||||
`"@sender:server: Second message"`,
|
||||
);
|
||||
|
||||
const secondMessageEdit = mkEvent({
|
||||
event: true,
|
||||
type: EventType.RoomMessage,
|
||||
user: "@sender:server",
|
||||
room: room.roomId,
|
||||
content: {
|
||||
"body": "* Second Message Edit",
|
||||
"m.new_content": {
|
||||
body: "Second Message Edit",
|
||||
},
|
||||
"m.relates_to": {
|
||||
rel_type: RelationType.Replace,
|
||||
event_id: secondMessage.getId()!,
|
||||
},
|
||||
},
|
||||
});
|
||||
await addEvent(store, room, secondMessageEdit);
|
||||
|
||||
expect((await store.getPreviewForRoom(room, DefaultTagID.Untagged))?.text).toMatchInlineSnapshot(
|
||||
`"@sender:server: Second Message Edit"`,
|
||||
);
|
||||
});
|
||||
|
||||
it("should not display a redacted edit", async () => {
|
||||
const firstMessage = mkMessage({
|
||||
user: "@sender:server",
|
||||
event: true,
|
||||
room: room.roomId,
|
||||
msg: "First message",
|
||||
});
|
||||
await addEvent(store, room, firstMessage, false);
|
||||
|
||||
expect((await store.getPreviewForRoom(room, DefaultTagID.Untagged))?.text).toMatchInlineSnapshot(
|
||||
`"@sender:server: First message"`,
|
||||
);
|
||||
|
||||
const secondMessage = mkMessage({
|
||||
user: "@sender:server",
|
||||
event: true,
|
||||
room: room.roomId,
|
||||
msg: "Second message",
|
||||
});
|
||||
await addEvent(store, room, secondMessage);
|
||||
|
||||
expect((await store.getPreviewForRoom(room, DefaultTagID.Untagged))?.text).toMatchInlineSnapshot(
|
||||
`"@sender:server: Second message"`,
|
||||
);
|
||||
|
||||
const secondMessageEdit = mkEvent({
|
||||
event: true,
|
||||
type: EventType.RoomMessage,
|
||||
user: "@sender:server",
|
||||
room: room.roomId,
|
||||
content: {
|
||||
"body": "* Second Message Edit",
|
||||
"m.new_content": {
|
||||
body: "Second Message Edit",
|
||||
},
|
||||
"m.relates_to": {
|
||||
rel_type: RelationType.Replace,
|
||||
event_id: secondMessage.getId()!,
|
||||
},
|
||||
},
|
||||
});
|
||||
await addEvent(store, room, secondMessageEdit);
|
||||
|
||||
expect((await store.getPreviewForRoom(room, DefaultTagID.Untagged))?.text).toMatchInlineSnapshot(
|
||||
`"@sender:server: Second Message Edit"`,
|
||||
);
|
||||
|
||||
secondMessage.makeRedacted(secondMessage, room);
|
||||
|
||||
await addEvent(store, room, secondMessage);
|
||||
|
||||
expect((await store.getPreviewForRoom(room, DefaultTagID.Untagged))?.text).toMatchInlineSnapshot(
|
||||
`"@sender:server: First message"`,
|
||||
);
|
||||
});
|
||||
|
||||
it("should ignore edits to unknown events", async () => {
|
||||
await expect(store.getPreviewForRoom(room, DefaultTagID.DM)).resolves.toBeNull();
|
||||
|
||||
const firstMessage = mkMessage({
|
||||
user: "@sender:server",
|
||||
event: true,
|
||||
room: room.roomId,
|
||||
msg: "First message",
|
||||
});
|
||||
await addEvent(store, room, firstMessage, true);
|
||||
|
||||
expect((await store.getPreviewForRoom(room, DefaultTagID.DM))?.text).toMatchInlineSnapshot(
|
||||
`"@sender:server: First message"`,
|
||||
);
|
||||
|
||||
const randomEdit = mkEvent({
|
||||
event: true,
|
||||
type: EventType.RoomMessage,
|
||||
user: "@sender:server",
|
||||
room: room.roomId,
|
||||
content: {
|
||||
"body": "* Second Message Edit",
|
||||
"m.new_content": {
|
||||
body: "Second Message Edit",
|
||||
},
|
||||
"m.relates_to": {
|
||||
rel_type: RelationType.Replace,
|
||||
event_id: "!other-event:server",
|
||||
},
|
||||
},
|
||||
});
|
||||
await addEvent(store, room, randomEdit);
|
||||
|
||||
expect((await store.getPreviewForRoom(room, DefaultTagID.Untagged))?.text).toMatchInlineSnapshot(
|
||||
`"@sender:server: First message"`,
|
||||
);
|
||||
});
|
||||
|
||||
it("should generate correct preview for message events in DMs", async () => {
|
||||
room.getLiveTimeline().getState(EventTimeline.FORWARDS)!.getJoinedMemberCount = jest.fn().mockReturnValue(2);
|
||||
|
||||
await expect(store.getPreviewForRoom(room, DefaultTagID.DM)).resolves.toBeNull();
|
||||
|
||||
const firstMessage = mkMessage({
|
||||
user: "@sender:server",
|
||||
event: true,
|
||||
room: room.roomId,
|
||||
msg: "First message",
|
||||
});
|
||||
await addEvent(store, room, firstMessage);
|
||||
|
||||
expect((await store.getPreviewForRoom(room, DefaultTagID.DM))?.text).toMatchInlineSnapshot(
|
||||
`"@sender:server: First message"`,
|
||||
);
|
||||
|
||||
const secondMessage = mkMessage({
|
||||
user: "@sender:server",
|
||||
event: true,
|
||||
room: room.roomId,
|
||||
msg: "Second message",
|
||||
});
|
||||
await addEvent(store, room, secondMessage);
|
||||
|
||||
expect((await store.getPreviewForRoom(room, DefaultTagID.DM))?.text).toMatchInlineSnapshot(
|
||||
`"@sender:server: Second message"`,
|
||||
);
|
||||
});
|
||||
|
||||
it("should generate the correct preview for a reaction", async () => {
|
||||
const firstMessage = mkMessage({
|
||||
user: "@sender:server",
|
||||
event: true,
|
||||
room: room.roomId,
|
||||
msg: "First message",
|
||||
});
|
||||
await addEvent(store, room, firstMessage);
|
||||
|
||||
const reaction = mkReaction(firstMessage);
|
||||
await addEvent(store, room, reaction);
|
||||
|
||||
const preview = await store.getPreviewForRoom(room, DefaultTagID.Untagged);
|
||||
expect(preview).toBeDefined();
|
||||
expect(preview?.isThreadReply).toBe(false);
|
||||
expect(preview?.text).toMatchInlineSnapshot(`"@sender:server reacted 🙃 to First message"`);
|
||||
});
|
||||
|
||||
it("should generate the correct preview for a reaction on a thread root", async () => {
|
||||
const { rootEvent, thread } = mkThread({
|
||||
room,
|
||||
client,
|
||||
authorId: client.getSafeUserId(),
|
||||
participantUserIds: [client.getSafeUserId()],
|
||||
});
|
||||
await addEvent(store, room, rootEvent);
|
||||
|
||||
const reaction = mkReaction(rootEvent, { ts: 42 });
|
||||
reaction.setThread(thread);
|
||||
await addEvent(store, room, reaction);
|
||||
|
||||
const preview = await store.getPreviewForRoom(room, DefaultTagID.Untagged);
|
||||
expect(preview).toBeDefined();
|
||||
expect(preview?.isThreadReply).toBe(false);
|
||||
expect(preview?.text).toContain("You reacted 🙃 to root event message");
|
||||
});
|
||||
|
||||
it("should handle local echos correctly", async () => {
|
||||
const firstMessage = mkMessage({
|
||||
user: "@sender:server",
|
||||
event: true,
|
||||
room: room.roomId,
|
||||
msg: "First message",
|
||||
});
|
||||
|
||||
await addEvent(store, room, firstMessage);
|
||||
|
||||
expect((await store.getPreviewForRoom(room, DefaultTagID.Untagged))?.text).toMatchInlineSnapshot(
|
||||
`"@sender:server: First message"`,
|
||||
);
|
||||
|
||||
const secondMessage = mkMessage({
|
||||
user: "@sender:server",
|
||||
event: true,
|
||||
room: room.roomId,
|
||||
msg: "Second message",
|
||||
});
|
||||
secondMessage.status = EventStatus.NOT_SENT;
|
||||
|
||||
await addPendingEvent(store, room, secondMessage);
|
||||
|
||||
expect((await store.getPreviewForRoom(room, DefaultTagID.Untagged))?.text).toMatchInlineSnapshot(
|
||||
`"@sender:server: Second message"`,
|
||||
);
|
||||
|
||||
await updatePendingEvent(secondMessage, EventStatus.CANCELLED);
|
||||
|
||||
expect((await store.getPreviewForRoom(room, DefaultTagID.Untagged))?.text).toMatchInlineSnapshot(
|
||||
`"@sender:server: First message"`,
|
||||
);
|
||||
});
|
||||
|
||||
it("should not generate previews for rooms not rendered", async () => {
|
||||
const firstMessage = mkMessage({
|
||||
user: "@sender:server",
|
||||
event: true,
|
||||
room: nonRenderedRoom.roomId,
|
||||
msg: "First message",
|
||||
});
|
||||
|
||||
await addEvent(store, room, firstMessage);
|
||||
|
||||
const secondMessage = mkMessage({
|
||||
user: "@sender:server",
|
||||
event: true,
|
||||
room: nonRenderedRoom.roomId,
|
||||
msg: "Second message",
|
||||
});
|
||||
secondMessage.status = EventStatus.NOT_SENT;
|
||||
|
||||
await addPendingEvent(store, room, secondMessage);
|
||||
|
||||
// @ts-ignore private access
|
||||
expect(store.previews.has(nonRenderedRoom.roomId)).toBeFalsy();
|
||||
});
|
||||
});
|
394
test/unit-tests/stores/room-list/RoomListStore-test.ts
Normal file
394
test/unit-tests/stores/room-list/RoomListStore-test.ts
Normal file
|
@ -0,0 +1,394 @@
|
|||
/*
|
||||
Copyright 2024 New Vector Ltd.
|
||||
Copyright 2022 The Matrix.org Foundation C.I.C.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import {
|
||||
ConditionKind,
|
||||
EventType,
|
||||
IPushRule,
|
||||
JoinRule,
|
||||
MatrixEvent,
|
||||
PendingEventOrdering,
|
||||
PushRuleActionName,
|
||||
Room,
|
||||
} from "matrix-js-sdk/src/matrix";
|
||||
import { KnownMembership } from "matrix-js-sdk/src/types";
|
||||
import { mocked } from "jest-mock";
|
||||
|
||||
import defaultDispatcher, { MatrixDispatcher } from "../../../../src/dispatcher/dispatcher";
|
||||
import { SettingLevel } from "../../../../src/settings/SettingLevel";
|
||||
import SettingsStore, { CallbackFn } from "../../../../src/settings/SettingsStore";
|
||||
import { ListAlgorithm, SortAlgorithm } from "../../../../src/stores/room-list/algorithms/models";
|
||||
import { DefaultTagID, OrderedDefaultTagIDs, RoomUpdateCause } from "../../../../src/stores/room-list/models";
|
||||
import RoomListStore, { RoomListStoreClass } from "../../../../src/stores/room-list/RoomListStore";
|
||||
import DMRoomMap from "../../../../src/utils/DMRoomMap";
|
||||
import { flushPromises, stubClient, upsertRoomStateEvents, mkRoom } from "../../../test-utils";
|
||||
import { DEFAULT_PUSH_RULES, makePushRule } from "../../../test-utils/pushRules";
|
||||
|
||||
describe("RoomListStore", () => {
|
||||
const client = stubClient();
|
||||
const newRoomId = "!roomid:example.com";
|
||||
const roomNoPredecessorId = "!roomnopreid:example.com";
|
||||
const oldRoomId = "!oldroomid:example.com";
|
||||
const userId = "@user:example.com";
|
||||
const createWithPredecessor = new MatrixEvent({
|
||||
type: EventType.RoomCreate,
|
||||
sender: userId,
|
||||
room_id: newRoomId,
|
||||
content: {
|
||||
predecessor: { room_id: oldRoomId, event_id: "tombstone_event_id" },
|
||||
},
|
||||
event_id: "$create",
|
||||
state_key: "",
|
||||
});
|
||||
const createNoPredecessor = new MatrixEvent({
|
||||
type: EventType.RoomCreate,
|
||||
sender: userId,
|
||||
room_id: newRoomId,
|
||||
content: {},
|
||||
event_id: "$create",
|
||||
state_key: "",
|
||||
});
|
||||
const predecessor = new MatrixEvent({
|
||||
type: EventType.RoomPredecessor,
|
||||
sender: userId,
|
||||
room_id: newRoomId,
|
||||
content: {
|
||||
predecessor_room_id: oldRoomId,
|
||||
last_known_event_id: "tombstone_event_id",
|
||||
},
|
||||
event_id: "$pred",
|
||||
state_key: "",
|
||||
});
|
||||
const roomWithPredecessorEvent = new Room(newRoomId, client, userId, {});
|
||||
upsertRoomStateEvents(roomWithPredecessorEvent, [predecessor]);
|
||||
const roomWithCreatePredecessor = new Room(newRoomId, client, userId, {});
|
||||
upsertRoomStateEvents(roomWithCreatePredecessor, [createWithPredecessor]);
|
||||
const roomNoPredecessor = new Room(roomNoPredecessorId, client, userId, {
|
||||
pendingEventOrdering: PendingEventOrdering.Detached,
|
||||
});
|
||||
upsertRoomStateEvents(roomNoPredecessor, [createNoPredecessor]);
|
||||
const oldRoom = new Room(oldRoomId, client, userId, {});
|
||||
const normalRoom = new Room("!normal:server.org", client, userId);
|
||||
client.getRoom = jest.fn().mockImplementation((roomId) => {
|
||||
switch (roomId) {
|
||||
case newRoomId:
|
||||
return roomWithCreatePredecessor;
|
||||
case oldRoomId:
|
||||
return oldRoom;
|
||||
case normalRoom.roomId:
|
||||
return normalRoom;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
beforeAll(async () => {
|
||||
await (RoomListStore.instance as RoomListStoreClass).makeReady(client);
|
||||
});
|
||||
|
||||
it.each(OrderedDefaultTagIDs)("defaults to importance ordering for %s=", (tagId) => {
|
||||
expect(RoomListStore.instance.getTagSorting(tagId)).toBe(SortAlgorithm.Recent);
|
||||
});
|
||||
|
||||
it.each(OrderedDefaultTagIDs)("defaults to activity ordering for %s=", (tagId) => {
|
||||
expect(RoomListStore.instance.getListOrder(tagId)).toBe(ListAlgorithm.Natural);
|
||||
});
|
||||
|
||||
function createStore(): { store: RoomListStoreClass; handleRoomUpdate: jest.Mock<any, any> } {
|
||||
const fakeDispatcher = { register: jest.fn() } as unknown as MatrixDispatcher;
|
||||
const store = new RoomListStoreClass(fakeDispatcher);
|
||||
// @ts-ignore accessing private member to set client
|
||||
store.readyStore.matrixClient = client;
|
||||
const handleRoomUpdate = jest.fn();
|
||||
// @ts-ignore accessing private member to mock it
|
||||
store.algorithm.handleRoomUpdate = handleRoomUpdate;
|
||||
|
||||
return { store, handleRoomUpdate };
|
||||
}
|
||||
|
||||
it("Removes old room if it finds a predecessor in the create event", () => {
|
||||
// Given a store we can spy on
|
||||
const { store, handleRoomUpdate } = createStore();
|
||||
|
||||
// When we tell it we joined a new room that has an old room as
|
||||
// predecessor in the create event
|
||||
const payload = {
|
||||
oldMembership: KnownMembership.Invite,
|
||||
membership: KnownMembership.Join,
|
||||
room: roomWithCreatePredecessor,
|
||||
};
|
||||
store.onDispatchMyMembership(payload);
|
||||
|
||||
// Then the old room is removed
|
||||
expect(handleRoomUpdate).toHaveBeenCalledWith(oldRoom, RoomUpdateCause.RoomRemoved);
|
||||
|
||||
// And the new room is added
|
||||
expect(handleRoomUpdate).toHaveBeenCalledWith(roomWithCreatePredecessor, RoomUpdateCause.NewRoom);
|
||||
});
|
||||
|
||||
it("Does not remove old room if there is no predecessor in the create event", () => {
|
||||
// Given a store we can spy on
|
||||
const { store, handleRoomUpdate } = createStore();
|
||||
|
||||
// When we tell it we joined a new room with no predecessor
|
||||
const payload = {
|
||||
oldMembership: KnownMembership.Invite,
|
||||
membership: KnownMembership.Join,
|
||||
room: roomNoPredecessor,
|
||||
};
|
||||
store.onDispatchMyMembership(payload);
|
||||
|
||||
// Then the new room is added
|
||||
expect(handleRoomUpdate).toHaveBeenCalledWith(roomNoPredecessor, RoomUpdateCause.NewRoom);
|
||||
// And no other updates happen
|
||||
expect(handleRoomUpdate).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("Lists all rooms that the client says are visible", () => {
|
||||
// Given 3 rooms that are visible according to the client
|
||||
const room1 = new Room("!r1:e.com", client, userId, { pendingEventOrdering: PendingEventOrdering.Detached });
|
||||
const room2 = new Room("!r2:e.com", client, userId, { pendingEventOrdering: PendingEventOrdering.Detached });
|
||||
const room3 = new Room("!r3:e.com", client, userId, { pendingEventOrdering: PendingEventOrdering.Detached });
|
||||
room1.updateMyMembership(KnownMembership.Join);
|
||||
room2.updateMyMembership(KnownMembership.Join);
|
||||
room3.updateMyMembership(KnownMembership.Join);
|
||||
DMRoomMap.makeShared(client);
|
||||
const { store } = createStore();
|
||||
client.getVisibleRooms = jest.fn().mockReturnValue([room1, room2, room3]);
|
||||
|
||||
// When we make the list of rooms
|
||||
store.regenerateAllLists({ trigger: false });
|
||||
|
||||
// Then the list contains all 3
|
||||
expect(store.orderedLists).toMatchObject({
|
||||
"im.vector.fake.recent": [room1, room2, room3],
|
||||
});
|
||||
|
||||
// We asked not to use MSC3946 when we asked the client for the visible rooms
|
||||
expect(client.getVisibleRooms).toHaveBeenCalledWith(false);
|
||||
expect(client.getVisibleRooms).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("Watches the feature flag setting", () => {
|
||||
jest.spyOn(SettingsStore, "watchSetting").mockReturnValue("dyn_pred_ref");
|
||||
jest.spyOn(SettingsStore, "unwatchSetting");
|
||||
|
||||
// When we create a store
|
||||
const { store } = createStore();
|
||||
|
||||
// Then we watch the feature flag
|
||||
expect(SettingsStore.watchSetting).toHaveBeenCalledWith(
|
||||
"feature_dynamic_room_predecessors",
|
||||
null,
|
||||
expect.any(Function),
|
||||
);
|
||||
|
||||
// And when we unmount it
|
||||
store.componentWillUnmount();
|
||||
|
||||
// Then we unwatch it.
|
||||
expect(SettingsStore.unwatchSetting).toHaveBeenCalledWith("dyn_pred_ref");
|
||||
});
|
||||
|
||||
it("Regenerates all lists when the feature flag is set", () => {
|
||||
// Given a store allowing us to spy on any use of SettingsStore
|
||||
let featureFlagValue = false;
|
||||
jest.spyOn(SettingsStore, "getValue").mockImplementation(() => featureFlagValue);
|
||||
|
||||
let watchCallback: CallbackFn | undefined;
|
||||
jest.spyOn(SettingsStore, "watchSetting").mockImplementation(
|
||||
(_settingName: string, _roomId: string | null, callbackFn: CallbackFn) => {
|
||||
watchCallback = callbackFn;
|
||||
return "dyn_pred_ref";
|
||||
},
|
||||
);
|
||||
jest.spyOn(SettingsStore, "unwatchSetting");
|
||||
|
||||
const { store } = createStore();
|
||||
client.getVisibleRooms = jest.fn().mockReturnValue([]);
|
||||
// Sanity: no calculation has happened yet
|
||||
expect(client.getVisibleRooms).toHaveBeenCalledTimes(0);
|
||||
|
||||
// When we calculate for the first time
|
||||
store.regenerateAllLists({ trigger: false });
|
||||
|
||||
// Then we use the current feature flag value (false)
|
||||
expect(client.getVisibleRooms).toHaveBeenCalledWith(false);
|
||||
expect(client.getVisibleRooms).toHaveBeenCalledTimes(1);
|
||||
|
||||
// But when we update the feature flag
|
||||
featureFlagValue = true;
|
||||
watchCallback!(
|
||||
"feature_dynamic_room_predecessors",
|
||||
"",
|
||||
SettingLevel.DEFAULT,
|
||||
featureFlagValue,
|
||||
featureFlagValue,
|
||||
);
|
||||
|
||||
// Then we recalculate and passed the updated value (true)
|
||||
expect(client.getVisibleRooms).toHaveBeenCalledWith(true);
|
||||
expect(client.getVisibleRooms).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
describe("When feature_dynamic_room_predecessors = true", () => {
|
||||
beforeEach(() => {
|
||||
jest.spyOn(SettingsStore, "getValue").mockImplementation(
|
||||
(settingName) => settingName === "feature_dynamic_room_predecessors",
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.spyOn(SettingsStore, "getValue").mockReset();
|
||||
});
|
||||
|
||||
it("Removes old room if it finds a predecessor in the m.predecessor event", () => {
|
||||
// Given a store we can spy on
|
||||
const { store, handleRoomUpdate } = createStore();
|
||||
|
||||
// When we tell it we joined a new room that has an old room as
|
||||
// predecessor in the create event
|
||||
const payload = {
|
||||
oldMembership: KnownMembership.Invite,
|
||||
membership: KnownMembership.Join,
|
||||
room: roomWithPredecessorEvent,
|
||||
};
|
||||
store.onDispatchMyMembership(payload);
|
||||
|
||||
// Then the old room is removed
|
||||
expect(handleRoomUpdate).toHaveBeenCalledWith(oldRoom, RoomUpdateCause.RoomRemoved);
|
||||
|
||||
// And the new room is added
|
||||
expect(handleRoomUpdate).toHaveBeenCalledWith(roomWithPredecessorEvent, RoomUpdateCause.NewRoom);
|
||||
});
|
||||
|
||||
it("Passes the feature flag on to the client when asking for visible rooms", () => {
|
||||
// Given a store that we can ask for a room list
|
||||
DMRoomMap.makeShared(client);
|
||||
const { store } = createStore();
|
||||
client.getVisibleRooms = jest.fn().mockReturnValue([]);
|
||||
|
||||
// When we make the list of rooms
|
||||
store.regenerateAllLists({ trigger: false });
|
||||
|
||||
// We asked to use MSC3946 when we asked the client for the visible rooms
|
||||
expect(client.getVisibleRooms).toHaveBeenCalledWith(true);
|
||||
expect(client.getVisibleRooms).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("room updates", () => {
|
||||
const makeStore = async () => {
|
||||
const store = new RoomListStoreClass(defaultDispatcher);
|
||||
await store.start();
|
||||
return store;
|
||||
};
|
||||
|
||||
describe("push rules updates", () => {
|
||||
const makePushRulesEvent = (overrideRules: IPushRule[] = []): MatrixEvent => {
|
||||
return new MatrixEvent({
|
||||
type: EventType.PushRules,
|
||||
content: {
|
||||
global: {
|
||||
...DEFAULT_PUSH_RULES.global,
|
||||
override: overrideRules,
|
||||
},
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
it("triggers a room update when room mutes have changed", async () => {
|
||||
const rule = makePushRule(normalRoom.roomId, {
|
||||
actions: [PushRuleActionName.DontNotify],
|
||||
conditions: [{ kind: ConditionKind.EventMatch, key: "room_id", pattern: normalRoom.roomId }],
|
||||
});
|
||||
const event = makePushRulesEvent([rule]);
|
||||
const previousEvent = makePushRulesEvent();
|
||||
|
||||
const store = await makeStore();
|
||||
// @ts-ignore private property alg
|
||||
const algorithmSpy = jest.spyOn(store.algorithm, "handleRoomUpdate").mockReturnValue(undefined);
|
||||
// @ts-ignore cheat and call protected fn
|
||||
store.onAction({ action: "MatrixActions.accountData", event, previousEvent });
|
||||
await flushPromises();
|
||||
|
||||
expect(algorithmSpy).toHaveBeenCalledWith(normalRoom, RoomUpdateCause.PossibleMuteChange);
|
||||
});
|
||||
|
||||
it("handles when a muted room is unknown by the room list", async () => {
|
||||
const rule = makePushRule(normalRoom.roomId, {
|
||||
actions: [PushRuleActionName.DontNotify],
|
||||
conditions: [{ kind: ConditionKind.EventMatch, key: "room_id", pattern: normalRoom.roomId }],
|
||||
});
|
||||
const unknownRoomRule = makePushRule("!unknown:server.org", {
|
||||
conditions: [{ kind: ConditionKind.EventMatch, key: "room_id", pattern: "!unknown:server.org" }],
|
||||
});
|
||||
const event = makePushRulesEvent([unknownRoomRule, rule]);
|
||||
const previousEvent = makePushRulesEvent();
|
||||
|
||||
const store = await makeStore();
|
||||
// @ts-ignore private property alg
|
||||
const algorithmSpy = jest.spyOn(store.algorithm, "handleRoomUpdate").mockReturnValue(undefined);
|
||||
|
||||
// @ts-ignore cheat and call protected fn
|
||||
store.onAction({ action: "MatrixActions.accountData", event, previousEvent });
|
||||
await flushPromises();
|
||||
|
||||
// only one call to update made for normalRoom
|
||||
expect(algorithmSpy).toHaveBeenCalledTimes(1);
|
||||
expect(algorithmSpy).toHaveBeenCalledWith(normalRoom, RoomUpdateCause.PossibleMuteChange);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Correctly tags rooms", () => {
|
||||
it("renders Public and Knock rooms in Conferences section", () => {
|
||||
const videoRoomPrivate = "!videoRoomPrivate_server";
|
||||
const videoRoomPublic = "!videoRoomPublic_server";
|
||||
const videoRoomKnock = "!videoRoomKnock_server";
|
||||
|
||||
const rooms: Room[] = [];
|
||||
RoomListStore.instance;
|
||||
mkRoom(client, videoRoomPrivate, rooms);
|
||||
mkRoom(client, videoRoomPublic, rooms);
|
||||
mkRoom(client, videoRoomKnock, rooms);
|
||||
|
||||
mocked(client).getRoom.mockImplementation((roomId) => rooms.find((room) => room.roomId === roomId) || null);
|
||||
mocked(client).getRooms.mockImplementation(() => rooms);
|
||||
|
||||
const videoRoomKnockRoom = client.getRoom(videoRoomKnock);
|
||||
(videoRoomKnockRoom!.getJoinRule as jest.Mock).mockReturnValue(JoinRule.Knock);
|
||||
|
||||
const videoRoomPrivateRoom = client.getRoom(videoRoomPrivate);
|
||||
(videoRoomPrivateRoom!.getJoinRule as jest.Mock).mockReturnValue(JoinRule.Invite);
|
||||
|
||||
const videoRoomPublicRoom = client.getRoom(videoRoomPublic);
|
||||
(videoRoomPublicRoom!.getJoinRule as jest.Mock).mockReturnValue(JoinRule.Public);
|
||||
|
||||
[videoRoomPrivateRoom, videoRoomPublicRoom, videoRoomKnockRoom].forEach((room) => {
|
||||
(room!.isCallRoom as jest.Mock).mockReturnValue(true);
|
||||
});
|
||||
|
||||
expect(
|
||||
RoomListStore.instance
|
||||
.getTagsForRoom(client.getRoom(videoRoomPublic)!)
|
||||
.includes(DefaultTagID.Conference),
|
||||
).toBeTruthy();
|
||||
expect(
|
||||
RoomListStore.instance
|
||||
.getTagsForRoom(client.getRoom(videoRoomKnock)!)
|
||||
.includes(DefaultTagID.Conference),
|
||||
).toBeTruthy();
|
||||
expect(
|
||||
RoomListStore.instance
|
||||
.getTagsForRoom(client.getRoom(videoRoomPrivate)!)
|
||||
.includes(DefaultTagID.Conference),
|
||||
).toBeFalsy();
|
||||
});
|
||||
});
|
||||
});
|
341
test/unit-tests/stores/room-list/SlidingRoomListStore-test.ts
Normal file
341
test/unit-tests/stores/room-list/SlidingRoomListStore-test.ts
Normal file
|
@ -0,0 +1,341 @@
|
|||
/*
|
||||
Copyright 2024 New Vector Ltd.
|
||||
Copyright 2022 The Matrix.org Foundation C.I.C.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
import { mocked } from "jest-mock";
|
||||
import { SlidingSync, SlidingSyncEvent } from "matrix-js-sdk/src/sliding-sync";
|
||||
import { Room } from "matrix-js-sdk/src/matrix";
|
||||
|
||||
import {
|
||||
LISTS_UPDATE_EVENT,
|
||||
SlidingRoomListStoreClass,
|
||||
SlidingSyncSortToFilter,
|
||||
} from "../../../../src/stores/room-list/SlidingRoomListStore";
|
||||
import { SpaceStoreClass } from "../../../../src/stores/spaces/SpaceStore";
|
||||
import { MockEventEmitter, stubClient, untilEmission } from "../../../test-utils";
|
||||
import { TestSdkContext } from "../../TestSdkContext";
|
||||
import { SlidingSyncManager } from "../../../../src/SlidingSyncManager";
|
||||
import { RoomViewStore } from "../../../../src/stores/RoomViewStore";
|
||||
import { MatrixDispatcher } from "../../../../src/dispatcher/dispatcher";
|
||||
import { SortAlgorithm } from "../../../../src/stores/room-list/algorithms/models";
|
||||
import { DefaultTagID, TagID } from "../../../../src/stores/room-list/models";
|
||||
import { MetaSpace, UPDATE_SELECTED_SPACE } from "../../../../src/stores/spaces";
|
||||
import { LISTS_LOADING_EVENT } from "../../../../src/stores/room-list/RoomListStore";
|
||||
import { UPDATE_EVENT } from "../../../../src/stores/AsyncStore";
|
||||
|
||||
jest.mock("../../../../src/SlidingSyncManager");
|
||||
const MockSlidingSyncManager = <jest.Mock<SlidingSyncManager>>(<unknown>SlidingSyncManager);
|
||||
|
||||
describe("SlidingRoomListStore", () => {
|
||||
let store: SlidingRoomListStoreClass;
|
||||
let context: TestSdkContext;
|
||||
let dis: MatrixDispatcher;
|
||||
let activeSpace: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
context = new TestSdkContext();
|
||||
context.client = stubClient();
|
||||
context._SpaceStore = new MockEventEmitter<SpaceStoreClass>({
|
||||
traverseSpace: jest.fn(),
|
||||
get activeSpace() {
|
||||
return activeSpace;
|
||||
},
|
||||
}) as SpaceStoreClass;
|
||||
context._SlidingSyncManager = new MockSlidingSyncManager();
|
||||
context._SlidingSyncManager.slidingSync = mocked(
|
||||
new MockEventEmitter({
|
||||
getListData: jest.fn(),
|
||||
}) as unknown as SlidingSync,
|
||||
);
|
||||
context._RoomViewStore = mocked(
|
||||
new MockEventEmitter({
|
||||
getRoomId: jest.fn(),
|
||||
}) as unknown as RoomViewStore,
|
||||
);
|
||||
mocked(context._SlidingSyncManager.ensureListRegistered).mockResolvedValue({
|
||||
ranges: [[0, 10]],
|
||||
});
|
||||
|
||||
dis = new MatrixDispatcher();
|
||||
store = new SlidingRoomListStoreClass(dis, context);
|
||||
});
|
||||
|
||||
describe("spaces", () => {
|
||||
it("alters 'filters.spaces' on the DefaultTagID.Untagged list when the selected space changes", async () => {
|
||||
await store.start(); // call onReady
|
||||
const spaceRoomId = "!foo:bar";
|
||||
|
||||
const p = untilEmission(store, LISTS_LOADING_EVENT, (listName, isLoading) => {
|
||||
return listName === DefaultTagID.Untagged && !isLoading;
|
||||
});
|
||||
|
||||
// change the active space
|
||||
activeSpace = spaceRoomId;
|
||||
context._SpaceStore!.emit(UPDATE_SELECTED_SPACE, spaceRoomId, false);
|
||||
await p;
|
||||
|
||||
expect(context._SlidingSyncManager!.ensureListRegistered).toHaveBeenCalledWith(DefaultTagID.Untagged, {
|
||||
filters: expect.objectContaining({
|
||||
spaces: [spaceRoomId],
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
it("gracefully handles subspaces in the home metaspace", async () => {
|
||||
const subspace = "!sub:space";
|
||||
mocked(context._SpaceStore!.traverseSpace).mockImplementation(
|
||||
(spaceId: string, fn: (roomId: string) => void) => {
|
||||
fn(subspace);
|
||||
},
|
||||
);
|
||||
activeSpace = MetaSpace.Home;
|
||||
await store.start(); // call onReady
|
||||
|
||||
expect(context._SlidingSyncManager!.ensureListRegistered).toHaveBeenCalledWith(DefaultTagID.Untagged, {
|
||||
filters: expect.objectContaining({
|
||||
spaces: [subspace],
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
it("alters 'filters.spaces' on the DefaultTagID.Untagged list if it loads with an active space", async () => {
|
||||
// change the active space before we are ready
|
||||
const spaceRoomId = "!foo2:bar";
|
||||
activeSpace = spaceRoomId;
|
||||
const p = untilEmission(store, LISTS_LOADING_EVENT, (listName, isLoading) => {
|
||||
return listName === DefaultTagID.Untagged && !isLoading;
|
||||
});
|
||||
await store.start(); // call onReady
|
||||
await p;
|
||||
expect(context._SlidingSyncManager!.ensureListRegistered).toHaveBeenCalledWith(
|
||||
DefaultTagID.Untagged,
|
||||
expect.objectContaining({
|
||||
filters: expect.objectContaining({
|
||||
spaces: [spaceRoomId],
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("includes subspaces in 'filters.spaces' when the selected space has subspaces", async () => {
|
||||
await store.start(); // call onReady
|
||||
const spaceRoomId = "!foo:bar";
|
||||
const subSpace1 = "!ss1:bar";
|
||||
const subSpace2 = "!ss2:bar";
|
||||
|
||||
const p = untilEmission(store, LISTS_LOADING_EVENT, (listName, isLoading) => {
|
||||
return listName === DefaultTagID.Untagged && !isLoading;
|
||||
});
|
||||
|
||||
mocked(context._SpaceStore!.traverseSpace).mockImplementation(
|
||||
(spaceId: string, fn: (roomId: string) => void) => {
|
||||
if (spaceId === spaceRoomId) {
|
||||
fn(subSpace1);
|
||||
fn(subSpace2);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// change the active space
|
||||
activeSpace = spaceRoomId;
|
||||
context._SpaceStore!.emit(UPDATE_SELECTED_SPACE, spaceRoomId, false);
|
||||
await p;
|
||||
|
||||
expect(context._SlidingSyncManager!.ensureListRegistered).toHaveBeenCalledWith(DefaultTagID.Untagged, {
|
||||
filters: expect.objectContaining({
|
||||
spaces: [spaceRoomId, subSpace1, subSpace2],
|
||||
}),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it("setTagSorting alters the 'sort' option in the list", async () => {
|
||||
const tagId: TagID = "foo";
|
||||
await store.setTagSorting(tagId, SortAlgorithm.Alphabetic);
|
||||
expect(context._SlidingSyncManager!.ensureListRegistered).toHaveBeenCalledWith(tagId, {
|
||||
sort: SlidingSyncSortToFilter[SortAlgorithm.Alphabetic],
|
||||
});
|
||||
expect(store.getTagSorting(tagId)).toEqual(SortAlgorithm.Alphabetic);
|
||||
|
||||
await store.setTagSorting(tagId, SortAlgorithm.Recent);
|
||||
expect(context._SlidingSyncManager!.ensureListRegistered).toHaveBeenCalledWith(tagId, {
|
||||
sort: SlidingSyncSortToFilter[SortAlgorithm.Recent],
|
||||
});
|
||||
expect(store.getTagSorting(tagId)).toEqual(SortAlgorithm.Recent);
|
||||
});
|
||||
|
||||
it("getTagsForRoom gets the tags for the room", async () => {
|
||||
await store.start();
|
||||
const roomA = "!a:localhost";
|
||||
const roomB = "!b:localhost";
|
||||
const keyToListData: Record<string, { joinedCount: number; roomIndexToRoomId: Record<number, string> }> = {
|
||||
[DefaultTagID.Untagged]: {
|
||||
joinedCount: 10,
|
||||
roomIndexToRoomId: {
|
||||
0: roomA,
|
||||
1: roomB,
|
||||
},
|
||||
},
|
||||
[DefaultTagID.Favourite]: {
|
||||
joinedCount: 2,
|
||||
roomIndexToRoomId: {
|
||||
0: roomB,
|
||||
},
|
||||
},
|
||||
};
|
||||
mocked(context._SlidingSyncManager!.slidingSync!.getListData).mockImplementation((key: string) => {
|
||||
return keyToListData[key] || null;
|
||||
});
|
||||
|
||||
expect(store.getTagsForRoom(new Room(roomA, context.client!, context.client!.getUserId()!))).toEqual([
|
||||
DefaultTagID.Untagged,
|
||||
]);
|
||||
expect(store.getTagsForRoom(new Room(roomB, context.client!, context.client!.getUserId()!))).toEqual([
|
||||
DefaultTagID.Favourite,
|
||||
DefaultTagID.Untagged,
|
||||
]);
|
||||
});
|
||||
|
||||
it("emits LISTS_UPDATE_EVENT when slidingSync lists update", async () => {
|
||||
await store.start();
|
||||
const roomA = "!a:localhost";
|
||||
const roomB = "!b:localhost";
|
||||
const roomC = "!c:localhost";
|
||||
const tagId = DefaultTagID.Favourite;
|
||||
const joinCount = 10;
|
||||
const roomIndexToRoomId = {
|
||||
// mixed to ensure we sort
|
||||
1: roomB,
|
||||
2: roomC,
|
||||
0: roomA,
|
||||
};
|
||||
const rooms = [
|
||||
new Room(roomA, context.client!, context.client!.getUserId()!),
|
||||
new Room(roomB, context.client!, context.client!.getUserId()!),
|
||||
new Room(roomC, context.client!, context.client!.getUserId()!),
|
||||
];
|
||||
mocked(context.client!.getRoom).mockImplementation((roomId: string) => {
|
||||
switch (roomId) {
|
||||
case roomA:
|
||||
return rooms[0];
|
||||
case roomB:
|
||||
return rooms[1];
|
||||
case roomC:
|
||||
return rooms[2];
|
||||
}
|
||||
return null;
|
||||
});
|
||||
const p = untilEmission(store, LISTS_UPDATE_EVENT);
|
||||
context.slidingSyncManager.slidingSync!.emit(SlidingSyncEvent.List, tagId, joinCount, roomIndexToRoomId);
|
||||
await p;
|
||||
expect(store.getCount(tagId)).toEqual(joinCount);
|
||||
expect(store.orderedLists[tagId]).toEqual(rooms);
|
||||
});
|
||||
|
||||
it("sets the sticky room on the basis of the viewed room in RoomViewStore", async () => {
|
||||
await store.start();
|
||||
// seed the store with 3 rooms
|
||||
const roomIdA = "!a:localhost";
|
||||
const roomIdB = "!b:localhost";
|
||||
const roomIdC = "!c:localhost";
|
||||
const tagId = DefaultTagID.Favourite;
|
||||
const joinCount = 10;
|
||||
const roomIndexToRoomId = {
|
||||
// mixed to ensure we sort
|
||||
1: roomIdB,
|
||||
2: roomIdC,
|
||||
0: roomIdA,
|
||||
};
|
||||
const roomA = new Room(roomIdA, context.client!, context.client!.getUserId()!);
|
||||
const roomB = new Room(roomIdB, context.client!, context.client!.getUserId()!);
|
||||
const roomC = new Room(roomIdC, context.client!, context.client!.getUserId()!);
|
||||
mocked(context.client!.getRoom).mockImplementation((roomId: string) => {
|
||||
switch (roomId) {
|
||||
case roomIdA:
|
||||
return roomA;
|
||||
case roomIdB:
|
||||
return roomB;
|
||||
case roomIdC:
|
||||
return roomC;
|
||||
}
|
||||
return null;
|
||||
});
|
||||
mocked(context._SlidingSyncManager!.slidingSync!.getListData).mockImplementation((key: string) => {
|
||||
if (key !== tagId) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
roomIndexToRoomId: roomIndexToRoomId,
|
||||
joinedCount: joinCount,
|
||||
};
|
||||
});
|
||||
let p = untilEmission(store, LISTS_UPDATE_EVENT);
|
||||
context.slidingSyncManager.slidingSync!.emit(SlidingSyncEvent.List, tagId, joinCount, roomIndexToRoomId);
|
||||
await p;
|
||||
expect(store.orderedLists[tagId]).toEqual([roomA, roomB, roomC]);
|
||||
|
||||
// make roomB sticky and inform the store
|
||||
mocked(context.roomViewStore.getRoomId).mockReturnValue(roomIdB);
|
||||
context.roomViewStore.emit(UPDATE_EVENT);
|
||||
|
||||
// bump room C to the top, room B should not move from i=1 despite the list update saying to
|
||||
roomIndexToRoomId[0] = roomIdC;
|
||||
roomIndexToRoomId[1] = roomIdA;
|
||||
roomIndexToRoomId[2] = roomIdB;
|
||||
p = untilEmission(store, LISTS_UPDATE_EVENT);
|
||||
context.slidingSyncManager.slidingSync!.emit(SlidingSyncEvent.List, tagId, joinCount, roomIndexToRoomId);
|
||||
await p;
|
||||
|
||||
// check that B didn't move and that A was put below B
|
||||
expect(store.orderedLists[tagId]).toEqual([roomC, roomB, roomA]);
|
||||
|
||||
// make room C sticky: rooms should move as a result, without needing an additional list update
|
||||
mocked(context.roomViewStore.getRoomId).mockReturnValue(roomIdC);
|
||||
p = untilEmission(store, LISTS_UPDATE_EVENT);
|
||||
context.roomViewStore.emit(UPDATE_EVENT);
|
||||
await p;
|
||||
expect(store.orderedLists[tagId].map((r) => r.roomId)).toEqual([roomC, roomA, roomB].map((r) => r.roomId));
|
||||
});
|
||||
|
||||
it("gracefully handles unknown room IDs", async () => {
|
||||
await store.start();
|
||||
const roomIdA = "!a:localhost";
|
||||
const roomIdB = "!b:localhost"; // does not exist
|
||||
const roomIdC = "!c:localhost";
|
||||
const roomIndexToRoomId = {
|
||||
0: roomIdA,
|
||||
1: roomIdB, // does not exist
|
||||
2: roomIdC,
|
||||
};
|
||||
const tagId = DefaultTagID.Favourite;
|
||||
const joinCount = 10;
|
||||
// seed the store with 2 rooms
|
||||
const roomA = new Room(roomIdA, context.client!, context.client!.getUserId()!);
|
||||
const roomC = new Room(roomIdC, context.client!, context.client!.getUserId()!);
|
||||
mocked(context.client!.getRoom).mockImplementation((roomId: string) => {
|
||||
switch (roomId) {
|
||||
case roomIdA:
|
||||
return roomA;
|
||||
case roomIdC:
|
||||
return roomC;
|
||||
}
|
||||
return null;
|
||||
});
|
||||
mocked(context._SlidingSyncManager!.slidingSync!.getListData).mockImplementation((key: string) => {
|
||||
if (key !== tagId) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
roomIndexToRoomId: roomIndexToRoomId,
|
||||
joinedCount: joinCount,
|
||||
};
|
||||
});
|
||||
const p = untilEmission(store, LISTS_UPDATE_EVENT);
|
||||
context.slidingSyncManager.slidingSync!.emit(SlidingSyncEvent.List, tagId, joinCount, roomIndexToRoomId);
|
||||
await p;
|
||||
expect(store.orderedLists[tagId]).toEqual([roomA, roomC]);
|
||||
});
|
||||
});
|
252
test/unit-tests/stores/room-list/SpaceWatcher-test.ts
Normal file
252
test/unit-tests/stores/room-list/SpaceWatcher-test.ts
Normal file
|
@ -0,0 +1,252 @@
|
|||
/*
|
||||
Copyright 2024 New Vector Ltd.
|
||||
Copyright 2021 The Matrix.org Foundation C.I.C.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { mocked } from "jest-mock";
|
||||
import { Room } from "matrix-js-sdk/src/matrix";
|
||||
|
||||
import { SpaceWatcher } from "../../../../src/stores/room-list/SpaceWatcher";
|
||||
import type { RoomListStoreClass } from "../../../../src/stores/room-list/RoomListStore";
|
||||
import SettingsStore from "../../../../src/settings/SettingsStore";
|
||||
import SpaceStore from "../../../../src/stores/spaces/SpaceStore";
|
||||
import { MetaSpace, UPDATE_HOME_BEHAVIOUR } from "../../../../src/stores/spaces";
|
||||
import { stubClient, mkSpace, emitPromise, setupAsyncStoreWithClient } from "../../../test-utils";
|
||||
import { SettingLevel } from "../../../../src/settings/SettingLevel";
|
||||
import { MatrixClientPeg } from "../../../../src/MatrixClientPeg";
|
||||
import { SpaceFilterCondition } from "../../../../src/stores/room-list/filters/SpaceFilterCondition";
|
||||
import DMRoomMap from "../../../../src/utils/DMRoomMap";
|
||||
|
||||
let filter: SpaceFilterCondition | null = null;
|
||||
|
||||
const mockRoomListStore = {
|
||||
addFilter: (f: SpaceFilterCondition) => (filter = f),
|
||||
removeFilter: (): void => {
|
||||
filter = null;
|
||||
},
|
||||
} as unknown as RoomListStoreClass;
|
||||
|
||||
const getUserIdForRoomId = jest.fn();
|
||||
const getDMRoomsForUserId = jest.fn();
|
||||
// @ts-ignore
|
||||
DMRoomMap.sharedInstance = { getUserIdForRoomId, getDMRoomsForUserId };
|
||||
|
||||
const space1 = "!space1:server";
|
||||
const space2 = "!space2:server";
|
||||
|
||||
describe("SpaceWatcher", () => {
|
||||
stubClient();
|
||||
const store = SpaceStore.instance;
|
||||
const client = mocked(MatrixClientPeg.safeGet());
|
||||
|
||||
let rooms: Room[] = [];
|
||||
const mkSpaceForRooms = (spaceId: string, children: string[] = []) => mkSpace(client, spaceId, rooms, children);
|
||||
|
||||
const setShowAllRooms = async (value: boolean) => {
|
||||
if (store.allRoomsInHome === value) return;
|
||||
await SettingsStore.setValue("Spaces.allRoomsInHome", null, SettingLevel.DEVICE, value);
|
||||
await emitPromise(store, UPDATE_HOME_BEHAVIOUR);
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
filter = null;
|
||||
store.removeAllListeners();
|
||||
store.setActiveSpace(MetaSpace.Home);
|
||||
client.getVisibleRooms.mockReturnValue((rooms = []));
|
||||
|
||||
mkSpaceForRooms(space1);
|
||||
mkSpaceForRooms(space2);
|
||||
|
||||
await SettingsStore.setValue("Spaces.enabledMetaSpaces", null, SettingLevel.DEVICE, {
|
||||
[MetaSpace.Home]: true,
|
||||
[MetaSpace.Favourites]: true,
|
||||
[MetaSpace.People]: true,
|
||||
[MetaSpace.Orphans]: true,
|
||||
});
|
||||
|
||||
client.getRoom.mockImplementation((roomId) => rooms.find((room) => room.roomId === roomId) || null);
|
||||
await setupAsyncStoreWithClient(store, client);
|
||||
});
|
||||
|
||||
it("initialises sanely with home behaviour", async () => {
|
||||
await setShowAllRooms(false);
|
||||
new SpaceWatcher(mockRoomListStore);
|
||||
|
||||
expect(filter).toBeInstanceOf(SpaceFilterCondition);
|
||||
});
|
||||
|
||||
it("initialises sanely with all behaviour", async () => {
|
||||
await setShowAllRooms(true);
|
||||
new SpaceWatcher(mockRoomListStore);
|
||||
|
||||
expect(filter).toBeNull();
|
||||
});
|
||||
|
||||
it("sets space=Home filter for all -> home transition", async () => {
|
||||
await setShowAllRooms(true);
|
||||
new SpaceWatcher(mockRoomListStore);
|
||||
|
||||
await setShowAllRooms(false);
|
||||
|
||||
expect(filter).toBeInstanceOf(SpaceFilterCondition);
|
||||
expect(filter!["space"]).toBe(MetaSpace.Home);
|
||||
});
|
||||
|
||||
it("sets filter correctly for all -> space transition", async () => {
|
||||
await setShowAllRooms(true);
|
||||
new SpaceWatcher(mockRoomListStore);
|
||||
|
||||
SpaceStore.instance.setActiveSpace(space1);
|
||||
|
||||
expect(filter).toBeInstanceOf(SpaceFilterCondition);
|
||||
expect(filter!["space"]).toBe(space1);
|
||||
});
|
||||
|
||||
it("removes filter for home -> all transition", async () => {
|
||||
await setShowAllRooms(false);
|
||||
new SpaceWatcher(mockRoomListStore);
|
||||
|
||||
await setShowAllRooms(true);
|
||||
|
||||
expect(filter).toBeNull();
|
||||
});
|
||||
|
||||
it("sets filter correctly for home -> space transition", async () => {
|
||||
await setShowAllRooms(false);
|
||||
new SpaceWatcher(mockRoomListStore);
|
||||
|
||||
SpaceStore.instance.setActiveSpace(space1);
|
||||
|
||||
expect(filter).toBeInstanceOf(SpaceFilterCondition);
|
||||
expect(filter!["space"]).toBe(space1);
|
||||
});
|
||||
|
||||
it("removes filter for space -> all transition", async () => {
|
||||
await setShowAllRooms(true);
|
||||
new SpaceWatcher(mockRoomListStore);
|
||||
|
||||
SpaceStore.instance.setActiveSpace(space1);
|
||||
expect(filter).toBeInstanceOf(SpaceFilterCondition);
|
||||
expect(filter!["space"]).toBe(space1);
|
||||
SpaceStore.instance.setActiveSpace(MetaSpace.Home);
|
||||
|
||||
expect(filter).toBeNull();
|
||||
});
|
||||
|
||||
it("removes filter for favourites -> all transition", async () => {
|
||||
await setShowAllRooms(true);
|
||||
new SpaceWatcher(mockRoomListStore);
|
||||
|
||||
SpaceStore.instance.setActiveSpace(MetaSpace.Favourites);
|
||||
expect(filter).toBeInstanceOf(SpaceFilterCondition);
|
||||
expect(filter!["space"]).toBe(MetaSpace.Favourites);
|
||||
SpaceStore.instance.setActiveSpace(MetaSpace.Home);
|
||||
|
||||
expect(filter).toBeNull();
|
||||
});
|
||||
|
||||
it("removes filter for people -> all transition", async () => {
|
||||
await setShowAllRooms(true);
|
||||
new SpaceWatcher(mockRoomListStore);
|
||||
|
||||
SpaceStore.instance.setActiveSpace(MetaSpace.People);
|
||||
expect(filter).toBeInstanceOf(SpaceFilterCondition);
|
||||
expect(filter!["space"]).toBe(MetaSpace.People);
|
||||
SpaceStore.instance.setActiveSpace(MetaSpace.Home);
|
||||
|
||||
expect(filter).toBeNull();
|
||||
});
|
||||
|
||||
it("removes filter for orphans -> all transition", async () => {
|
||||
await setShowAllRooms(true);
|
||||
new SpaceWatcher(mockRoomListStore);
|
||||
|
||||
SpaceStore.instance.setActiveSpace(MetaSpace.Orphans);
|
||||
expect(filter).toBeInstanceOf(SpaceFilterCondition);
|
||||
expect(filter!["space"]).toBe(MetaSpace.Orphans);
|
||||
SpaceStore.instance.setActiveSpace(MetaSpace.Home);
|
||||
|
||||
expect(filter).toBeNull();
|
||||
});
|
||||
|
||||
it("updates filter correctly for space -> home transition", async () => {
|
||||
await setShowAllRooms(false);
|
||||
SpaceStore.instance.setActiveSpace(space1);
|
||||
|
||||
new SpaceWatcher(mockRoomListStore);
|
||||
expect(filter).toBeInstanceOf(SpaceFilterCondition);
|
||||
expect(filter!["space"]).toBe(space1);
|
||||
SpaceStore.instance.setActiveSpace(MetaSpace.Home);
|
||||
|
||||
expect(filter).toBeInstanceOf(SpaceFilterCondition);
|
||||
expect(filter!["space"]).toBe(MetaSpace.Home);
|
||||
});
|
||||
|
||||
it("updates filter correctly for space -> orphans transition", async () => {
|
||||
await setShowAllRooms(false);
|
||||
SpaceStore.instance.setActiveSpace(space1);
|
||||
|
||||
new SpaceWatcher(mockRoomListStore);
|
||||
expect(filter).toBeInstanceOf(SpaceFilterCondition);
|
||||
expect(filter!["space"]).toBe(space1);
|
||||
SpaceStore.instance.setActiveSpace(MetaSpace.Orphans);
|
||||
|
||||
expect(filter).toBeInstanceOf(SpaceFilterCondition);
|
||||
expect(filter!["space"]).toBe(MetaSpace.Orphans);
|
||||
});
|
||||
|
||||
it("updates filter correctly for orphans -> people transition", async () => {
|
||||
await setShowAllRooms(false);
|
||||
SpaceStore.instance.setActiveSpace(MetaSpace.Orphans);
|
||||
|
||||
new SpaceWatcher(mockRoomListStore);
|
||||
expect(filter).toBeInstanceOf(SpaceFilterCondition);
|
||||
expect(filter!["space"]).toBe(MetaSpace.Orphans);
|
||||
SpaceStore.instance.setActiveSpace(MetaSpace.People);
|
||||
|
||||
expect(filter).toBeInstanceOf(SpaceFilterCondition);
|
||||
expect(filter!["space"]).toBe(MetaSpace.People);
|
||||
});
|
||||
|
||||
it("updates filter correctly for space -> space transition", async () => {
|
||||
await setShowAllRooms(false);
|
||||
SpaceStore.instance.setActiveSpace(space1);
|
||||
|
||||
new SpaceWatcher(mockRoomListStore);
|
||||
expect(filter).toBeInstanceOf(SpaceFilterCondition);
|
||||
expect(filter!["space"]).toBe(space1);
|
||||
SpaceStore.instance.setActiveSpace(space2);
|
||||
|
||||
expect(filter).toBeInstanceOf(SpaceFilterCondition);
|
||||
expect(filter!["space"]).toBe(space2);
|
||||
});
|
||||
|
||||
it("doesn't change filter when changing showAllRooms mode to true", async () => {
|
||||
await setShowAllRooms(false);
|
||||
SpaceStore.instance.setActiveSpace(space1);
|
||||
|
||||
new SpaceWatcher(mockRoomListStore);
|
||||
expect(filter).toBeInstanceOf(SpaceFilterCondition);
|
||||
expect(filter!["space"]).toBe(space1);
|
||||
await setShowAllRooms(true);
|
||||
|
||||
expect(filter).toBeInstanceOf(SpaceFilterCondition);
|
||||
expect(filter!["space"]).toBe(space1);
|
||||
});
|
||||
|
||||
it("doesn't change filter when changing showAllRooms mode to false", async () => {
|
||||
await setShowAllRooms(true);
|
||||
SpaceStore.instance.setActiveSpace(space1);
|
||||
|
||||
new SpaceWatcher(mockRoomListStore);
|
||||
expect(filter).toBeInstanceOf(SpaceFilterCondition);
|
||||
expect(filter!["space"]).toBe(space1);
|
||||
await setShowAllRooms(false);
|
||||
|
||||
expect(filter).toBeInstanceOf(SpaceFilterCondition);
|
||||
expect(filter!["space"]).toBe(space1);
|
||||
});
|
||||
});
|
101
test/unit-tests/stores/room-list/algorithms/Algorithm-test.ts
Normal file
101
test/unit-tests/stores/room-list/algorithms/Algorithm-test.ts
Normal file
|
@ -0,0 +1,101 @@
|
|||
/*
|
||||
Copyright 2024 New Vector Ltd.
|
||||
Copyright 2022 The Matrix.org Foundation C.I.C.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { mocked, MockedObject } from "jest-mock";
|
||||
import { PendingEventOrdering, Room, RoomStateEvent } from "matrix-js-sdk/src/matrix";
|
||||
import { KnownMembership } from "matrix-js-sdk/src/types";
|
||||
import { Widget } from "matrix-widget-api";
|
||||
|
||||
import type { MatrixClient } from "matrix-js-sdk/src/matrix";
|
||||
import type { ClientWidgetApi } from "matrix-widget-api";
|
||||
import {
|
||||
stubClient,
|
||||
setupAsyncStoreWithClient,
|
||||
useMockedCalls,
|
||||
MockedCall,
|
||||
useMockMediaDevices,
|
||||
} from "../../../../test-utils";
|
||||
import { MatrixClientPeg } from "../../../../../src/MatrixClientPeg";
|
||||
import DMRoomMap from "../../../../../src/utils/DMRoomMap";
|
||||
import { DefaultTagID } from "../../../../../src/stores/room-list/models";
|
||||
import { SortAlgorithm, ListAlgorithm } from "../../../../../src/stores/room-list/algorithms/models";
|
||||
import "../../../../../src/stores/room-list/RoomListStore"; // must be imported before Algorithm to avoid cycles
|
||||
import { Algorithm } from "../../../../../src/stores/room-list/algorithms/Algorithm";
|
||||
import { CallStore } from "../../../../../src/stores/CallStore";
|
||||
import { WidgetMessagingStore } from "../../../../../src/stores/widgets/WidgetMessagingStore";
|
||||
|
||||
describe("Algorithm", () => {
|
||||
useMockedCalls();
|
||||
|
||||
let client: MockedObject<MatrixClient>;
|
||||
let algorithm: Algorithm;
|
||||
|
||||
beforeEach(() => {
|
||||
useMockMediaDevices();
|
||||
stubClient();
|
||||
client = mocked(MatrixClientPeg.safeGet());
|
||||
DMRoomMap.makeShared(client);
|
||||
|
||||
algorithm = new Algorithm();
|
||||
algorithm.start();
|
||||
algorithm.populateTags(
|
||||
{ [DefaultTagID.Untagged]: SortAlgorithm.Alphabetic },
|
||||
{ [DefaultTagID.Untagged]: ListAlgorithm.Natural },
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
algorithm.stop();
|
||||
});
|
||||
|
||||
it("sticks rooms with calls to the top when they're connected", async () => {
|
||||
const room = new Room("!1:example.org", client, "@alice:example.org", {
|
||||
pendingEventOrdering: PendingEventOrdering.Detached,
|
||||
});
|
||||
const roomWithCall = new Room("!2:example.org", client, "@alice:example.org", {
|
||||
pendingEventOrdering: PendingEventOrdering.Detached,
|
||||
});
|
||||
|
||||
client.getRoom.mockImplementation((roomId) => {
|
||||
switch (roomId) {
|
||||
case room.roomId:
|
||||
return room;
|
||||
case roomWithCall.roomId:
|
||||
return roomWithCall;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
});
|
||||
client.getRooms.mockReturnValue([room, roomWithCall]);
|
||||
client.reEmitter.reEmit(room, [RoomStateEvent.Events]);
|
||||
client.reEmitter.reEmit(roomWithCall, [RoomStateEvent.Events]);
|
||||
|
||||
for (const room of client.getRooms()) jest.spyOn(room, "getMyMembership").mockReturnValue(KnownMembership.Join);
|
||||
algorithm.setKnownRooms(client.getRooms());
|
||||
|
||||
setupAsyncStoreWithClient(CallStore.instance, client);
|
||||
setupAsyncStoreWithClient(WidgetMessagingStore.instance, client);
|
||||
|
||||
MockedCall.create(roomWithCall, "1");
|
||||
const call = CallStore.instance.getCall(roomWithCall.roomId);
|
||||
if (call === null) throw new Error("Failed to create call");
|
||||
|
||||
const widget = new Widget(call.widget);
|
||||
WidgetMessagingStore.instance.storeMessaging(widget, roomWithCall.roomId, {
|
||||
stop: () => {},
|
||||
} as unknown as ClientWidgetApi);
|
||||
|
||||
// End of setup
|
||||
|
||||
expect(algorithm.getOrderedRooms()[DefaultTagID.Untagged]).toEqual([room, roomWithCall]);
|
||||
await call.start();
|
||||
expect(algorithm.getOrderedRooms()[DefaultTagID.Untagged]).toEqual([roomWithCall, room]);
|
||||
await call.disconnect();
|
||||
expect(algorithm.getOrderedRooms()[DefaultTagID.Untagged]).toEqual([room, roomWithCall]);
|
||||
});
|
||||
});
|
|
@ -0,0 +1,177 @@
|
|||
/*
|
||||
Copyright 2024 New Vector Ltd.
|
||||
Copyright 2022 The Matrix.org Foundation C.I.C.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { Room, MatrixClient } from "matrix-js-sdk/src/matrix";
|
||||
import { KnownMembership } from "matrix-js-sdk/src/types";
|
||||
|
||||
import { mkMessage, mkRoom, stubClient } from "../../../../test-utils";
|
||||
import { MatrixClientPeg } from "../../../../../src/MatrixClientPeg";
|
||||
import "../../../../../src/stores/room-list/RoomListStore";
|
||||
import { RecentAlgorithm } from "../../../../../src/stores/room-list/algorithms/tag-sorting/RecentAlgorithm";
|
||||
import { makeThreadEvent, mkThread } from "../../../../test-utils/threads";
|
||||
import { DefaultTagID } from "../../../../../src/stores/room-list/models";
|
||||
|
||||
describe("RecentAlgorithm", () => {
|
||||
let algorithm: RecentAlgorithm;
|
||||
let cli: MatrixClient;
|
||||
|
||||
beforeEach(() => {
|
||||
stubClient();
|
||||
cli = MatrixClientPeg.safeGet();
|
||||
algorithm = new RecentAlgorithm();
|
||||
});
|
||||
|
||||
describe("getLastTs", () => {
|
||||
it("returns the last ts", () => {
|
||||
const room = new Room("room123", cli, "@john:matrix.org");
|
||||
|
||||
const event1 = mkMessage({
|
||||
room: room.roomId,
|
||||
msg: "Hello world!",
|
||||
user: "@alice:matrix.org",
|
||||
ts: 5,
|
||||
event: true,
|
||||
});
|
||||
const event2 = mkMessage({
|
||||
room: room.roomId,
|
||||
msg: "Howdy!",
|
||||
user: "@bob:matrix.org",
|
||||
ts: 10,
|
||||
event: true,
|
||||
});
|
||||
|
||||
room.getMyMembership = () => KnownMembership.Join;
|
||||
|
||||
room.addLiveEvents([event1]);
|
||||
expect(algorithm.getLastTs(room, "@jane:matrix.org")).toBe(5);
|
||||
expect(algorithm.getLastTs(room, "@john:matrix.org")).toBe(5);
|
||||
|
||||
room.addLiveEvents([event2]);
|
||||
|
||||
expect(algorithm.getLastTs(room, "@jane:matrix.org")).toBe(10);
|
||||
expect(algorithm.getLastTs(room, "@john:matrix.org")).toBe(10);
|
||||
});
|
||||
|
||||
it("returns a fake ts for rooms without a timeline", () => {
|
||||
const room = mkRoom(cli, "!new:example.org");
|
||||
// @ts-ignore
|
||||
room.timeline = undefined;
|
||||
expect(algorithm.getLastTs(room, "@john:matrix.org")).toBe(Number.MAX_SAFE_INTEGER);
|
||||
});
|
||||
|
||||
it("works when not a member", () => {
|
||||
const room = mkRoom(cli, "!new:example.org");
|
||||
room.getMyMembership.mockReturnValue(KnownMembership.Invite);
|
||||
expect(algorithm.getLastTs(room, "@john:matrix.org")).toBe(Number.MAX_SAFE_INTEGER);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sortRooms", () => {
|
||||
it("orders rooms per last message ts", () => {
|
||||
const room1 = new Room("room1", cli, "@bob:matrix.org");
|
||||
const room2 = new Room("room2", cli, "@bob:matrix.org");
|
||||
|
||||
room1.getMyMembership = () => KnownMembership.Join;
|
||||
room2.getMyMembership = () => KnownMembership.Join;
|
||||
|
||||
const evt = mkMessage({
|
||||
room: room1.roomId,
|
||||
msg: "Hello world!",
|
||||
user: "@alice:matrix.org",
|
||||
ts: 5,
|
||||
event: true,
|
||||
});
|
||||
const evt2 = mkMessage({
|
||||
room: room2.roomId,
|
||||
msg: "Hello world!",
|
||||
user: "@alice:matrix.org",
|
||||
ts: 2,
|
||||
event: true,
|
||||
});
|
||||
|
||||
room1.addLiveEvents([evt]);
|
||||
room2.addLiveEvents([evt2]);
|
||||
|
||||
expect(algorithm.sortRooms([room2, room1], DefaultTagID.Untagged)).toEqual([room1, room2]);
|
||||
});
|
||||
|
||||
it("orders rooms without messages first", () => {
|
||||
const room1 = new Room("room1", cli, "@bob:matrix.org");
|
||||
const room2 = new Room("room2", cli, "@bob:matrix.org");
|
||||
|
||||
room1.getMyMembership = () => KnownMembership.Join;
|
||||
room2.getMyMembership = () => KnownMembership.Join;
|
||||
|
||||
const evt = mkMessage({
|
||||
room: room1.roomId,
|
||||
msg: "Hello world!",
|
||||
user: "@alice:matrix.org",
|
||||
ts: 5,
|
||||
event: true,
|
||||
});
|
||||
|
||||
room1.addLiveEvents([evt]);
|
||||
|
||||
expect(algorithm.sortRooms([room2, room1], DefaultTagID.Untagged)).toEqual([room2, room1]);
|
||||
|
||||
const { events } = mkThread({
|
||||
room: room1,
|
||||
client: cli,
|
||||
authorId: "@bob:matrix.org",
|
||||
participantUserIds: ["@bob:matrix.org"],
|
||||
ts: 12,
|
||||
});
|
||||
|
||||
room1.addLiveEvents(events);
|
||||
});
|
||||
|
||||
it("orders rooms based on thread replies too", () => {
|
||||
const room1 = new Room("room1", cli, "@bob:matrix.org");
|
||||
const room2 = new Room("room2", cli, "@bob:matrix.org");
|
||||
|
||||
room1.getMyMembership = () => KnownMembership.Join;
|
||||
room2.getMyMembership = () => KnownMembership.Join;
|
||||
|
||||
const { rootEvent, events: events1 } = mkThread({
|
||||
room: room1,
|
||||
client: cli,
|
||||
authorId: "@bob:matrix.org",
|
||||
participantUserIds: ["@bob:matrix.org"],
|
||||
ts: 12,
|
||||
length: 5,
|
||||
});
|
||||
room1.addLiveEvents(events1);
|
||||
|
||||
const { events: events2 } = mkThread({
|
||||
room: room2,
|
||||
client: cli,
|
||||
authorId: "@bob:matrix.org",
|
||||
participantUserIds: ["@bob:matrix.org"],
|
||||
ts: 14,
|
||||
length: 10,
|
||||
});
|
||||
room2.addLiveEvents(events2);
|
||||
|
||||
expect(algorithm.sortRooms([room1, room2], DefaultTagID.Untagged)).toEqual([room2, room1]);
|
||||
|
||||
const threadReply = makeThreadEvent({
|
||||
user: "@bob:matrix.org",
|
||||
room: room1.roomId,
|
||||
event: true,
|
||||
msg: `hello world`,
|
||||
rootEventId: rootEvent.getId()!,
|
||||
replyToEventId: rootEvent.getId()!,
|
||||
// replies are 1ms after each other
|
||||
ts: 50,
|
||||
});
|
||||
room1.addLiveEvents([threadReply]);
|
||||
|
||||
expect(algorithm.sortRooms([room1, room2], DefaultTagID.Untagged)).toEqual([room1, room2]);
|
||||
});
|
||||
});
|
||||
});
|
|
@ -0,0 +1,425 @@
|
|||
/*
|
||||
Copyright 2024 New Vector Ltd.
|
||||
Copyright 2023 The Matrix.org Foundation C.I.C.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { ConditionKind, MatrixEvent, PushRuleActionName, Room, RoomEvent } from "matrix-js-sdk/src/matrix";
|
||||
import { logger } from "matrix-js-sdk/src/logger";
|
||||
|
||||
import { RoomNotificationStateStore } from "../../../../../../src/stores/notifications/RoomNotificationStateStore";
|
||||
import { ImportanceAlgorithm } from "../../../../../../src/stores/room-list/algorithms/list-ordering/ImportanceAlgorithm";
|
||||
import { SortAlgorithm } from "../../../../../../src/stores/room-list/algorithms/models";
|
||||
import * as RoomNotifs from "../../../../../../src/RoomNotifs";
|
||||
import { DefaultTagID, RoomUpdateCause } from "../../../../../../src/stores/room-list/models";
|
||||
import { NotificationLevel } from "../../../../../../src/stores/notifications/NotificationLevel";
|
||||
import { AlphabeticAlgorithm } from "../../../../../../src/stores/room-list/algorithms/tag-sorting/AlphabeticAlgorithm";
|
||||
import { getMockClientWithEventEmitter, mockClientMethodsUser } from "../../../../../test-utils";
|
||||
import { RecentAlgorithm } from "../../../../../../src/stores/room-list/algorithms/tag-sorting/RecentAlgorithm";
|
||||
import { DEFAULT_PUSH_RULES, makePushRule } from "../../../../../test-utils/pushRules";
|
||||
|
||||
describe("ImportanceAlgorithm", () => {
|
||||
const userId = "@alice:server.org";
|
||||
const tagId = DefaultTagID.Favourite;
|
||||
|
||||
const makeRoom = (id: string, name: string, order?: number): Room => {
|
||||
const room = new Room(id, client, userId);
|
||||
room.name = name;
|
||||
const tagEvent = new MatrixEvent({
|
||||
type: "m.tag",
|
||||
content: {
|
||||
tags: {
|
||||
[tagId]: {
|
||||
order,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
room.addTags(tagEvent);
|
||||
return room;
|
||||
};
|
||||
|
||||
const client = getMockClientWithEventEmitter({
|
||||
...mockClientMethodsUser(userId),
|
||||
});
|
||||
const roomA = makeRoom("!aaa:server.org", "Alpha", 2);
|
||||
const roomB = makeRoom("!bbb:server.org", "Bravo", 5);
|
||||
const roomC = makeRoom("!ccc:server.org", "Charlie", 1);
|
||||
const roomD = makeRoom("!ddd:server.org", "Delta", 4);
|
||||
const roomE = makeRoom("!eee:server.org", "Echo", 3);
|
||||
const roomX = makeRoom("!xxx:server.org", "Xylophone", 99);
|
||||
|
||||
const muteRoomARule = makePushRule(roomA.roomId, {
|
||||
actions: [PushRuleActionName.DontNotify],
|
||||
conditions: [{ kind: ConditionKind.EventMatch, key: "room_id", pattern: roomA.roomId }],
|
||||
});
|
||||
const muteRoomBRule = makePushRule(roomB.roomId, {
|
||||
actions: [PushRuleActionName.DontNotify],
|
||||
conditions: [{ kind: ConditionKind.EventMatch, key: "room_id", pattern: roomB.roomId }],
|
||||
});
|
||||
client.pushRules = {
|
||||
global: {
|
||||
...DEFAULT_PUSH_RULES.global,
|
||||
override: [...DEFAULT_PUSH_RULES.global.override!, muteRoomARule, muteRoomBRule],
|
||||
},
|
||||
};
|
||||
|
||||
const unreadStates: Record<string, ReturnType<(typeof RoomNotifs)["determineUnreadState"]>> = {
|
||||
red: { symbol: null, count: 1, level: NotificationLevel.Highlight },
|
||||
grey: { symbol: null, count: 1, level: NotificationLevel.Notification },
|
||||
none: { symbol: null, count: 0, level: NotificationLevel.None },
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
jest.spyOn(RoomNotifs, "determineUnreadState").mockReturnValue({
|
||||
symbol: null,
|
||||
count: 0,
|
||||
level: NotificationLevel.None,
|
||||
});
|
||||
});
|
||||
|
||||
const setupAlgorithm = (sortAlgorithm: SortAlgorithm, rooms?: Room[]) => {
|
||||
const algorithm = new ImportanceAlgorithm(tagId, sortAlgorithm);
|
||||
algorithm.setRooms(rooms || [roomA, roomB, roomC]);
|
||||
return algorithm;
|
||||
};
|
||||
|
||||
describe("When sortAlgorithm is manual", () => {
|
||||
const sortAlgorithm = SortAlgorithm.Manual;
|
||||
it("orders rooms by tag order without categorizing", () => {
|
||||
jest.spyOn(RoomNotificationStateStore.instance, "getRoomState");
|
||||
const algorithm = setupAlgorithm(sortAlgorithm);
|
||||
|
||||
// didn't check notif state
|
||||
expect(RoomNotificationStateStore.instance.getRoomState).not.toHaveBeenCalled();
|
||||
// sorted according to room tag order
|
||||
expect(algorithm.orderedRooms).toEqual([roomC, roomA, roomB]);
|
||||
});
|
||||
|
||||
describe("handleRoomUpdate", () => {
|
||||
// XXX: This doesn't work because manual ordered rooms dont get categoryindices
|
||||
// possibly related https://github.com/vector-im/element-web/issues/25099
|
||||
it.skip("removes a room", () => {
|
||||
const algorithm = setupAlgorithm(sortAlgorithm);
|
||||
|
||||
const shouldTriggerUpdate = algorithm.handleRoomUpdate(roomA, RoomUpdateCause.RoomRemoved);
|
||||
|
||||
expect(shouldTriggerUpdate).toBe(true);
|
||||
expect(algorithm.orderedRooms).toEqual([roomC, roomB]);
|
||||
});
|
||||
|
||||
// XXX: This doesn't work because manual ordered rooms dont get categoryindices
|
||||
it.skip("adds a new room", () => {
|
||||
const algorithm = setupAlgorithm(sortAlgorithm);
|
||||
|
||||
const shouldTriggerUpdate = algorithm.handleRoomUpdate(roomD, RoomUpdateCause.NewRoom);
|
||||
|
||||
expect(shouldTriggerUpdate).toBe(true);
|
||||
expect(algorithm.orderedRooms).toEqual([roomC, roomB, roomD, roomE]);
|
||||
});
|
||||
|
||||
it("does nothing and returns false for a timeline update", () => {
|
||||
const algorithm = setupAlgorithm(sortAlgorithm);
|
||||
|
||||
const beforeRooms = algorithm.orderedRooms;
|
||||
const shouldTriggerUpdate = algorithm.handleRoomUpdate(roomA, RoomUpdateCause.Timeline);
|
||||
|
||||
expect(shouldTriggerUpdate).toBe(false);
|
||||
// strict equal
|
||||
expect(algorithm.orderedRooms).toBe(beforeRooms);
|
||||
});
|
||||
|
||||
it("does nothing and returns false for a read receipt update", () => {
|
||||
const algorithm = setupAlgorithm(sortAlgorithm);
|
||||
|
||||
const beforeRooms = algorithm.orderedRooms;
|
||||
const shouldTriggerUpdate = algorithm.handleRoomUpdate(roomA, RoomUpdateCause.ReadReceipt);
|
||||
|
||||
expect(shouldTriggerUpdate).toBe(false);
|
||||
// strict equal
|
||||
expect(algorithm.orderedRooms).toBe(beforeRooms);
|
||||
});
|
||||
|
||||
it("throws for an unhandle update cause", () => {
|
||||
const algorithm = setupAlgorithm(sortAlgorithm);
|
||||
|
||||
expect(() =>
|
||||
algorithm.handleRoomUpdate(roomA, "something unexpected" as unknown as RoomUpdateCause),
|
||||
).toThrow("Unsupported update cause: something unexpected");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("When sortAlgorithm is alphabetical", () => {
|
||||
const sortAlgorithm = SortAlgorithm.Alphabetic;
|
||||
|
||||
beforeEach(async () => {
|
||||
// destroy roomMap so we can start fresh
|
||||
// @ts-ignore private property
|
||||
RoomNotificationStateStore.instance.roomMap = new Map<Room, RoomNotificationState>();
|
||||
|
||||
jest.spyOn(AlphabeticAlgorithm.prototype, "sortRooms").mockClear();
|
||||
jest.spyOn(RoomNotifs, "determineUnreadState")
|
||||
.mockClear()
|
||||
.mockImplementation((room) => {
|
||||
switch (room) {
|
||||
// b and e have red notifs
|
||||
case roomB:
|
||||
case roomE:
|
||||
return unreadStates.red;
|
||||
// c is grey
|
||||
case roomC:
|
||||
return unreadStates.grey;
|
||||
default:
|
||||
return unreadStates.none;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it("orders rooms by alpha when they have the same notif state", () => {
|
||||
jest.spyOn(RoomNotifs, "determineUnreadState").mockReturnValue({
|
||||
symbol: null,
|
||||
count: 0,
|
||||
level: NotificationLevel.None,
|
||||
});
|
||||
const algorithm = setupAlgorithm(sortAlgorithm);
|
||||
|
||||
// sorted according to alpha
|
||||
expect(algorithm.orderedRooms).toEqual([roomA, roomB, roomC]);
|
||||
});
|
||||
|
||||
it("orders rooms by notification state then alpha", () => {
|
||||
const algorithm = setupAlgorithm(sortAlgorithm, [roomC, roomB, roomE, roomD, roomA]);
|
||||
|
||||
expect(algorithm.orderedRooms).toEqual([
|
||||
// alpha within red
|
||||
roomB,
|
||||
roomE,
|
||||
// grey
|
||||
roomC,
|
||||
// alpha within none
|
||||
roomA,
|
||||
roomD,
|
||||
]);
|
||||
});
|
||||
|
||||
describe("handleRoomUpdate", () => {
|
||||
it("removes a room", () => {
|
||||
const algorithm = setupAlgorithm(sortAlgorithm);
|
||||
jest.spyOn(AlphabeticAlgorithm.prototype, "sortRooms").mockClear();
|
||||
|
||||
const shouldTriggerUpdate = algorithm.handleRoomUpdate(roomA, RoomUpdateCause.RoomRemoved);
|
||||
|
||||
expect(shouldTriggerUpdate).toBe(true);
|
||||
expect(algorithm.orderedRooms).toEqual([roomB, roomC]);
|
||||
// no re-sorting on a remove
|
||||
expect(AlphabeticAlgorithm.prototype.sortRooms).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("warns and returns without change when removing a room that is not indexed", () => {
|
||||
jest.spyOn(logger, "warn").mockReturnValue(undefined);
|
||||
const algorithm = setupAlgorithm(sortAlgorithm);
|
||||
|
||||
const shouldTriggerUpdate = algorithm.handleRoomUpdate(roomD, RoomUpdateCause.RoomRemoved);
|
||||
|
||||
expect(shouldTriggerUpdate).toBe(false);
|
||||
expect(logger.warn).toHaveBeenCalledWith(`Tried to remove unknown room from ${tagId}: ${roomD.roomId}`);
|
||||
});
|
||||
|
||||
it("adds a new room", () => {
|
||||
const algorithm = setupAlgorithm(sortAlgorithm);
|
||||
jest.spyOn(AlphabeticAlgorithm.prototype, "sortRooms").mockClear();
|
||||
|
||||
const shouldTriggerUpdate = algorithm.handleRoomUpdate(roomE, RoomUpdateCause.NewRoom);
|
||||
|
||||
expect(shouldTriggerUpdate).toBe(true);
|
||||
// inserted according to notif state
|
||||
expect(algorithm.orderedRooms).toEqual([roomB, roomE, roomC, roomA]);
|
||||
// only sorted within category
|
||||
expect(AlphabeticAlgorithm.prototype.sortRooms).toHaveBeenCalledWith([roomB, roomE], tagId);
|
||||
});
|
||||
|
||||
it("throws for an unhandled update cause", () => {
|
||||
const algorithm = setupAlgorithm(sortAlgorithm);
|
||||
|
||||
expect(() =>
|
||||
algorithm.handleRoomUpdate(roomA, "something unexpected" as unknown as RoomUpdateCause),
|
||||
).toThrow("Unsupported update cause: something unexpected");
|
||||
});
|
||||
|
||||
it("ignores a mute change", () => {
|
||||
// muted rooms are not pushed to the bottom when sort is alpha
|
||||
const algorithm = setupAlgorithm(sortAlgorithm, [roomC, roomB, roomE, roomD, roomA]);
|
||||
jest.spyOn(AlphabeticAlgorithm.prototype, "sortRooms").mockClear();
|
||||
|
||||
const shouldTriggerUpdate = algorithm.handleRoomUpdate(roomE, RoomUpdateCause.PossibleMuteChange);
|
||||
|
||||
expect(shouldTriggerUpdate).toBe(false);
|
||||
// no sorting
|
||||
expect(AlphabeticAlgorithm.prototype.sortRooms).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
describe("time and read receipt updates", () => {
|
||||
it("throws for when a room is not indexed", () => {
|
||||
const algorithm = setupAlgorithm(sortAlgorithm, [roomC, roomB, roomE, roomD, roomA]);
|
||||
|
||||
expect(() => algorithm.handleRoomUpdate(roomX, RoomUpdateCause.Timeline)).toThrow(
|
||||
`Room ${roomX.roomId} has no index in ${tagId}`,
|
||||
);
|
||||
});
|
||||
|
||||
it("re-sorts category when updated room has not changed category", () => {
|
||||
const algorithm = setupAlgorithm(sortAlgorithm, [roomC, roomB, roomE, roomD, roomA]);
|
||||
jest.spyOn(AlphabeticAlgorithm.prototype, "sortRooms").mockClear();
|
||||
|
||||
const shouldTriggerUpdate = algorithm.handleRoomUpdate(roomE, RoomUpdateCause.Timeline);
|
||||
|
||||
expect(shouldTriggerUpdate).toBe(true);
|
||||
expect(algorithm.orderedRooms).toEqual([roomB, roomE, roomC, roomA, roomD]);
|
||||
// only sorted within category
|
||||
expect(AlphabeticAlgorithm.prototype.sortRooms).toHaveBeenCalledTimes(1);
|
||||
expect(AlphabeticAlgorithm.prototype.sortRooms).toHaveBeenCalledWith([roomB, roomE], tagId);
|
||||
});
|
||||
|
||||
it("re-sorts category when updated room has changed category", () => {
|
||||
const algorithm = setupAlgorithm(sortAlgorithm, [roomC, roomB, roomE, roomD, roomA]);
|
||||
jest.spyOn(AlphabeticAlgorithm.prototype, "sortRooms").mockClear();
|
||||
|
||||
// change roomE to unreadState.none
|
||||
jest.spyOn(RoomNotifs, "determineUnreadState").mockImplementation((room) => {
|
||||
switch (room) {
|
||||
// b and e have red notifs
|
||||
case roomB:
|
||||
return unreadStates.red;
|
||||
// c is grey
|
||||
case roomC:
|
||||
return unreadStates.grey;
|
||||
case roomE:
|
||||
default:
|
||||
return unreadStates.none;
|
||||
}
|
||||
});
|
||||
// @ts-ignore don't bother mocking rest of emit properties
|
||||
roomE.emit(RoomEvent.Timeline, new MatrixEvent({ type: "whatever", room_id: roomE.roomId }));
|
||||
|
||||
const shouldTriggerUpdate = algorithm.handleRoomUpdate(roomE, RoomUpdateCause.Timeline);
|
||||
|
||||
expect(shouldTriggerUpdate).toBe(true);
|
||||
expect(algorithm.orderedRooms).toEqual([roomB, roomC, roomA, roomD, roomE]);
|
||||
|
||||
// only sorted within roomE's new category
|
||||
expect(AlphabeticAlgorithm.prototype.sortRooms).toHaveBeenCalledTimes(1);
|
||||
expect(AlphabeticAlgorithm.prototype.sortRooms).toHaveBeenCalledWith([roomA, roomD, roomE], tagId);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("When sortAlgorithm is recent", () => {
|
||||
const sortAlgorithm = SortAlgorithm.Recent;
|
||||
|
||||
// mock recent algorithm sorting
|
||||
const fakeRecentOrder = [roomC, roomB, roomE, roomD, roomA];
|
||||
|
||||
beforeEach(async () => {
|
||||
// destroy roomMap so we can start fresh
|
||||
// @ts-ignore private property
|
||||
RoomNotificationStateStore.instance.roomMap = new Map<Room, RoomNotificationState>();
|
||||
|
||||
jest.spyOn(RecentAlgorithm.prototype, "sortRooms")
|
||||
.mockClear()
|
||||
.mockImplementation((rooms: Room[]) =>
|
||||
fakeRecentOrder.filter((sortedRoom) => rooms.includes(sortedRoom)),
|
||||
);
|
||||
jest.spyOn(RoomNotifs, "determineUnreadState")
|
||||
.mockClear()
|
||||
.mockImplementation((room) => {
|
||||
switch (room) {
|
||||
// b, c and e have red notifs
|
||||
case roomB:
|
||||
case roomE:
|
||||
case roomC:
|
||||
return unreadStates.red;
|
||||
default:
|
||||
return unreadStates.none;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it("orders rooms by recent when they have the same notif state", () => {
|
||||
jest.spyOn(RoomNotifs, "determineUnreadState").mockReturnValue({
|
||||
symbol: null,
|
||||
count: 0,
|
||||
level: NotificationLevel.None,
|
||||
});
|
||||
const algorithm = setupAlgorithm(sortAlgorithm);
|
||||
|
||||
// sorted according to recent
|
||||
expect(algorithm.orderedRooms).toEqual([roomC, roomB, roomA]);
|
||||
});
|
||||
|
||||
it("orders rooms by notification state then recent", () => {
|
||||
const algorithm = setupAlgorithm(sortAlgorithm, [roomC, roomB, roomE, roomD, roomA]);
|
||||
|
||||
expect(algorithm.orderedRooms).toEqual([
|
||||
// recent within red
|
||||
roomC,
|
||||
roomE,
|
||||
// recent within none
|
||||
roomD,
|
||||
// muted
|
||||
roomB,
|
||||
roomA,
|
||||
]);
|
||||
});
|
||||
|
||||
describe("handleRoomUpdate", () => {
|
||||
it("removes a room", () => {
|
||||
const algorithm = setupAlgorithm(sortAlgorithm);
|
||||
jest.spyOn(RecentAlgorithm.prototype, "sortRooms").mockClear();
|
||||
|
||||
const shouldTriggerUpdate = algorithm.handleRoomUpdate(roomA, RoomUpdateCause.RoomRemoved);
|
||||
|
||||
expect(shouldTriggerUpdate).toBe(true);
|
||||
expect(algorithm.orderedRooms).toEqual([roomC, roomB]);
|
||||
// no re-sorting on a remove
|
||||
expect(RecentAlgorithm.prototype.sortRooms).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("warns and returns without change when removing a room that is not indexed", () => {
|
||||
jest.spyOn(logger, "warn").mockReturnValue(undefined);
|
||||
const algorithm = setupAlgorithm(sortAlgorithm);
|
||||
|
||||
const shouldTriggerUpdate = algorithm.handleRoomUpdate(roomD, RoomUpdateCause.RoomRemoved);
|
||||
|
||||
expect(shouldTriggerUpdate).toBe(false);
|
||||
expect(logger.warn).toHaveBeenCalledWith(`Tried to remove unknown room from ${tagId}: ${roomD.roomId}`);
|
||||
});
|
||||
|
||||
it("adds a new room", () => {
|
||||
const algorithm = setupAlgorithm(sortAlgorithm);
|
||||
jest.spyOn(RecentAlgorithm.prototype, "sortRooms").mockClear();
|
||||
|
||||
const shouldTriggerUpdate = algorithm.handleRoomUpdate(roomE, RoomUpdateCause.NewRoom);
|
||||
|
||||
expect(shouldTriggerUpdate).toBe(true);
|
||||
// inserted according to notif state and mute
|
||||
expect(algorithm.orderedRooms).toEqual([roomC, roomE, roomB, roomA]);
|
||||
// only sorted within category
|
||||
expect(RecentAlgorithm.prototype.sortRooms).toHaveBeenCalledWith([roomE, roomC], tagId);
|
||||
});
|
||||
|
||||
it("re-sorts on a mute change", () => {
|
||||
const algorithm = setupAlgorithm(sortAlgorithm, [roomC, roomB, roomE, roomD, roomA]);
|
||||
jest.spyOn(RecentAlgorithm.prototype, "sortRooms").mockClear();
|
||||
|
||||
const shouldTriggerUpdate = algorithm.handleRoomUpdate(roomE, RoomUpdateCause.PossibleMuteChange);
|
||||
|
||||
expect(shouldTriggerUpdate).toBe(true);
|
||||
expect(RecentAlgorithm.prototype.sortRooms).toHaveBeenCalledWith([roomC, roomE], tagId);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
|
@ -0,0 +1,280 @@
|
|||
/*
|
||||
Copyright 2024 New Vector Ltd.
|
||||
Copyright 2023 The Matrix.org Foundation C.I.C.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { ConditionKind, EventType, MatrixEvent, PushRuleActionName, Room, ClientEvent } from "matrix-js-sdk/src/matrix";
|
||||
import { logger } from "matrix-js-sdk/src/logger";
|
||||
|
||||
import { NaturalAlgorithm } from "../../../../../../src/stores/room-list/algorithms/list-ordering/NaturalAlgorithm";
|
||||
import { SortAlgorithm } from "../../../../../../src/stores/room-list/algorithms/models";
|
||||
import { DefaultTagID, RoomUpdateCause } from "../../../../../../src/stores/room-list/models";
|
||||
import { AlphabeticAlgorithm } from "../../../../../../src/stores/room-list/algorithms/tag-sorting/AlphabeticAlgorithm";
|
||||
import { RecentAlgorithm } from "../../../../../../src/stores/room-list/algorithms/tag-sorting/RecentAlgorithm";
|
||||
import { RoomNotificationStateStore } from "../../../../../../src/stores/notifications/RoomNotificationStateStore";
|
||||
import * as RoomNotifs from "../../../../../../src/RoomNotifs";
|
||||
import { getMockClientWithEventEmitter, mockClientMethodsUser } from "../../../../../test-utils";
|
||||
import { DEFAULT_PUSH_RULES, makePushRule } from "../../../../../test-utils/pushRules";
|
||||
import { NotificationLevel } from "../../../../../../src/stores/notifications/NotificationLevel";
|
||||
|
||||
describe("NaturalAlgorithm", () => {
|
||||
const userId = "@alice:server.org";
|
||||
const tagId = DefaultTagID.Favourite;
|
||||
|
||||
const makeRoom = (id: string, name: string): Room => {
|
||||
const room = new Room(id, client, userId);
|
||||
room.name = name;
|
||||
return room;
|
||||
};
|
||||
|
||||
const client = getMockClientWithEventEmitter({
|
||||
...mockClientMethodsUser(userId),
|
||||
});
|
||||
const roomA = makeRoom("!aaa:server.org", "Alpha");
|
||||
const roomB = makeRoom("!bbb:server.org", "Bravo");
|
||||
const roomC = makeRoom("!ccc:server.org", "Charlie");
|
||||
const roomD = makeRoom("!ddd:server.org", "Delta");
|
||||
const roomE = makeRoom("!eee:server.org", "Echo");
|
||||
const roomX = makeRoom("!xxx:server.org", "Xylophone");
|
||||
|
||||
const muteRoomARule = makePushRule(roomA.roomId, {
|
||||
actions: [PushRuleActionName.DontNotify],
|
||||
conditions: [{ kind: ConditionKind.EventMatch, key: "room_id", pattern: roomA.roomId }],
|
||||
});
|
||||
const muteRoomDRule = makePushRule(roomD.roomId, {
|
||||
actions: [PushRuleActionName.DontNotify],
|
||||
conditions: [{ kind: ConditionKind.EventMatch, key: "room_id", pattern: roomD.roomId }],
|
||||
});
|
||||
client.pushRules = {
|
||||
global: {
|
||||
...DEFAULT_PUSH_RULES.global,
|
||||
override: [...DEFAULT_PUSH_RULES.global!.override!, muteRoomARule, muteRoomDRule],
|
||||
},
|
||||
};
|
||||
|
||||
const setupAlgorithm = (sortAlgorithm: SortAlgorithm, rooms?: Room[]) => {
|
||||
const algorithm = new NaturalAlgorithm(tagId, sortAlgorithm);
|
||||
algorithm.setRooms(rooms || [roomA, roomB, roomC]);
|
||||
return algorithm;
|
||||
};
|
||||
|
||||
describe("When sortAlgorithm is alphabetical", () => {
|
||||
const sortAlgorithm = SortAlgorithm.Alphabetic;
|
||||
|
||||
beforeEach(async () => {
|
||||
jest.spyOn(AlphabeticAlgorithm.prototype, "sortRooms").mockClear();
|
||||
});
|
||||
|
||||
it("orders rooms by alpha", () => {
|
||||
const algorithm = setupAlgorithm(sortAlgorithm);
|
||||
|
||||
// sorted according to alpha
|
||||
expect(algorithm.orderedRooms).toEqual([roomA, roomB, roomC]);
|
||||
});
|
||||
|
||||
describe("handleRoomUpdate", () => {
|
||||
it("removes a room", () => {
|
||||
const algorithm = setupAlgorithm(sortAlgorithm);
|
||||
jest.spyOn(AlphabeticAlgorithm.prototype, "sortRooms").mockClear();
|
||||
|
||||
const shouldTriggerUpdate = algorithm.handleRoomUpdate(roomA, RoomUpdateCause.RoomRemoved);
|
||||
|
||||
expect(shouldTriggerUpdate).toBe(true);
|
||||
expect(algorithm.orderedRooms).toEqual([roomB, roomC]);
|
||||
});
|
||||
|
||||
it("warns when removing a room that is not indexed", () => {
|
||||
jest.spyOn(logger, "warn").mockReturnValue(undefined);
|
||||
const algorithm = setupAlgorithm(sortAlgorithm);
|
||||
|
||||
const shouldTriggerUpdate = algorithm.handleRoomUpdate(roomD, RoomUpdateCause.RoomRemoved);
|
||||
|
||||
expect(shouldTriggerUpdate).toBe(false);
|
||||
expect(logger.warn).toHaveBeenCalledWith(`Tried to remove unknown room from ${tagId}: ${roomD.roomId}`);
|
||||
});
|
||||
|
||||
it("adds a new room", () => {
|
||||
const algorithm = setupAlgorithm(sortAlgorithm);
|
||||
jest.spyOn(AlphabeticAlgorithm.prototype, "sortRooms").mockClear();
|
||||
|
||||
const shouldTriggerUpdate = algorithm.handleRoomUpdate(roomE, RoomUpdateCause.NewRoom);
|
||||
|
||||
expect(shouldTriggerUpdate).toBe(true);
|
||||
expect(algorithm.orderedRooms).toEqual([roomA, roomB, roomC, roomE]);
|
||||
// only sorted within category
|
||||
expect(AlphabeticAlgorithm.prototype.sortRooms).toHaveBeenCalledWith(
|
||||
[roomA, roomB, roomC, roomE],
|
||||
tagId,
|
||||
);
|
||||
});
|
||||
|
||||
it("adds a new muted room", () => {
|
||||
const algorithm = setupAlgorithm(sortAlgorithm, [roomA, roomB, roomE]);
|
||||
jest.spyOn(AlphabeticAlgorithm.prototype, "sortRooms").mockClear();
|
||||
|
||||
const shouldTriggerUpdate = algorithm.handleRoomUpdate(roomD, RoomUpdateCause.NewRoom);
|
||||
|
||||
expect(shouldTriggerUpdate).toBe(true);
|
||||
// muted room mixed in main category
|
||||
expect(algorithm.orderedRooms).toEqual([roomA, roomB, roomD, roomE]);
|
||||
// only sorted within category
|
||||
expect(AlphabeticAlgorithm.prototype.sortRooms).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("ignores a mute change update", () => {
|
||||
const algorithm = setupAlgorithm(sortAlgorithm);
|
||||
jest.spyOn(AlphabeticAlgorithm.prototype, "sortRooms").mockClear();
|
||||
|
||||
const shouldTriggerUpdate = algorithm.handleRoomUpdate(roomA, RoomUpdateCause.PossibleMuteChange);
|
||||
|
||||
expect(shouldTriggerUpdate).toBe(false);
|
||||
expect(AlphabeticAlgorithm.prototype.sortRooms).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("throws for an unhandled update cause", () => {
|
||||
const algorithm = setupAlgorithm(sortAlgorithm);
|
||||
|
||||
expect(() =>
|
||||
algorithm.handleRoomUpdate(roomA, "something unexpected" as unknown as RoomUpdateCause),
|
||||
).toThrow("Unsupported update cause: something unexpected");
|
||||
});
|
||||
|
||||
describe("time and read receipt updates", () => {
|
||||
it("handles when a room is not indexed", () => {
|
||||
const algorithm = setupAlgorithm(sortAlgorithm);
|
||||
|
||||
const shouldTriggerUpdate = algorithm.handleRoomUpdate(roomX, RoomUpdateCause.Timeline);
|
||||
|
||||
// for better or worse natural alg sets this to true
|
||||
expect(shouldTriggerUpdate).toBe(true);
|
||||
expect(algorithm.orderedRooms).toEqual([roomA, roomB, roomC]);
|
||||
});
|
||||
|
||||
it("re-sorts rooms when timeline updates", () => {
|
||||
const algorithm = setupAlgorithm(sortAlgorithm);
|
||||
jest.spyOn(AlphabeticAlgorithm.prototype, "sortRooms").mockClear();
|
||||
|
||||
const shouldTriggerUpdate = algorithm.handleRoomUpdate(roomA, RoomUpdateCause.Timeline);
|
||||
|
||||
expect(shouldTriggerUpdate).toBe(true);
|
||||
expect(algorithm.orderedRooms).toEqual([roomA, roomB, roomC]);
|
||||
// only sorted within category
|
||||
expect(AlphabeticAlgorithm.prototype.sortRooms).toHaveBeenCalledTimes(1);
|
||||
expect(AlphabeticAlgorithm.prototype.sortRooms).toHaveBeenCalledWith([roomA, roomB, roomC], tagId);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("When sortAlgorithm is recent", () => {
|
||||
const sortAlgorithm = SortAlgorithm.Recent;
|
||||
|
||||
// mock recent algorithm sorting
|
||||
const fakeRecentOrder = [roomC, roomA, roomB, roomD, roomE];
|
||||
|
||||
beforeEach(async () => {
|
||||
// destroy roomMap so we can start fresh
|
||||
// @ts-ignore private property
|
||||
RoomNotificationStateStore.instance.roomMap = new Map<Room, RoomNotificationState>();
|
||||
|
||||
jest.spyOn(RecentAlgorithm.prototype, "sortRooms")
|
||||
.mockClear()
|
||||
.mockImplementation((rooms: Room[]) =>
|
||||
fakeRecentOrder.filter((sortedRoom) => rooms.includes(sortedRoom)),
|
||||
);
|
||||
|
||||
jest.spyOn(RoomNotifs, "determineUnreadState").mockReturnValue({
|
||||
symbol: null,
|
||||
count: 0,
|
||||
level: NotificationLevel.None,
|
||||
});
|
||||
});
|
||||
|
||||
it("orders rooms by recent with muted rooms to the bottom", () => {
|
||||
const algorithm = setupAlgorithm(sortAlgorithm);
|
||||
|
||||
// sorted according to recent
|
||||
expect(algorithm.orderedRooms).toEqual([roomC, roomB, roomA]);
|
||||
});
|
||||
|
||||
describe("handleRoomUpdate", () => {
|
||||
it("removes a room", () => {
|
||||
const algorithm = setupAlgorithm(sortAlgorithm);
|
||||
jest.spyOn(RecentAlgorithm.prototype, "sortRooms").mockClear();
|
||||
|
||||
const shouldTriggerUpdate = algorithm.handleRoomUpdate(roomA, RoomUpdateCause.RoomRemoved);
|
||||
|
||||
expect(shouldTriggerUpdate).toBe(true);
|
||||
expect(algorithm.orderedRooms).toEqual([roomC, roomB]);
|
||||
// no re-sorting on a remove
|
||||
expect(RecentAlgorithm.prototype.sortRooms).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("warns and returns without change when removing a room that is not indexed", () => {
|
||||
jest.spyOn(logger, "warn").mockReturnValue(undefined);
|
||||
const algorithm = setupAlgorithm(sortAlgorithm);
|
||||
|
||||
const shouldTriggerUpdate = algorithm.handleRoomUpdate(roomD, RoomUpdateCause.RoomRemoved);
|
||||
|
||||
expect(shouldTriggerUpdate).toBe(false);
|
||||
expect(logger.warn).toHaveBeenCalledWith(`Tried to remove unknown room from ${tagId}: ${roomD.roomId}`);
|
||||
});
|
||||
|
||||
it("adds a new room", () => {
|
||||
const algorithm = setupAlgorithm(sortAlgorithm);
|
||||
jest.spyOn(RecentAlgorithm.prototype, "sortRooms").mockClear();
|
||||
|
||||
const shouldTriggerUpdate = algorithm.handleRoomUpdate(roomE, RoomUpdateCause.NewRoom);
|
||||
|
||||
expect(shouldTriggerUpdate).toBe(true);
|
||||
// inserted according to mute then recentness
|
||||
expect(algorithm.orderedRooms).toEqual([roomC, roomB, roomE, roomA]);
|
||||
// only sorted within category, muted roomA is not resorted
|
||||
expect(RecentAlgorithm.prototype.sortRooms).toHaveBeenCalledWith([roomC, roomB, roomE], tagId);
|
||||
});
|
||||
|
||||
it("does not re-sort on possible mute change when room did not change effective mutedness", () => {
|
||||
const algorithm = setupAlgorithm(sortAlgorithm, [roomC, roomB, roomE, roomD, roomA]);
|
||||
jest.spyOn(RecentAlgorithm.prototype, "sortRooms").mockClear();
|
||||
|
||||
const shouldTriggerUpdate = algorithm.handleRoomUpdate(roomE, RoomUpdateCause.PossibleMuteChange);
|
||||
|
||||
expect(shouldTriggerUpdate).toBe(false);
|
||||
expect(RecentAlgorithm.prototype.sortRooms).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("re-sorts on a mute change", () => {
|
||||
const algorithm = setupAlgorithm(sortAlgorithm, [roomC, roomB, roomE, roomD, roomA]);
|
||||
jest.spyOn(RecentAlgorithm.prototype, "sortRooms").mockClear();
|
||||
|
||||
// mute roomE
|
||||
const muteRoomERule = makePushRule(roomE.roomId, {
|
||||
actions: [PushRuleActionName.DontNotify],
|
||||
conditions: [{ kind: ConditionKind.EventMatch, key: "room_id", pattern: roomE.roomId }],
|
||||
});
|
||||
const pushRulesEvent = new MatrixEvent({ type: EventType.PushRules });
|
||||
client.pushRules!.global!.override!.push(muteRoomERule);
|
||||
client.emit(ClientEvent.AccountData, pushRulesEvent);
|
||||
|
||||
const shouldTriggerUpdate = algorithm.handleRoomUpdate(roomE, RoomUpdateCause.PossibleMuteChange);
|
||||
|
||||
expect(shouldTriggerUpdate).toBe(true);
|
||||
expect(algorithm.orderedRooms).toEqual([
|
||||
// unmuted, sorted by recent
|
||||
roomC,
|
||||
roomB,
|
||||
// muted, sorted by recent
|
||||
roomA,
|
||||
roomD,
|
||||
roomE,
|
||||
]);
|
||||
// only sorted muted category
|
||||
expect(RecentAlgorithm.prototype.sortRooms).toHaveBeenCalledTimes(1);
|
||||
expect(RecentAlgorithm.prototype.sortRooms).toHaveBeenCalledWith([roomA, roomD, roomE], tagId);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
|
@ -0,0 +1,198 @@
|
|||
/*
|
||||
Copyright 2024 New Vector Ltd.
|
||||
Copyright 2022 The Matrix.org Foundation C.I.C.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { mocked } from "jest-mock";
|
||||
import { Room } from "matrix-js-sdk/src/matrix";
|
||||
|
||||
import SettingsStore from "../../../../../src/settings/SettingsStore";
|
||||
import { FILTER_CHANGED } from "../../../../../src/stores/room-list/filters/IFilterCondition";
|
||||
import { SpaceFilterCondition } from "../../../../../src/stores/room-list/filters/SpaceFilterCondition";
|
||||
import { MetaSpace, SpaceKey } from "../../../../../src/stores/spaces";
|
||||
import SpaceStore from "../../../../../src/stores/spaces/SpaceStore";
|
||||
|
||||
jest.mock("../../../../../src/settings/SettingsStore");
|
||||
jest.mock("../../../../../src/stores/spaces/SpaceStore", () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
const EventEmitter = require("events");
|
||||
class MockSpaceStore extends EventEmitter {
|
||||
isRoomInSpace = jest.fn();
|
||||
getSpaceFilteredUserIds = jest.fn().mockReturnValue(new Set<string>([]));
|
||||
getSpaceFilteredRoomIds = jest.fn().mockReturnValue(new Set<string>([]));
|
||||
}
|
||||
return { instance: new MockSpaceStore() };
|
||||
});
|
||||
|
||||
const SettingsStoreMock = mocked(SettingsStore);
|
||||
const SpaceStoreInstanceMock = mocked(SpaceStore.instance);
|
||||
|
||||
jest.useFakeTimers();
|
||||
|
||||
describe("SpaceFilterCondition", () => {
|
||||
const space1 = "!space1:server";
|
||||
const space2 = "!space2:server";
|
||||
const room1Id = "!r1:server";
|
||||
const room2Id = "!r2:server";
|
||||
const room3Id = "!r3:server";
|
||||
const user1Id = "@u1:server";
|
||||
const user2Id = "@u2:server";
|
||||
const user3Id = "@u3:server";
|
||||
const makeMockGetValue =
|
||||
(settings: Record<string, any> = {}) =>
|
||||
(settingName: string, space: SpaceKey) =>
|
||||
settings[settingName]?.[space] || false;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.resetAllMocks();
|
||||
SettingsStoreMock.getValue.mockClear().mockImplementation(makeMockGetValue());
|
||||
SpaceStoreInstanceMock.getSpaceFilteredUserIds.mockReturnValue(new Set([]));
|
||||
SpaceStoreInstanceMock.isRoomInSpace.mockReturnValue(true);
|
||||
});
|
||||
|
||||
const initFilter = (space: SpaceKey): SpaceFilterCondition => {
|
||||
const filter = new SpaceFilterCondition();
|
||||
filter.updateSpace(space);
|
||||
jest.runOnlyPendingTimers();
|
||||
return filter;
|
||||
};
|
||||
|
||||
describe("isVisible", () => {
|
||||
const room1 = { roomId: room1Id } as unknown as Room;
|
||||
it("calls isRoomInSpace correctly", () => {
|
||||
const filter = initFilter(space1);
|
||||
|
||||
expect(filter.isVisible(room1)).toEqual(true);
|
||||
expect(SpaceStoreInstanceMock.isRoomInSpace).toHaveBeenCalledWith(space1, room1Id);
|
||||
});
|
||||
});
|
||||
|
||||
describe("onStoreUpdate", () => {
|
||||
it("emits filter changed event when updateSpace is called even without changes", async () => {
|
||||
const filter = new SpaceFilterCondition();
|
||||
const emitSpy = jest.spyOn(filter, "emit");
|
||||
filter.updateSpace(space1);
|
||||
jest.runOnlyPendingTimers();
|
||||
expect(emitSpy).toHaveBeenCalledWith(FILTER_CHANGED);
|
||||
});
|
||||
|
||||
describe("showPeopleInSpace setting", () => {
|
||||
it("emits filter changed event when setting changes", async () => {
|
||||
// init filter with setting true for space1
|
||||
SettingsStoreMock.getValue.mockImplementation(
|
||||
makeMockGetValue({
|
||||
["Spaces.showPeopleInSpace"]: { [space1]: true },
|
||||
}),
|
||||
);
|
||||
const filter = initFilter(space1);
|
||||
const emitSpy = jest.spyOn(filter, "emit");
|
||||
|
||||
SettingsStoreMock.getValue.mockClear().mockImplementation(
|
||||
makeMockGetValue({
|
||||
["Spaces.showPeopleInSpace"]: { [space1]: false },
|
||||
}),
|
||||
);
|
||||
|
||||
SpaceStoreInstanceMock.emit(space1);
|
||||
jest.runOnlyPendingTimers();
|
||||
expect(emitSpy).toHaveBeenCalledWith(FILTER_CHANGED);
|
||||
});
|
||||
|
||||
it("emits filter changed event when setting is false and space changes to a meta space", async () => {
|
||||
// init filter with setting true for space1
|
||||
SettingsStoreMock.getValue.mockImplementation(
|
||||
makeMockGetValue({
|
||||
["Spaces.showPeopleInSpace"]: { [space1]: false },
|
||||
}),
|
||||
);
|
||||
const filter = initFilter(space1);
|
||||
const emitSpy = jest.spyOn(filter, "emit");
|
||||
|
||||
filter.updateSpace(MetaSpace.Home);
|
||||
jest.runOnlyPendingTimers();
|
||||
expect(emitSpy).toHaveBeenCalledWith(FILTER_CHANGED);
|
||||
});
|
||||
});
|
||||
|
||||
it("does not emit filter changed event on store update when nothing changed", async () => {
|
||||
const filter = initFilter(space1);
|
||||
const emitSpy = jest.spyOn(filter, "emit");
|
||||
SpaceStoreInstanceMock.emit(space1);
|
||||
jest.runOnlyPendingTimers();
|
||||
expect(emitSpy).not.toHaveBeenCalledWith(FILTER_CHANGED);
|
||||
});
|
||||
|
||||
it("removes listener when updateSpace is called", async () => {
|
||||
const filter = initFilter(space1);
|
||||
filter.updateSpace(space2);
|
||||
jest.runOnlyPendingTimers();
|
||||
const emitSpy = jest.spyOn(filter, "emit");
|
||||
|
||||
// update mock so filter would emit change if it was listening to space1
|
||||
SpaceStoreInstanceMock.getSpaceFilteredRoomIds.mockReturnValue(new Set([room1Id]));
|
||||
SpaceStoreInstanceMock.emit(space1);
|
||||
jest.runOnlyPendingTimers();
|
||||
// no filter changed event
|
||||
expect(emitSpy).not.toHaveBeenCalledWith(FILTER_CHANGED);
|
||||
});
|
||||
|
||||
it("removes listener when destroy is called", async () => {
|
||||
const filter = initFilter(space1);
|
||||
filter.destroy();
|
||||
jest.runOnlyPendingTimers();
|
||||
const emitSpy = jest.spyOn(filter, "emit");
|
||||
|
||||
// update mock so filter would emit change if it was listening to space1
|
||||
SpaceStoreInstanceMock.getSpaceFilteredRoomIds.mockReturnValue(new Set([room1Id]));
|
||||
SpaceStoreInstanceMock.emit(space1);
|
||||
jest.runOnlyPendingTimers();
|
||||
// no filter changed event
|
||||
expect(emitSpy).not.toHaveBeenCalledWith(FILTER_CHANGED);
|
||||
});
|
||||
|
||||
describe("when directChildRoomIds change", () => {
|
||||
beforeEach(() => {
|
||||
SpaceStoreInstanceMock.getSpaceFilteredRoomIds.mockReturnValue(new Set([room1Id, room2Id]));
|
||||
});
|
||||
const filterChangedCases = [
|
||||
["room added", [room1Id, room2Id, room3Id]],
|
||||
["room removed", [room1Id]],
|
||||
["room swapped", [room1Id, room3Id]], // same number of rooms with changes
|
||||
];
|
||||
|
||||
it.each(filterChangedCases)("%s", (_d, rooms) => {
|
||||
const filter = initFilter(space1);
|
||||
const emitSpy = jest.spyOn(filter, "emit");
|
||||
|
||||
SpaceStoreInstanceMock.getSpaceFilteredRoomIds.mockReturnValue(new Set(rooms));
|
||||
SpaceStoreInstanceMock.emit(space1);
|
||||
jest.runOnlyPendingTimers();
|
||||
expect(emitSpy).toHaveBeenCalledWith(FILTER_CHANGED);
|
||||
});
|
||||
});
|
||||
|
||||
describe("when user ids change", () => {
|
||||
beforeEach(() => {
|
||||
SpaceStoreInstanceMock.getSpaceFilteredUserIds.mockReturnValue(new Set([user1Id, user2Id]));
|
||||
});
|
||||
const filterChangedCases = [
|
||||
["user added", [user1Id, user2Id, user3Id]],
|
||||
["user removed", [user1Id]],
|
||||
["user swapped", [user1Id, user3Id]], // same number of rooms with changes
|
||||
];
|
||||
|
||||
it.each(filterChangedCases)("%s", (_d, rooms) => {
|
||||
const filter = initFilter(space1);
|
||||
const emitSpy = jest.spyOn(filter, "emit");
|
||||
|
||||
SpaceStoreInstanceMock.getSpaceFilteredUserIds.mockReturnValue(new Set(rooms));
|
||||
SpaceStoreInstanceMock.emit(space1);
|
||||
jest.runOnlyPendingTimers();
|
||||
expect(emitSpy).toHaveBeenCalledWith(FILTER_CHANGED);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
|
@ -0,0 +1,117 @@
|
|||
/*
|
||||
Copyright 2024 New Vector Ltd.
|
||||
Copyright 2022 The Matrix.org Foundation C.I.C.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { mocked } from "jest-mock";
|
||||
import { Room, RoomType } from "matrix-js-sdk/src/matrix";
|
||||
|
||||
import { VisibilityProvider } from "../../../../../src/stores/room-list/filters/VisibilityProvider";
|
||||
import LegacyCallHandler from "../../../../../src/LegacyCallHandler";
|
||||
import VoipUserMapper from "../../../../../src/VoipUserMapper";
|
||||
import { LocalRoom, LOCAL_ROOM_ID_PREFIX } from "../../../../../src/models/LocalRoom";
|
||||
import { RoomListCustomisations } from "../../../../../src/customisations/RoomList";
|
||||
import { createTestClient } from "../../../../test-utils";
|
||||
|
||||
jest.mock("../../../../../src/VoipUserMapper", () => ({
|
||||
sharedInstance: jest.fn(),
|
||||
}));
|
||||
|
||||
jest.mock("../../../../../src/LegacyCallHandler", () => ({
|
||||
instance: {
|
||||
getSupportsVirtualRooms: jest.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
jest.mock("../../../../../src/customisations/RoomList", () => ({
|
||||
RoomListCustomisations: {
|
||||
isRoomVisible: jest.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const createRoom = (isSpaceRoom = false): Room => {
|
||||
return {
|
||||
isSpaceRoom: () => isSpaceRoom,
|
||||
getType: () => (isSpaceRoom ? RoomType.Space : undefined),
|
||||
} as unknown as Room;
|
||||
};
|
||||
|
||||
const createLocalRoom = (): LocalRoom => {
|
||||
const room = new LocalRoom(LOCAL_ROOM_ID_PREFIX + "test", createTestClient(), "@test:example.com");
|
||||
room.isSpaceRoom = () => false;
|
||||
return room;
|
||||
};
|
||||
|
||||
describe("VisibilityProvider", () => {
|
||||
let mockVoipUserMapper: VoipUserMapper;
|
||||
|
||||
beforeEach(() => {
|
||||
mockVoipUserMapper = {
|
||||
onNewInvitedRoom: jest.fn(),
|
||||
isVirtualRoom: jest.fn(),
|
||||
} as unknown as VoipUserMapper;
|
||||
mocked(VoipUserMapper.sharedInstance).mockReturnValue(mockVoipUserMapper);
|
||||
});
|
||||
|
||||
describe("instance", () => {
|
||||
it("should return an instance", () => {
|
||||
const visibilityProvider = VisibilityProvider.instance;
|
||||
expect(visibilityProvider).toBeInstanceOf(VisibilityProvider);
|
||||
expect(VisibilityProvider.instance).toBe(visibilityProvider);
|
||||
});
|
||||
});
|
||||
|
||||
describe("onNewInvitedRoom", () => {
|
||||
it("should call onNewInvitedRoom on VoipUserMapper.sharedInstance", async () => {
|
||||
const room = {} as unknown as Room;
|
||||
await VisibilityProvider.instance.onNewInvitedRoom(room);
|
||||
expect(mockVoipUserMapper.onNewInvitedRoom).toHaveBeenCalledWith(room);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isRoomVisible", () => {
|
||||
describe("for a virtual room", () => {
|
||||
beforeEach(() => {
|
||||
mocked(LegacyCallHandler.instance.getSupportsVirtualRooms).mockReturnValue(true);
|
||||
mocked(mockVoipUserMapper.isVirtualRoom).mockReturnValue(true);
|
||||
});
|
||||
|
||||
it("should return return false", () => {
|
||||
const room = createRoom();
|
||||
expect(VisibilityProvider.instance.isRoomVisible(room)).toBe(false);
|
||||
expect(mockVoipUserMapper.isVirtualRoom).toHaveBeenCalledWith(room);
|
||||
});
|
||||
});
|
||||
|
||||
it("should return false without room", () => {
|
||||
expect(VisibilityProvider.instance.isRoomVisible()).toBe(false);
|
||||
});
|
||||
|
||||
it("should return false for a space room", () => {
|
||||
const room = createRoom(true);
|
||||
expect(VisibilityProvider.instance.isRoomVisible(room)).toBe(false);
|
||||
});
|
||||
|
||||
it("should return false for a local room", () => {
|
||||
const room = createLocalRoom();
|
||||
expect(VisibilityProvider.instance.isRoomVisible(room)).toBe(false);
|
||||
});
|
||||
|
||||
it("should return false if visibility customisation returns false", () => {
|
||||
mocked(RoomListCustomisations.isRoomVisible!).mockReturnValue(false);
|
||||
const room = createRoom();
|
||||
expect(VisibilityProvider.instance.isRoomVisible(room)).toBe(false);
|
||||
expect(RoomListCustomisations.isRoomVisible).toHaveBeenCalledWith(room);
|
||||
});
|
||||
|
||||
it("should return true if visibility customisation returns true", () => {
|
||||
mocked(RoomListCustomisations.isRoomVisible!).mockReturnValue(true);
|
||||
const room = createRoom();
|
||||
expect(VisibilityProvider.instance.isRoomVisible(room)).toBe(true);
|
||||
expect(RoomListCustomisations.isRoomVisible).toHaveBeenCalledWith(room);
|
||||
});
|
||||
});
|
||||
});
|
|
@ -0,0 +1,88 @@
|
|||
/*
|
||||
Copyright 2024 New Vector Ltd.
|
||||
Copyright 2022 The Matrix.org Foundation C.I.C.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { RelationType } from "matrix-js-sdk/src/matrix";
|
||||
|
||||
import { MessageEventPreview } from "../../../../../src/stores/room-list/previews/MessageEventPreview";
|
||||
import { mkEvent, stubClient } from "../../../../test-utils";
|
||||
|
||||
describe("MessageEventPreview", () => {
|
||||
const preview = new MessageEventPreview();
|
||||
const userId = "@user:example.com";
|
||||
|
||||
beforeAll(() => {
|
||||
stubClient();
|
||||
});
|
||||
|
||||
describe("getTextFor", () => {
|
||||
it("when called with an event with empty content should return null", () => {
|
||||
const event = mkEvent({
|
||||
event: true,
|
||||
content: {},
|
||||
user: userId,
|
||||
type: "m.room.message",
|
||||
});
|
||||
expect(preview.getTextFor(event)).toBeNull();
|
||||
});
|
||||
|
||||
it("when called with an event with empty body should return null", () => {
|
||||
const event = mkEvent({
|
||||
event: true,
|
||||
content: {
|
||||
body: "",
|
||||
},
|
||||
user: userId,
|
||||
type: "m.room.message",
|
||||
});
|
||||
expect(preview.getTextFor(event)).toBeNull();
|
||||
});
|
||||
|
||||
it("when called with an event with body should return »user: body«", () => {
|
||||
const event = mkEvent({
|
||||
event: true,
|
||||
content: {
|
||||
body: "test body",
|
||||
},
|
||||
user: userId,
|
||||
type: "m.room.message",
|
||||
});
|
||||
expect(preview.getTextFor(event)).toBe(`${userId}: test body`);
|
||||
});
|
||||
|
||||
it("when called for a replaced event with new content should return the new content body", () => {
|
||||
const event = mkEvent({
|
||||
event: true,
|
||||
content: {
|
||||
["m.new_content"]: {
|
||||
body: "test new content body",
|
||||
},
|
||||
["m.relates_to"]: {
|
||||
rel_type: RelationType.Replace,
|
||||
event_id: "$asd123",
|
||||
},
|
||||
},
|
||||
user: userId,
|
||||
type: "m.room.message",
|
||||
});
|
||||
expect(preview.getTextFor(event)).toBe(`${userId}: test new content body`);
|
||||
});
|
||||
|
||||
it("when called with a broadcast chunk event it should return null", () => {
|
||||
const event = mkEvent({
|
||||
event: true,
|
||||
content: {
|
||||
body: "test body",
|
||||
["io.element.voice_broadcast_chunk"]: {},
|
||||
},
|
||||
user: userId,
|
||||
type: "m.room.message",
|
||||
});
|
||||
expect(preview.getTextFor(event)).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
|
@ -0,0 +1,36 @@
|
|||
/*
|
||||
Copyright 2024 New Vector Ltd.
|
||||
Copyright 2021 The Matrix.org Foundation C.I.C.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { MatrixClient } from "matrix-js-sdk/src/matrix";
|
||||
|
||||
import { PollStartEventPreview } from "../../../../../src/stores/room-list/previews/PollStartEventPreview";
|
||||
import { MatrixClientPeg } from "../../../../../src/MatrixClientPeg";
|
||||
import { makePollStartEvent } from "../../../../test-utils";
|
||||
|
||||
jest.spyOn(MatrixClientPeg, "get").mockReturnValue({
|
||||
getUserId: () => "@me:example.com",
|
||||
getSafeUserId: () => "@me:example.com",
|
||||
} as unknown as MatrixClient);
|
||||
jest.spyOn(MatrixClientPeg, "safeGet").mockReturnValue({
|
||||
getUserId: () => "@me:example.com",
|
||||
getSafeUserId: () => "@me:example.com",
|
||||
} as unknown as MatrixClient);
|
||||
|
||||
describe("PollStartEventPreview", () => {
|
||||
it("shows the question for a poll I created", async () => {
|
||||
const pollStartEvent = makePollStartEvent("My Question", "@me:example.com");
|
||||
const preview = new PollStartEventPreview();
|
||||
expect(preview.getTextFor(pollStartEvent)).toBe("My Question");
|
||||
});
|
||||
|
||||
it("shows the sender and question for a poll created by someone else", async () => {
|
||||
const pollStartEvent = makePollStartEvent("Your Question", "@yo:example.com");
|
||||
const preview = new PollStartEventPreview();
|
||||
expect(preview.getTextFor(pollStartEvent)).toBe("@yo:example.com: Your Question");
|
||||
});
|
||||
});
|
|
@ -0,0 +1,131 @@
|
|||
/*
|
||||
Copyright 2024 New Vector Ltd.
|
||||
Copyright 2023 The Matrix.org Foundation C.I.C.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { RelationType, Room, RoomMember } from "matrix-js-sdk/src/matrix";
|
||||
import { mocked } from "jest-mock";
|
||||
|
||||
import { mkEvent, stubClient } from "../../../../test-utils";
|
||||
import { ReactionEventPreview } from "../../../../../src/stores/room-list/previews/ReactionEventPreview";
|
||||
import { MatrixClientPeg } from "../../../../../src/MatrixClientPeg";
|
||||
|
||||
describe("ReactionEventPreview", () => {
|
||||
const preview = new ReactionEventPreview();
|
||||
const userId = "@user:example.com";
|
||||
const roomId = "!room:example.com";
|
||||
|
||||
beforeAll(() => {
|
||||
stubClient();
|
||||
});
|
||||
|
||||
describe("getTextFor", () => {
|
||||
it("should return null for non-relations", () => {
|
||||
const event = mkEvent({
|
||||
event: true,
|
||||
content: {},
|
||||
user: userId,
|
||||
type: "m.room.message",
|
||||
room: roomId,
|
||||
});
|
||||
expect(preview.getTextFor(event)).toBeNull();
|
||||
});
|
||||
|
||||
it("should return null for non-reactions", () => {
|
||||
const event = mkEvent({
|
||||
event: true,
|
||||
content: {
|
||||
"body": "",
|
||||
"m.relates_to": {
|
||||
rel_type: RelationType.Thread,
|
||||
event_id: "$foo:bar",
|
||||
},
|
||||
},
|
||||
user: userId,
|
||||
type: "m.room.message",
|
||||
room: roomId,
|
||||
});
|
||||
expect(preview.getTextFor(event)).toBeNull();
|
||||
});
|
||||
|
||||
it("should use 'You' for your own reactions", () => {
|
||||
const cli = MatrixClientPeg.safeGet();
|
||||
const room = new Room(roomId, cli, userId);
|
||||
mocked(cli.getRoom).mockReturnValue(room);
|
||||
|
||||
const message = mkEvent({
|
||||
event: true,
|
||||
content: {
|
||||
"body": "duck duck goose",
|
||||
"m.relates_to": {
|
||||
rel_type: RelationType.Thread,
|
||||
event_id: "$foo:bar",
|
||||
},
|
||||
},
|
||||
user: userId,
|
||||
type: "m.room.message",
|
||||
room: roomId,
|
||||
});
|
||||
|
||||
room.getUnfilteredTimelineSet().addLiveEvent(message, {});
|
||||
|
||||
const event = mkEvent({
|
||||
event: true,
|
||||
content: {
|
||||
"m.relates_to": {
|
||||
rel_type: RelationType.Annotation,
|
||||
key: "🪿",
|
||||
event_id: message.getId(),
|
||||
},
|
||||
},
|
||||
user: cli.getSafeUserId(),
|
||||
type: "m.reaction",
|
||||
room: roomId,
|
||||
});
|
||||
expect(preview.getTextFor(event)).toMatchInlineSnapshot(`"You reacted 🪿 to duck duck goose"`);
|
||||
});
|
||||
|
||||
it("should use display name for your others' reactions", () => {
|
||||
const cli = MatrixClientPeg.safeGet();
|
||||
const room = new Room(roomId, cli, userId);
|
||||
mocked(cli.getRoom).mockReturnValue(room);
|
||||
|
||||
const message = mkEvent({
|
||||
event: true,
|
||||
content: {
|
||||
"body": "duck duck goose",
|
||||
"m.relates_to": {
|
||||
rel_type: RelationType.Thread,
|
||||
event_id: "$foo:bar",
|
||||
},
|
||||
},
|
||||
user: userId,
|
||||
type: "m.room.message",
|
||||
room: roomId,
|
||||
});
|
||||
|
||||
room.getUnfilteredTimelineSet().addLiveEvent(message, {});
|
||||
|
||||
const event = mkEvent({
|
||||
event: true,
|
||||
content: {
|
||||
"m.relates_to": {
|
||||
rel_type: RelationType.Annotation,
|
||||
key: "🪿",
|
||||
event_id: message.getId(),
|
||||
},
|
||||
},
|
||||
user: userId,
|
||||
type: "m.reaction",
|
||||
room: roomId,
|
||||
});
|
||||
event.sender = new RoomMember(roomId, userId);
|
||||
event.sender.name = "Bob";
|
||||
|
||||
expect(preview.getTextFor(event)).toMatchInlineSnapshot(`"Bob reacted 🪿 to duck duck goose"`);
|
||||
});
|
||||
});
|
||||
});
|
|
@ -0,0 +1,54 @@
|
|||
/*
|
||||
Copyright 2024 New Vector Ltd.
|
||||
Copyright 2022 The Matrix.org Foundation C.I.C.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { Room } from "matrix-js-sdk/src/matrix";
|
||||
|
||||
import { VoiceBroadcastPreview } from "../../../../../src/stores/room-list/previews/VoiceBroadcastPreview";
|
||||
import { VoiceBroadcastInfoState } from "../../../../../src/voice-broadcast";
|
||||
import { mkEvent, stubClient } from "../../../../test-utils";
|
||||
import { mkVoiceBroadcastInfoStateEvent } from "../../../voice-broadcast/utils/test-utils";
|
||||
|
||||
describe("VoiceBroadcastPreview.getTextFor", () => {
|
||||
const roomId = "!room:example.com";
|
||||
const userId = "@user:example.com";
|
||||
const deviceId = "d42";
|
||||
let preview: VoiceBroadcastPreview;
|
||||
|
||||
beforeAll(() => {
|
||||
preview = new VoiceBroadcastPreview();
|
||||
});
|
||||
|
||||
it("when passing an event with empty content, it should return null", () => {
|
||||
const event = mkEvent({
|
||||
event: true,
|
||||
content: {},
|
||||
user: userId,
|
||||
type: "m.room.message",
|
||||
});
|
||||
expect(preview.getTextFor(event)).toBeNull();
|
||||
});
|
||||
|
||||
it("when passing a broadcast started event, it should return null", () => {
|
||||
const event = mkVoiceBroadcastInfoStateEvent(roomId, VoiceBroadcastInfoState.Started, userId, deviceId);
|
||||
expect(preview.getTextFor(event)).toBeNull();
|
||||
});
|
||||
|
||||
it("when passing a broadcast stopped event, it should return the expected text", () => {
|
||||
const event = mkVoiceBroadcastInfoStateEvent(roomId, VoiceBroadcastInfoState.Stopped, userId, deviceId);
|
||||
expect(preview.getTextFor(event)).toBe("@user:example.com ended a voice broadcast");
|
||||
});
|
||||
|
||||
it("when passing a redacted broadcast stopped event, it should return null", () => {
|
||||
const event = mkVoiceBroadcastInfoStateEvent(roomId, VoiceBroadcastInfoState.Stopped, userId, deviceId);
|
||||
event.makeRedacted(
|
||||
mkEvent({ event: true, content: {}, user: userId, type: "m.room.redaction" }),
|
||||
new Room(roomId, stubClient(), userId),
|
||||
);
|
||||
expect(preview.getTextFor(event)).toBeNull();
|
||||
});
|
||||
});
|
88
test/unit-tests/stores/room-list/utils/roomMute-test.ts
Normal file
88
test/unit-tests/stores/room-list/utils/roomMute-test.ts
Normal file
|
@ -0,0 +1,88 @@
|
|||
/*
|
||||
Copyright 2024 New Vector Ltd.
|
||||
Copyright 2023 The Matrix.org Foundation C.I.C.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { ConditionKind, EventType, IPushRule, MatrixEvent, PushRuleActionName } from "matrix-js-sdk/src/matrix";
|
||||
|
||||
import { getChangedOverrideRoomMutePushRules } from "../../../../../src/stores/room-list/utils/roomMute";
|
||||
import { DEFAULT_PUSH_RULES, getDefaultRuleWithKind, makePushRule } from "../../../../test-utils/pushRules";
|
||||
|
||||
describe("getChangedOverrideRoomMutePushRules()", () => {
|
||||
const makePushRulesEvent = (overrideRules: IPushRule[] = []): MatrixEvent => {
|
||||
return new MatrixEvent({
|
||||
type: EventType.PushRules,
|
||||
content: {
|
||||
global: {
|
||||
...DEFAULT_PUSH_RULES.global,
|
||||
override: overrideRules,
|
||||
},
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
it("returns undefined when dispatched action is not accountData", () => {
|
||||
const action = { action: "MatrixActions.Event.decrypted", event: new MatrixEvent({}) };
|
||||
expect(getChangedOverrideRoomMutePushRules(action)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("returns undefined when dispatched action is not pushrules", () => {
|
||||
const action = { action: "MatrixActions.accountData", event: new MatrixEvent({ type: "not-push-rules" }) };
|
||||
expect(getChangedOverrideRoomMutePushRules(action)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("returns undefined when actions event is falsy", () => {
|
||||
const action = { action: "MatrixActions.accountData" };
|
||||
expect(getChangedOverrideRoomMutePushRules(action)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("returns undefined when actions previousEvent is falsy", () => {
|
||||
const pushRulesEvent = makePushRulesEvent();
|
||||
const action = { action: "MatrixActions.accountData", event: pushRulesEvent };
|
||||
expect(getChangedOverrideRoomMutePushRules(action)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("filters out non-room specific rules", () => {
|
||||
// an override rule that exists in default rules
|
||||
const { rule } = getDefaultRuleWithKind(".m.rule.contains_display_name");
|
||||
const updatedRule = {
|
||||
...rule,
|
||||
actions: [PushRuleActionName.DontNotify],
|
||||
enabled: false,
|
||||
};
|
||||
const previousEvent = makePushRulesEvent([rule]);
|
||||
const pushRulesEvent = makePushRulesEvent([updatedRule]);
|
||||
const action = { action: "MatrixActions.accountData", event: pushRulesEvent, previousEvent: previousEvent };
|
||||
// contains_display_name changed, but is not room-specific
|
||||
expect(getChangedOverrideRoomMutePushRules(action)).toEqual([]);
|
||||
});
|
||||
|
||||
it("returns ruleIds for added room rules", () => {
|
||||
const roomId1 = "!room1:server.org";
|
||||
const rule = makePushRule(roomId1, {
|
||||
actions: [PushRuleActionName.DontNotify],
|
||||
conditions: [{ kind: ConditionKind.EventMatch, key: "room_id", pattern: roomId1 }],
|
||||
});
|
||||
const previousEvent = makePushRulesEvent();
|
||||
const pushRulesEvent = makePushRulesEvent([rule]);
|
||||
const action = { action: "MatrixActions.accountData", event: pushRulesEvent, previousEvent: previousEvent };
|
||||
// contains_display_name changed, but is not room-specific
|
||||
expect(getChangedOverrideRoomMutePushRules(action)).toEqual([rule.rule_id]);
|
||||
});
|
||||
|
||||
it("returns ruleIds for removed room rules", () => {
|
||||
const roomId1 = "!room1:server.org";
|
||||
const rule = makePushRule(roomId1, {
|
||||
actions: [PushRuleActionName.DontNotify],
|
||||
conditions: [{ kind: ConditionKind.EventMatch, key: "room_id", pattern: roomId1 }],
|
||||
});
|
||||
const previousEvent = makePushRulesEvent([rule]);
|
||||
const pushRulesEvent = makePushRulesEvent();
|
||||
const action = { action: "MatrixActions.accountData", event: pushRulesEvent, previousEvent: previousEvent };
|
||||
// contains_display_name changed, but is not room-specific
|
||||
expect(getChangedOverrideRoomMutePushRules(action)).toEqual([rule.rule_id]);
|
||||
});
|
||||
});
|
281
test/unit-tests/stores/widgets/StopGapWidget-test.ts
Normal file
281
test/unit-tests/stores/widgets/StopGapWidget-test.ts
Normal file
|
@ -0,0 +1,281 @@
|
|||
/*
|
||||
Copyright 2024 New Vector Ltd.
|
||||
Copyright 2022 The Matrix.org Foundation C.I.C
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { mocked, MockedObject } from "jest-mock";
|
||||
import { last } from "lodash";
|
||||
import { MatrixEvent, MatrixClient, ClientEvent, EventTimeline } from "matrix-js-sdk/src/matrix";
|
||||
import { ClientWidgetApi, WidgetApiFromWidgetAction } from "matrix-widget-api";
|
||||
import { waitFor } from "jest-matrix-react";
|
||||
|
||||
import { stubClient, mkRoom, mkEvent } from "../../../test-utils";
|
||||
import { MatrixClientPeg } from "../../../../src/MatrixClientPeg";
|
||||
import { StopGapWidget } from "../../../../src/stores/widgets/StopGapWidget";
|
||||
import { ElementWidgetActions } from "../../../../src/stores/widgets/ElementWidgetActions";
|
||||
import { VoiceBroadcastInfoEventType, VoiceBroadcastRecording } from "../../../../src/voice-broadcast";
|
||||
import { SdkContextClass } from "../../../../src/contexts/SDKContext";
|
||||
import ActiveWidgetStore from "../../../../src/stores/ActiveWidgetStore";
|
||||
import SettingsStore from "../../../../src/settings/SettingsStore";
|
||||
|
||||
jest.mock("matrix-widget-api/lib/ClientWidgetApi");
|
||||
|
||||
describe("StopGapWidget", () => {
|
||||
let client: MockedObject<MatrixClient>;
|
||||
let widget: StopGapWidget;
|
||||
let messaging: MockedObject<ClientWidgetApi>;
|
||||
|
||||
beforeEach(() => {
|
||||
stubClient();
|
||||
client = mocked(MatrixClientPeg.safeGet());
|
||||
|
||||
widget = new StopGapWidget({
|
||||
app: {
|
||||
id: "test",
|
||||
creatorUserId: "@alice:example.org",
|
||||
type: "example",
|
||||
url: "https://example.org?user-id=$matrix_user_id&device-id=$org.matrix.msc3819.matrix_device_id&base-url=$org.matrix.msc4039.matrix_base_url&theme=$org.matrix.msc2873.client_theme",
|
||||
roomId: "!1:example.org",
|
||||
},
|
||||
room: mkRoom(client, "!1:example.org"),
|
||||
userId: "@alice:example.org",
|
||||
creatorUserId: "@alice:example.org",
|
||||
waitForIframeLoad: true,
|
||||
userWidget: false,
|
||||
});
|
||||
// Start messaging without an iframe, since ClientWidgetApi is mocked
|
||||
widget.startMessaging(null as unknown as HTMLIFrameElement);
|
||||
messaging = mocked(last(mocked(ClientWidgetApi).mock.instances)!);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
widget.stopMessaging();
|
||||
});
|
||||
|
||||
it("should replace parameters in widget url template", () => {
|
||||
const originGetValue = SettingsStore.getValue;
|
||||
const spy = jest.spyOn(SettingsStore, "getValue").mockImplementation((setting) => {
|
||||
if (setting === "theme") return "my-theme-for-testing";
|
||||
return originGetValue(setting);
|
||||
});
|
||||
expect(widget.embedUrl).toBe(
|
||||
"https://example.org/?user-id=%40userId%3Amatrix.org&device-id=ABCDEFGHI&base-url=https%3A%2F%2Fmatrix-client.matrix.org&theme=my-theme-for-testing&widgetId=test&parentUrl=http%3A%2F%2Flocalhost%2F",
|
||||
);
|
||||
spy.mockClear();
|
||||
});
|
||||
|
||||
it("feeds incoming to-device messages to the widget", async () => {
|
||||
const event = mkEvent({
|
||||
event: true,
|
||||
type: "org.example.foo",
|
||||
user: "@alice:example.org",
|
||||
content: { hello: "world" },
|
||||
});
|
||||
|
||||
client.emit(ClientEvent.ToDeviceEvent, event);
|
||||
await Promise.resolve(); // flush promises
|
||||
expect(messaging.feedToDevice).toHaveBeenCalledWith(event.getEffectiveEvent(), false);
|
||||
});
|
||||
|
||||
describe("feed event", () => {
|
||||
let event1: MatrixEvent;
|
||||
let event2: MatrixEvent;
|
||||
|
||||
beforeEach(() => {
|
||||
event1 = mkEvent({
|
||||
event: true,
|
||||
id: "$event-id1",
|
||||
type: "org.example.foo",
|
||||
user: "@alice:example.org",
|
||||
content: { hello: "world" },
|
||||
room: "!1:example.org",
|
||||
});
|
||||
|
||||
event2 = mkEvent({
|
||||
event: true,
|
||||
id: "$event-id2",
|
||||
type: "org.example.foo",
|
||||
user: "@alice:example.org",
|
||||
content: { hello: "world" },
|
||||
room: "!1:example.org",
|
||||
});
|
||||
|
||||
const room = mkRoom(client, "!1:example.org");
|
||||
client.getRoom.mockImplementation((roomId) => (roomId === "!1:example.org" ? room : null));
|
||||
room.getLiveTimeline.mockReturnValue({
|
||||
getEvents: (): MatrixEvent[] => [event1, event2],
|
||||
} as unknown as EventTimeline);
|
||||
|
||||
messaging.feedEvent.mockResolvedValue();
|
||||
});
|
||||
|
||||
it("feeds incoming event to the widget", async () => {
|
||||
client.emit(ClientEvent.Event, event1);
|
||||
expect(messaging.feedEvent).toHaveBeenCalledWith(event1.getEffectiveEvent(), "!1:example.org");
|
||||
|
||||
client.emit(ClientEvent.Event, event2);
|
||||
expect(messaging.feedEvent).toHaveBeenCalledTimes(2);
|
||||
expect(messaging.feedEvent).toHaveBeenLastCalledWith(event2.getEffectiveEvent(), "!1:example.org");
|
||||
});
|
||||
|
||||
it("should not feed incoming event to the widget if seen already", async () => {
|
||||
client.emit(ClientEvent.Event, event1);
|
||||
expect(messaging.feedEvent).toHaveBeenCalledWith(event1.getEffectiveEvent(), "!1:example.org");
|
||||
|
||||
client.emit(ClientEvent.Event, event2);
|
||||
expect(messaging.feedEvent).toHaveBeenCalledTimes(2);
|
||||
expect(messaging.feedEvent).toHaveBeenLastCalledWith(event2.getEffectiveEvent(), "!1:example.org");
|
||||
|
||||
client.emit(ClientEvent.Event, event1);
|
||||
expect(messaging.feedEvent).toHaveBeenCalledTimes(2);
|
||||
expect(messaging.feedEvent).toHaveBeenLastCalledWith(event2.getEffectiveEvent(), "!1:example.org");
|
||||
});
|
||||
|
||||
it("should not feed incoming event if not in timeline", () => {
|
||||
const event = mkEvent({
|
||||
event: true,
|
||||
id: "$event-id",
|
||||
type: "org.example.foo",
|
||||
user: "@alice:example.org",
|
||||
content: {
|
||||
hello: "world",
|
||||
},
|
||||
room: "!1:example.org",
|
||||
});
|
||||
|
||||
client.emit(ClientEvent.Event, event);
|
||||
expect(messaging.feedEvent).toHaveBeenCalledWith(event.getEffectiveEvent(), "!1:example.org");
|
||||
});
|
||||
|
||||
it("feeds incoming event that is not in timeline but relates to unknown parent to the widget", async () => {
|
||||
const event = mkEvent({
|
||||
event: true,
|
||||
id: "$event-idRelation",
|
||||
type: "org.example.foo",
|
||||
user: "@alice:example.org",
|
||||
content: {
|
||||
"hello": "world",
|
||||
"m.relates_to": {
|
||||
event_id: "$unknown-parent",
|
||||
rel_type: "m.reference",
|
||||
},
|
||||
},
|
||||
room: "!1:example.org",
|
||||
});
|
||||
|
||||
client.emit(ClientEvent.Event, event1);
|
||||
expect(messaging.feedEvent).toHaveBeenCalledWith(event1.getEffectiveEvent(), "!1:example.org");
|
||||
|
||||
client.emit(ClientEvent.Event, event);
|
||||
expect(messaging.feedEvent).toHaveBeenCalledTimes(2);
|
||||
expect(messaging.feedEvent).toHaveBeenLastCalledWith(event.getEffectiveEvent(), "!1:example.org");
|
||||
|
||||
client.emit(ClientEvent.Event, event1);
|
||||
expect(messaging.feedEvent).toHaveBeenCalledTimes(2);
|
||||
expect(messaging.feedEvent).toHaveBeenLastCalledWith(event.getEffectiveEvent(), "!1:example.org");
|
||||
});
|
||||
});
|
||||
|
||||
describe("when there is a voice broadcast recording", () => {
|
||||
let voiceBroadcastInfoEvent: MatrixEvent;
|
||||
let voiceBroadcastRecording: VoiceBroadcastRecording;
|
||||
|
||||
beforeEach(() => {
|
||||
voiceBroadcastInfoEvent = mkEvent({
|
||||
event: true,
|
||||
room: client.getRoom("x")?.roomId,
|
||||
user: client.getUserId()!,
|
||||
type: VoiceBroadcastInfoEventType,
|
||||
content: {},
|
||||
});
|
||||
voiceBroadcastRecording = new VoiceBroadcastRecording(voiceBroadcastInfoEvent, client);
|
||||
jest.spyOn(voiceBroadcastRecording, "pause");
|
||||
jest.spyOn(SdkContextClass.instance.voiceBroadcastRecordingsStore, "getCurrent").mockReturnValue(
|
||||
voiceBroadcastRecording,
|
||||
);
|
||||
});
|
||||
|
||||
describe(`and receiving a action:${ElementWidgetActions.JoinCall} message`, () => {
|
||||
beforeEach(async () => {
|
||||
messaging.on.mock.calls.find(([event, listener]) => {
|
||||
if (event === `action:${ElementWidgetActions.JoinCall}`) {
|
||||
listener();
|
||||
return true;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it("should pause the current voice broadcast recording", () => {
|
||||
expect(voiceBroadcastRecording.pause).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
describe("StopGapWidget with stickyPromise", () => {
|
||||
let client: MockedObject<MatrixClient>;
|
||||
let widget: StopGapWidget;
|
||||
let messaging: MockedObject<ClientWidgetApi>;
|
||||
|
||||
beforeEach(() => {
|
||||
stubClient();
|
||||
client = mocked(MatrixClientPeg.safeGet());
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
widget.stopMessaging();
|
||||
});
|
||||
it("should wait for the sticky promise to resolve before starting messaging", async () => {
|
||||
jest.useFakeTimers();
|
||||
const getStickyPromise = async () => {
|
||||
return new Promise<void>((resolve) => {
|
||||
setTimeout(() => {
|
||||
resolve();
|
||||
}, 1000);
|
||||
});
|
||||
};
|
||||
widget = new StopGapWidget({
|
||||
app: {
|
||||
id: "test",
|
||||
creatorUserId: "@alice:example.org",
|
||||
type: "example",
|
||||
url: "https://example.org?user-id=$matrix_user_id&device-id=$org.matrix.msc3819.matrix_device_id&base-url=$org.matrix.msc4039.matrix_base_url",
|
||||
roomId: "!1:example.org",
|
||||
},
|
||||
room: mkRoom(client, "!1:example.org"),
|
||||
userId: "@alice:example.org",
|
||||
creatorUserId: "@alice:example.org",
|
||||
waitForIframeLoad: true,
|
||||
userWidget: false,
|
||||
stickyPromise: getStickyPromise,
|
||||
});
|
||||
|
||||
const setPersistenceSpy = jest.spyOn(ActiveWidgetStore.instance, "setWidgetPersistence");
|
||||
|
||||
// Start messaging without an iframe, since ClientWidgetApi is mocked
|
||||
widget.startMessaging(null as unknown as HTMLIFrameElement);
|
||||
const emitSticky = async () => {
|
||||
messaging = mocked(last(mocked(ClientWidgetApi).mock.instances)!);
|
||||
messaging?.hasCapability.mockReturnValue(true);
|
||||
// messaging.transport.reply will be called but transport is undefined in this test environment
|
||||
// This just makes sure the call doesn't throw
|
||||
Object.defineProperty(messaging, "transport", { value: { reply: () => {} } });
|
||||
messaging.on.mock.calls.find(([event, listener]) => {
|
||||
if (event === `action:${WidgetApiFromWidgetAction.UpdateAlwaysOnScreen}`) {
|
||||
listener({ preventDefault: () => {}, detail: { data: { value: true } } });
|
||||
return true;
|
||||
}
|
||||
});
|
||||
};
|
||||
await emitSticky();
|
||||
expect(setPersistenceSpy).not.toHaveBeenCalled();
|
||||
// Advance the fake timer so that the sticky promise resolves
|
||||
jest.runAllTimers();
|
||||
// Use a real timer and wait for the next tick so the sticky promise can resolve
|
||||
jest.useRealTimers();
|
||||
|
||||
waitFor(() => expect(setPersistenceSpy).toHaveBeenCalled(), { interval: 5 });
|
||||
});
|
||||
});
|
644
test/unit-tests/stores/widgets/StopGapWidgetDriver-test.ts
Normal file
644
test/unit-tests/stores/widgets/StopGapWidgetDriver-test.ts
Normal file
|
@ -0,0 +1,644 @@
|
|||
/*
|
||||
Copyright 2024 New Vector Ltd.
|
||||
Copyright 2022 The Matrix.org Foundation C.I.C.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { mocked, MockedObject } from "jest-mock";
|
||||
import fetchMockJest from "fetch-mock-jest";
|
||||
import {
|
||||
MatrixClient,
|
||||
ClientEvent,
|
||||
ITurnServer as IClientTurnServer,
|
||||
Direction,
|
||||
EventType,
|
||||
MatrixEvent,
|
||||
MsgType,
|
||||
RelationType,
|
||||
} from "matrix-js-sdk/src/matrix";
|
||||
import { DeviceInfo } from "matrix-js-sdk/src/crypto/deviceinfo";
|
||||
import {
|
||||
Widget,
|
||||
MatrixWidgetType,
|
||||
WidgetKind,
|
||||
WidgetDriver,
|
||||
ITurnServer,
|
||||
SimpleObservable,
|
||||
OpenIDRequestState,
|
||||
IOpenIDUpdate,
|
||||
UpdateDelayedEventAction,
|
||||
} from "matrix-widget-api";
|
||||
import {
|
||||
ApprovalOpts,
|
||||
CapabilitiesOpts,
|
||||
WidgetLifecycle,
|
||||
} from "@matrix-org/react-sdk-module-api/lib/lifecycles/WidgetLifecycle";
|
||||
|
||||
import { SdkContextClass } from "../../../../src/contexts/SDKContext";
|
||||
import { MatrixClientPeg } from "../../../../src/MatrixClientPeg";
|
||||
import { StopGapWidgetDriver } from "../../../../src/stores/widgets/StopGapWidgetDriver";
|
||||
import { stubClient } from "../../../test-utils";
|
||||
import { ModuleRunner } from "../../../../src/modules/ModuleRunner";
|
||||
import dis from "../../../../src/dispatcher/dispatcher";
|
||||
import Modal from "../../../../src/Modal";
|
||||
import SettingsStore from "../../../../src/settings/SettingsStore";
|
||||
|
||||
describe("StopGapWidgetDriver", () => {
|
||||
let client: MockedObject<MatrixClient>;
|
||||
|
||||
const mkDefaultDriver = (): WidgetDriver =>
|
||||
new StopGapWidgetDriver(
|
||||
[],
|
||||
new Widget({
|
||||
id: "test",
|
||||
creatorUserId: "@alice:example.org",
|
||||
type: "example",
|
||||
url: "https://example.org",
|
||||
}),
|
||||
WidgetKind.Room,
|
||||
false,
|
||||
"!1:example.org",
|
||||
);
|
||||
|
||||
jest.spyOn(Modal, "createDialog").mockImplementation(() => {
|
||||
throw new Error("Should not have to create a dialog");
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
stubClient();
|
||||
client = mocked(MatrixClientPeg.safeGet());
|
||||
client.getUserId.mockReturnValue("@alice:example.org");
|
||||
client.getSafeUserId.mockReturnValue("@alice:example.org");
|
||||
});
|
||||
|
||||
it("auto-approves capabilities of virtual Element Call widgets", async () => {
|
||||
const driver = new StopGapWidgetDriver(
|
||||
[],
|
||||
new Widget({
|
||||
id: "group_call",
|
||||
creatorUserId: "@alice:example.org",
|
||||
type: MatrixWidgetType.Custom,
|
||||
url: "https://call.element.io",
|
||||
}),
|
||||
WidgetKind.Room,
|
||||
true,
|
||||
"!1:example.org",
|
||||
);
|
||||
|
||||
// These are intentionally raw identifiers rather than constants, so it's obvious what's being requested
|
||||
const requestedCapabilities = new Set([
|
||||
"m.always_on_screen",
|
||||
"town.robin.msc3846.turn_servers",
|
||||
"org.matrix.msc2762.timeline:!1:example.org",
|
||||
"org.matrix.msc2762.send.event:org.matrix.rageshake_request",
|
||||
"org.matrix.msc2762.receive.event:org.matrix.rageshake_request",
|
||||
"org.matrix.msc2762.send.event:m.reaction",
|
||||
"org.matrix.msc2762.receive.event:m.reaction",
|
||||
"org.matrix.msc2762.send.event:m.room.redaction",
|
||||
"org.matrix.msc2762.receive.event:m.room.redaction",
|
||||
"org.matrix.msc2762.receive.state_event:m.room.create",
|
||||
"org.matrix.msc2762.receive.state_event:m.room.member",
|
||||
"org.matrix.msc2762.receive.state_event:org.matrix.msc3401.call",
|
||||
"org.matrix.msc2762.send.state_event:org.matrix.msc3401.call.member#@alice:example.org",
|
||||
"org.matrix.msc2762.receive.state_event:org.matrix.msc3401.call.member",
|
||||
`org.matrix.msc2762.send.state_event:org.matrix.msc3401.call.member#_@alice:example.org_${client.deviceId}`,
|
||||
`org.matrix.msc2762.send.state_event:org.matrix.msc3401.call.member#@alice:example.org_${client.deviceId}`,
|
||||
"org.matrix.msc3819.send.to_device:m.call.invite",
|
||||
"org.matrix.msc3819.receive.to_device:m.call.invite",
|
||||
"org.matrix.msc3819.send.to_device:m.call.candidates",
|
||||
"org.matrix.msc3819.receive.to_device:m.call.candidates",
|
||||
"org.matrix.msc3819.send.to_device:m.call.answer",
|
||||
"org.matrix.msc3819.receive.to_device:m.call.answer",
|
||||
"org.matrix.msc3819.send.to_device:m.call.hangup",
|
||||
"org.matrix.msc3819.receive.to_device:m.call.hangup",
|
||||
"org.matrix.msc3819.send.to_device:m.call.reject",
|
||||
"org.matrix.msc3819.receive.to_device:m.call.reject",
|
||||
"org.matrix.msc3819.send.to_device:m.call.select_answer",
|
||||
"org.matrix.msc3819.receive.to_device:m.call.select_answer",
|
||||
"org.matrix.msc3819.send.to_device:m.call.negotiate",
|
||||
"org.matrix.msc3819.receive.to_device:m.call.negotiate",
|
||||
"org.matrix.msc3819.send.to_device:m.call.sdp_stream_metadata_changed",
|
||||
"org.matrix.msc3819.receive.to_device:m.call.sdp_stream_metadata_changed",
|
||||
"org.matrix.msc3819.send.to_device:org.matrix.call.sdp_stream_metadata_changed",
|
||||
"org.matrix.msc3819.receive.to_device:org.matrix.call.sdp_stream_metadata_changed",
|
||||
"org.matrix.msc3819.send.to_device:m.call.replaces",
|
||||
"org.matrix.msc3819.receive.to_device:m.call.replaces",
|
||||
"org.matrix.msc4157.send.delayed_event",
|
||||
"org.matrix.msc4157.update_delayed_event",
|
||||
]);
|
||||
|
||||
const approvedCapabilities = await driver.validateCapabilities(requestedCapabilities);
|
||||
expect(approvedCapabilities).toEqual(requestedCapabilities);
|
||||
});
|
||||
|
||||
it("approves capabilities via module api", async () => {
|
||||
const driver = mkDefaultDriver();
|
||||
|
||||
const requestedCapabilities = new Set(["org.matrix.msc2931.navigate", "org.matrix.msc2762.timeline:*"]);
|
||||
|
||||
jest.spyOn(ModuleRunner.instance, "invoke").mockImplementation(
|
||||
(lifecycleEvent, opts, widgetInfo, requested) => {
|
||||
if (lifecycleEvent === WidgetLifecycle.CapabilitiesRequest) {
|
||||
(opts as CapabilitiesOpts).approvedCapabilities = requested;
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
const approvedCapabilities = await driver.validateCapabilities(requestedCapabilities);
|
||||
expect(approvedCapabilities).toEqual(requestedCapabilities);
|
||||
});
|
||||
|
||||
it("approves identity via module api", async () => {
|
||||
const driver = mkDefaultDriver();
|
||||
|
||||
jest.spyOn(ModuleRunner.instance, "invoke").mockImplementation((lifecycleEvent, opts, widgetInfo) => {
|
||||
if (lifecycleEvent === WidgetLifecycle.IdentityRequest) {
|
||||
(opts as ApprovalOpts).approved = true;
|
||||
}
|
||||
});
|
||||
|
||||
const listener = jest.fn();
|
||||
const observer = new SimpleObservable<IOpenIDUpdate>();
|
||||
observer.onUpdate(listener);
|
||||
await driver.askOpenID(observer);
|
||||
|
||||
const openIdUpdate: IOpenIDUpdate = {
|
||||
state: OpenIDRequestState.Allowed,
|
||||
token: await client.getOpenIdToken(),
|
||||
};
|
||||
expect(listener).toHaveBeenCalledWith(openIdUpdate);
|
||||
});
|
||||
|
||||
describe("sendToDevice", () => {
|
||||
const contentMap = {
|
||||
"@alice:example.org": {
|
||||
"*": {
|
||||
hello: "alice",
|
||||
},
|
||||
},
|
||||
"@bob:example.org": {
|
||||
bobDesktop: {
|
||||
hello: "bob",
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
let driver: WidgetDriver;
|
||||
|
||||
beforeEach(() => {
|
||||
driver = mkDefaultDriver();
|
||||
});
|
||||
|
||||
it("sends unencrypted messages", async () => {
|
||||
await driver.sendToDevice("org.example.foo", false, contentMap);
|
||||
expect(client.queueToDevice.mock.calls).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it("sends encrypted messages", async () => {
|
||||
const aliceWeb = new DeviceInfo("aliceWeb");
|
||||
const aliceMobile = new DeviceInfo("aliceMobile");
|
||||
const bobDesktop = new DeviceInfo("bobDesktop");
|
||||
|
||||
mocked(client.crypto!.deviceList).downloadKeys.mockResolvedValue(
|
||||
new Map([
|
||||
[
|
||||
"@alice:example.org",
|
||||
new Map([
|
||||
["aliceWeb", aliceWeb],
|
||||
["aliceMobile", aliceMobile],
|
||||
]),
|
||||
],
|
||||
["@bob:example.org", new Map([["bobDesktop", bobDesktop]])],
|
||||
]),
|
||||
);
|
||||
|
||||
await driver.sendToDevice("org.example.foo", true, contentMap);
|
||||
expect(client.encryptAndSendToDevices.mock.calls).toMatchSnapshot();
|
||||
});
|
||||
});
|
||||
|
||||
describe("getTurnServers", () => {
|
||||
let driver: WidgetDriver;
|
||||
|
||||
beforeEach(() => {
|
||||
driver = mkDefaultDriver();
|
||||
});
|
||||
|
||||
it("stops if VoIP isn't supported", async () => {
|
||||
jest.spyOn(client, "pollingTurnServers", "get").mockReturnValue(false);
|
||||
const servers = driver.getTurnServers();
|
||||
expect(await servers.next()).toEqual({ value: undefined, done: true });
|
||||
});
|
||||
|
||||
it("stops if the homeserver provides no TURN servers", async () => {
|
||||
const servers = driver.getTurnServers();
|
||||
expect(await servers.next()).toEqual({ value: undefined, done: true });
|
||||
});
|
||||
|
||||
it("gets TURN servers", async () => {
|
||||
const server1: ITurnServer = {
|
||||
uris: [
|
||||
"turn:turn.example.com:3478?transport=udp",
|
||||
"turn:10.20.30.40:3478?transport=tcp",
|
||||
"turns:10.20.30.40:443?transport=tcp",
|
||||
],
|
||||
username: "1443779631:@user:example.com",
|
||||
password: "JlKfBy1QwLrO20385QyAtEyIv0=",
|
||||
};
|
||||
const server2: ITurnServer = {
|
||||
uris: [
|
||||
"turn:turn.example.com:3478?transport=udp",
|
||||
"turn:10.20.30.40:3478?transport=tcp",
|
||||
"turns:10.20.30.40:443?transport=tcp",
|
||||
],
|
||||
username: "1448999322:@user:example.com",
|
||||
password: "hunter2",
|
||||
};
|
||||
const clientServer1: IClientTurnServer = {
|
||||
urls: server1.uris,
|
||||
username: server1.username,
|
||||
credential: server1.password,
|
||||
};
|
||||
const clientServer2: IClientTurnServer = {
|
||||
urls: server2.uris,
|
||||
username: server2.username,
|
||||
credential: server2.password,
|
||||
};
|
||||
|
||||
client.getTurnServers.mockReturnValue([clientServer1]);
|
||||
const servers = driver.getTurnServers();
|
||||
expect(await servers.next()).toEqual({ value: server1, done: false });
|
||||
|
||||
const nextServer = servers.next();
|
||||
client.getTurnServers.mockReturnValue([clientServer2]);
|
||||
client.emit(ClientEvent.TurnServers, [clientServer2]);
|
||||
expect(await nextServer).toEqual({ value: server2, done: false });
|
||||
|
||||
await servers.return(undefined);
|
||||
});
|
||||
});
|
||||
|
||||
describe("readEventRelations", () => {
|
||||
let driver: WidgetDriver;
|
||||
|
||||
beforeEach(() => {
|
||||
driver = mkDefaultDriver();
|
||||
});
|
||||
|
||||
it("reads related events from the current room", async () => {
|
||||
jest.spyOn(SdkContextClass.instance.roomViewStore, "getRoomId").mockReturnValue("!this-room-id");
|
||||
|
||||
client.relations.mockResolvedValue({
|
||||
originalEvent: new MatrixEvent(),
|
||||
events: [],
|
||||
});
|
||||
|
||||
await expect(driver.readEventRelations("$event")).resolves.toEqual({
|
||||
chunk: [],
|
||||
nextBatch: undefined,
|
||||
prevBatch: undefined,
|
||||
});
|
||||
|
||||
expect(client.relations).toHaveBeenCalledWith("!this-room-id", "$event", null, null, {});
|
||||
});
|
||||
|
||||
it("reads related events from a selected room", async () => {
|
||||
client.relations.mockResolvedValue({
|
||||
originalEvent: new MatrixEvent(),
|
||||
events: [new MatrixEvent(), new MatrixEvent()],
|
||||
nextBatch: "next-batch-token",
|
||||
});
|
||||
|
||||
await expect(driver.readEventRelations("$event", "!room-id")).resolves.toEqual({
|
||||
chunk: [expect.objectContaining({ content: {} }), expect.objectContaining({ content: {} })],
|
||||
nextBatch: "next-batch-token",
|
||||
prevBatch: undefined,
|
||||
});
|
||||
|
||||
expect(client.relations).toHaveBeenCalledWith("!room-id", "$event", null, null, {});
|
||||
});
|
||||
|
||||
it("reads related events with custom parameters", async () => {
|
||||
client.relations.mockResolvedValue({
|
||||
originalEvent: new MatrixEvent(),
|
||||
events: [],
|
||||
});
|
||||
|
||||
await expect(
|
||||
driver.readEventRelations(
|
||||
"$event",
|
||||
"!room-id",
|
||||
"m.reference",
|
||||
"m.room.message",
|
||||
"from-token",
|
||||
"to-token",
|
||||
25,
|
||||
"f",
|
||||
),
|
||||
).resolves.toEqual({
|
||||
chunk: [],
|
||||
nextBatch: undefined,
|
||||
prevBatch: undefined,
|
||||
});
|
||||
|
||||
expect(client.relations).toHaveBeenCalledWith("!room-id", "$event", "m.reference", "m.room.message", {
|
||||
limit: 25,
|
||||
from: "from-token",
|
||||
to: "to-token",
|
||||
dir: Direction.Forward,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("chat effects", () => {
|
||||
let driver: WidgetDriver;
|
||||
// let client: MatrixClient;
|
||||
|
||||
beforeEach(() => {
|
||||
stubClient();
|
||||
driver = mkDefaultDriver();
|
||||
jest.spyOn(dis, "dispatch").mockReset();
|
||||
});
|
||||
|
||||
it("sends chat effects", async () => {
|
||||
await driver.sendEvent(
|
||||
EventType.RoomMessage,
|
||||
{
|
||||
msgtype: MsgType.Text,
|
||||
body: "🎉",
|
||||
},
|
||||
null,
|
||||
);
|
||||
|
||||
expect(dis.dispatch).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not send chat effects in threads", async () => {
|
||||
await driver.sendEvent(
|
||||
EventType.RoomMessage,
|
||||
{
|
||||
"body": "🎉",
|
||||
"m.relates_to": {
|
||||
rel_type: RelationType.Thread,
|
||||
event_id: "$123",
|
||||
},
|
||||
},
|
||||
null,
|
||||
);
|
||||
|
||||
expect(dis.dispatch).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("sendDelayedEvent", () => {
|
||||
let driver: WidgetDriver;
|
||||
const roomId = "!this-room-id";
|
||||
|
||||
beforeEach(() => {
|
||||
driver = mkDefaultDriver();
|
||||
});
|
||||
|
||||
it("cannot send delayed events with missing arguments", async () => {
|
||||
await expect(driver.sendDelayedEvent(null, null, EventType.RoomMessage, {})).rejects.toThrow(
|
||||
"Must provide at least one of",
|
||||
);
|
||||
});
|
||||
|
||||
it("sends delayed message events", async () => {
|
||||
client._unstable_sendDelayedEvent.mockResolvedValue({
|
||||
delay_id: "id",
|
||||
});
|
||||
|
||||
await expect(driver.sendDelayedEvent(2000, null, EventType.RoomMessage, {})).resolves.toEqual({
|
||||
roomId,
|
||||
delayId: "id",
|
||||
});
|
||||
|
||||
expect(client._unstable_sendDelayedEvent).toHaveBeenCalledWith(
|
||||
roomId,
|
||||
{ delay: 2000 },
|
||||
null,
|
||||
EventType.RoomMessage,
|
||||
{},
|
||||
);
|
||||
});
|
||||
|
||||
it("sends child action delayed message events", async () => {
|
||||
client._unstable_sendDelayedEvent.mockResolvedValue({
|
||||
delay_id: "id-child",
|
||||
});
|
||||
|
||||
await expect(driver.sendDelayedEvent(null, "id-parent", EventType.RoomMessage, {})).resolves.toEqual({
|
||||
roomId,
|
||||
delayId: "id-child",
|
||||
});
|
||||
|
||||
expect(client._unstable_sendDelayedEvent).toHaveBeenCalledWith(
|
||||
roomId,
|
||||
{ parent_delay_id: "id-parent" },
|
||||
null,
|
||||
EventType.RoomMessage,
|
||||
{},
|
||||
);
|
||||
});
|
||||
|
||||
it("sends delayed state events", async () => {
|
||||
client._unstable_sendDelayedStateEvent.mockResolvedValue({
|
||||
delay_id: "id",
|
||||
});
|
||||
|
||||
await expect(driver.sendDelayedEvent(2000, null, EventType.RoomTopic, {}, "")).resolves.toEqual({
|
||||
roomId,
|
||||
delayId: "id",
|
||||
});
|
||||
|
||||
expect(client._unstable_sendDelayedStateEvent).toHaveBeenCalledWith(
|
||||
roomId,
|
||||
{ delay: 2000 },
|
||||
EventType.RoomTopic,
|
||||
{},
|
||||
"",
|
||||
);
|
||||
});
|
||||
|
||||
it("sends child action delayed state events", async () => {
|
||||
client._unstable_sendDelayedStateEvent.mockResolvedValue({
|
||||
delay_id: "id-child",
|
||||
});
|
||||
|
||||
await expect(driver.sendDelayedEvent(null, "id-parent", EventType.RoomTopic, {}, "")).resolves.toEqual({
|
||||
roomId,
|
||||
delayId: "id-child",
|
||||
});
|
||||
|
||||
expect(client._unstable_sendDelayedStateEvent).toHaveBeenCalledWith(
|
||||
roomId,
|
||||
{ parent_delay_id: "id-parent" },
|
||||
EventType.RoomTopic,
|
||||
{},
|
||||
"",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("updateDelayedEvent", () => {
|
||||
let driver: WidgetDriver;
|
||||
|
||||
beforeEach(() => {
|
||||
driver = mkDefaultDriver();
|
||||
});
|
||||
|
||||
it("updates delayed events", async () => {
|
||||
client._unstable_updateDelayedEvent.mockResolvedValue({});
|
||||
for (const action of [
|
||||
UpdateDelayedEventAction.Cancel,
|
||||
UpdateDelayedEventAction.Restart,
|
||||
UpdateDelayedEventAction.Send,
|
||||
]) {
|
||||
await expect(driver.updateDelayedEvent("id", action)).resolves.toBeUndefined();
|
||||
expect(client._unstable_updateDelayedEvent).toHaveBeenCalledWith("id", action);
|
||||
}
|
||||
});
|
||||
|
||||
it("fails to update delayed events", async () => {
|
||||
const errorMessage = "Cannot restart this delayed event";
|
||||
client._unstable_updateDelayedEvent.mockRejectedValue(new Error(errorMessage));
|
||||
await expect(driver.updateDelayedEvent("id", UpdateDelayedEventAction.Restart)).rejects.toThrow(
|
||||
errorMessage,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("If the feature_dynamic_room_predecessors feature is not enabled", () => {
|
||||
beforeEach(() => {
|
||||
jest.spyOn(SettingsStore, "getValue").mockReturnValue(false);
|
||||
});
|
||||
|
||||
it("passes the flag through to getVisibleRooms", () => {
|
||||
const driver = mkDefaultDriver();
|
||||
driver.readRoomEvents(EventType.CallAnswer, "", 0, ["*"]);
|
||||
expect(client.getVisibleRooms).toHaveBeenCalledWith(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("If the feature_dynamic_room_predecessors is enabled", () => {
|
||||
beforeEach(() => {
|
||||
// Turn on feature_dynamic_room_predecessors setting
|
||||
jest.spyOn(SettingsStore, "getValue").mockImplementation(
|
||||
(settingName) => settingName === "feature_dynamic_room_predecessors",
|
||||
);
|
||||
});
|
||||
|
||||
it("passes the flag through to getVisibleRooms", () => {
|
||||
const driver = mkDefaultDriver();
|
||||
driver.readRoomEvents(EventType.CallAnswer, "", 0, ["*"]);
|
||||
expect(client.getVisibleRooms).toHaveBeenCalledWith(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("searchUserDirectory", () => {
|
||||
let driver: WidgetDriver;
|
||||
|
||||
beforeEach(() => {
|
||||
driver = mkDefaultDriver();
|
||||
});
|
||||
|
||||
it("searches for users in the user directory", async () => {
|
||||
client.searchUserDirectory.mockResolvedValue({
|
||||
limited: false,
|
||||
results: [{ user_id: "@user", display_name: "Name", avatar_url: "mxc://" }],
|
||||
});
|
||||
|
||||
await expect(driver.searchUserDirectory("foo")).resolves.toEqual({
|
||||
limited: false,
|
||||
results: [{ userId: "@user", displayName: "Name", avatarUrl: "mxc://" }],
|
||||
});
|
||||
|
||||
expect(client.searchUserDirectory).toHaveBeenCalledWith({ term: "foo", limit: undefined });
|
||||
});
|
||||
|
||||
it("searches for users with a custom limit", async () => {
|
||||
client.searchUserDirectory.mockResolvedValue({
|
||||
limited: true,
|
||||
results: [],
|
||||
});
|
||||
|
||||
await expect(driver.searchUserDirectory("foo", 25)).resolves.toEqual({
|
||||
limited: true,
|
||||
results: [],
|
||||
});
|
||||
|
||||
expect(client.searchUserDirectory).toHaveBeenCalledWith({ term: "foo", limit: 25 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("getMediaConfig", () => {
|
||||
let driver: WidgetDriver;
|
||||
|
||||
beforeEach(() => {
|
||||
driver = mkDefaultDriver();
|
||||
});
|
||||
|
||||
it("gets the media configuration", async () => {
|
||||
client.getMediaConfig.mockResolvedValue({
|
||||
"m.upload.size": 1000,
|
||||
});
|
||||
|
||||
await expect(driver.getMediaConfig()).resolves.toEqual({
|
||||
"m.upload.size": 1000,
|
||||
});
|
||||
|
||||
expect(client.getMediaConfig).toHaveBeenCalledWith();
|
||||
});
|
||||
});
|
||||
|
||||
describe("uploadFile", () => {
|
||||
let driver: WidgetDriver;
|
||||
|
||||
beforeEach(() => {
|
||||
driver = mkDefaultDriver();
|
||||
});
|
||||
|
||||
it("uploads a file", async () => {
|
||||
client.uploadContent.mockResolvedValue({
|
||||
content_uri: "mxc://...",
|
||||
});
|
||||
|
||||
await expect(driver.uploadFile("data")).resolves.toEqual({
|
||||
contentUri: "mxc://...",
|
||||
});
|
||||
|
||||
expect(client.uploadContent).toHaveBeenCalledWith("data");
|
||||
});
|
||||
});
|
||||
|
||||
describe("downloadFile", () => {
|
||||
let driver: WidgetDriver;
|
||||
|
||||
beforeEach(() => {
|
||||
driver = mkDefaultDriver();
|
||||
});
|
||||
|
||||
it("should download a file and return the blob", async () => {
|
||||
// eslint-disable-next-line no-restricted-properties
|
||||
client.mxcUrlToHttp.mockImplementation((mxcUrl) => {
|
||||
if (mxcUrl === "mxc://example.com/test_file") {
|
||||
return "https://example.com/_matrix/media/v3/download/example.com/test_file";
|
||||
}
|
||||
|
||||
return null;
|
||||
});
|
||||
|
||||
fetchMockJest.get("https://example.com/_matrix/media/v3/download/example.com/test_file", "test contents");
|
||||
|
||||
const result = await driver.downloadFile("mxc://example.com/test_file");
|
||||
// A type test is impossible here because of
|
||||
// https://github.com/jefflau/jest-fetch-mock/issues/209
|
||||
// Tell TypeScript that file is a blob.
|
||||
const file = result.file as Blob;
|
||||
await expect(file.text()).resolves.toEqual("test contents");
|
||||
});
|
||||
});
|
||||
});
|
100
test/unit-tests/stores/widgets/WidgetPermissionStore-test.ts
Normal file
100
test/unit-tests/stores/widgets/WidgetPermissionStore-test.ts
Normal file
|
@ -0,0 +1,100 @@
|
|||
/*
|
||||
Copyright 2024 New Vector Ltd.
|
||||
Copyright 2022 The Matrix.org Foundation C.I.C.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { mocked } from "jest-mock";
|
||||
import { MatrixClient } from "matrix-js-sdk/src/matrix";
|
||||
import { MatrixWidgetType, Widget, WidgetKind } from "matrix-widget-api";
|
||||
|
||||
import { OIDCState, WidgetPermissionStore } from "../../../../src/stores/widgets/WidgetPermissionStore";
|
||||
import SettingsStore from "../../../../src/settings/SettingsStore";
|
||||
import { TestSdkContext } from "../../TestSdkContext";
|
||||
import { SettingLevel } from "../../../../src/settings/SettingLevel";
|
||||
import { SdkContextClass } from "../../../../src/contexts/SDKContext";
|
||||
import { stubClient } from "../../../test-utils";
|
||||
import { StopGapWidgetDriver } from "../../../../src/stores/widgets/StopGapWidgetDriver";
|
||||
|
||||
jest.mock("../../../../src/settings/SettingsStore");
|
||||
|
||||
describe("WidgetPermissionStore", () => {
|
||||
let widgetPermissionStore: WidgetPermissionStore;
|
||||
let mockClient: MatrixClient;
|
||||
const userId = "@alice:localhost";
|
||||
const roomId = "!room:localhost";
|
||||
const w = new Widget({
|
||||
id: "wid",
|
||||
creatorUserId: userId,
|
||||
type: "m.custom",
|
||||
url: "https://invalid.address.here",
|
||||
});
|
||||
const elementCallWidget = new Widget({
|
||||
id: "group_call",
|
||||
creatorUserId: "@alice:example.org",
|
||||
type: MatrixWidgetType.Custom,
|
||||
url: "https://call.element.io",
|
||||
});
|
||||
let settings: Record<string, any> = {}; // key value store
|
||||
|
||||
beforeEach(() => {
|
||||
settings = {}; // clear settings
|
||||
mocked(SettingsStore.getValue).mockImplementation((setting: string) => {
|
||||
return settings[setting];
|
||||
});
|
||||
mocked(SettingsStore.setValue).mockImplementation(
|
||||
(settingName: string, roomId: string | null, level: SettingLevel, value: any): Promise<void> => {
|
||||
// the store doesn't use any specific level or room ID (room IDs are packed into keys in `value`)
|
||||
settings[settingName] = value;
|
||||
return Promise.resolve();
|
||||
},
|
||||
);
|
||||
mockClient = stubClient();
|
||||
const context = new TestSdkContext();
|
||||
context.client = mockClient;
|
||||
widgetPermissionStore = new WidgetPermissionStore(context);
|
||||
});
|
||||
|
||||
it("should persist OIDCState.Allowed for a widget", () => {
|
||||
widgetPermissionStore.setOIDCState(w, WidgetKind.Account, roomId, OIDCState.Allowed);
|
||||
// check it remembered the value
|
||||
expect(widgetPermissionStore.getOIDCState(w, WidgetKind.Account, roomId)).toEqual(OIDCState.Allowed);
|
||||
});
|
||||
|
||||
it("should persist OIDCState.Denied for a widget", () => {
|
||||
widgetPermissionStore.setOIDCState(w, WidgetKind.Account, roomId, OIDCState.Denied);
|
||||
// check it remembered the value
|
||||
expect(widgetPermissionStore.getOIDCState(w, WidgetKind.Account, roomId)).toEqual(OIDCState.Denied);
|
||||
});
|
||||
|
||||
it("should update OIDCState for a widget", () => {
|
||||
widgetPermissionStore.setOIDCState(w, WidgetKind.Account, roomId, OIDCState.Allowed);
|
||||
widgetPermissionStore.setOIDCState(w, WidgetKind.Account, roomId, OIDCState.Denied);
|
||||
// check it remembered the latest value
|
||||
expect(widgetPermissionStore.getOIDCState(w, WidgetKind.Account, roomId)).toEqual(OIDCState.Denied);
|
||||
});
|
||||
|
||||
it("should scope the location for a widget when setting OIDC state", () => {
|
||||
// allow this widget for this room
|
||||
widgetPermissionStore.setOIDCState(w, WidgetKind.Room, roomId, OIDCState.Allowed);
|
||||
// check it remembered the value
|
||||
expect(widgetPermissionStore.getOIDCState(w, WidgetKind.Room, roomId)).toEqual(OIDCState.Allowed);
|
||||
// check this is not the case for the entire account
|
||||
expect(widgetPermissionStore.getOIDCState(w, WidgetKind.Account, roomId)).toEqual(OIDCState.Unknown);
|
||||
});
|
||||
it("is created once in SdkContextClass", () => {
|
||||
const context = new SdkContextClass();
|
||||
const store = context.widgetPermissionStore;
|
||||
expect(store).toBeDefined();
|
||||
const store2 = context.widgetPermissionStore;
|
||||
expect(store2).toStrictEqual(store);
|
||||
});
|
||||
it("auto-approves OIDC requests for element-call", async () => {
|
||||
new StopGapWidgetDriver([], elementCallWidget, WidgetKind.Room, true, roomId);
|
||||
expect(widgetPermissionStore.getOIDCState(elementCallWidget, WidgetKind.Room, roomId)).toEqual(
|
||||
OIDCState.Allowed,
|
||||
);
|
||||
});
|
||||
});
|
|
@ -0,0 +1,82 @@
|
|||
// Jest Snapshot v1, https://goo.gl/fbAQLP
|
||||
|
||||
exports[`StopGapWidgetDriver sendToDevice sends encrypted messages 1`] = `
|
||||
[
|
||||
[
|
||||
[
|
||||
{
|
||||
"deviceInfo": DeviceInfo {
|
||||
"algorithms": [],
|
||||
"deviceId": "aliceWeb",
|
||||
"keys": {},
|
||||
"known": false,
|
||||
"signatures": {},
|
||||
"unsigned": {},
|
||||
"verified": 0,
|
||||
},
|
||||
"userId": "@alice:example.org",
|
||||
},
|
||||
{
|
||||
"deviceInfo": DeviceInfo {
|
||||
"algorithms": [],
|
||||
"deviceId": "aliceMobile",
|
||||
"keys": {},
|
||||
"known": false,
|
||||
"signatures": {},
|
||||
"unsigned": {},
|
||||
"verified": 0,
|
||||
},
|
||||
"userId": "@alice:example.org",
|
||||
},
|
||||
],
|
||||
{
|
||||
"hello": "alice",
|
||||
},
|
||||
],
|
||||
[
|
||||
[
|
||||
{
|
||||
"deviceInfo": DeviceInfo {
|
||||
"algorithms": [],
|
||||
"deviceId": "bobDesktop",
|
||||
"keys": {},
|
||||
"known": false,
|
||||
"signatures": {},
|
||||
"unsigned": {},
|
||||
"verified": 0,
|
||||
},
|
||||
"userId": "@bob:example.org",
|
||||
},
|
||||
],
|
||||
{
|
||||
"hello": "bob",
|
||||
},
|
||||
],
|
||||
]
|
||||
`;
|
||||
|
||||
exports[`StopGapWidgetDriver sendToDevice sends unencrypted messages 1`] = `
|
||||
[
|
||||
[
|
||||
{
|
||||
"batch": [
|
||||
{
|
||||
"deviceId": "*",
|
||||
"payload": {
|
||||
"hello": "alice",
|
||||
},
|
||||
"userId": "@alice:example.org",
|
||||
},
|
||||
{
|
||||
"deviceId": "bobDesktop",
|
||||
"payload": {
|
||||
"hello": "bob",
|
||||
},
|
||||
"userId": "@bob:example.org",
|
||||
},
|
||||
],
|
||||
"eventType": "org.example.foo",
|
||||
},
|
||||
],
|
||||
]
|
||||
`;
|
Loading…
Add table
Add a link
Reference in a new issue