Skip to content
This repository has been archived by the owner on Sep 11, 2024. It is now read-only.

Commit

Permalink
restructures code to improve testability
Browse files Browse the repository at this point in the history
  • Loading branch information
GoodGuyMarco committed Dec 8, 2022
1 parent bd9e453 commit 360a7bd
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 27 deletions.
54 changes: 32 additions & 22 deletions src/components/views/settings/AddPrivilegedUsers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

import React, { FormEvent, useContext, useRef, useState } from 'react';
import React, { FormEvent, useCallback, useContext, useRef, useState } from 'react';
import { Room } from 'matrix-js-sdk/src/models/room';
import { EventType } from "matrix-js-sdk/src/@types/event";

Expand All @@ -40,31 +40,16 @@ export const AddPrivilegedUsers: React.FC<AddPrivilegedUsersProps> = ({ room, de
const [isLoading, setIsLoading] = useState<boolean>(false);
const [powerLevel, setPowerLevel] = useState<number>(defaultUserLevel);
const [selectedUsers, setSelectedUsers] = useState<ICompletion[]>([]);
// const filterSuggestions = useCallback(
// (user: ICompletion) => {
// if (user.completionId === undefined) {
// return false;
// }
//
// const member = room.getMember(user.completionId);
//
// if (member === null) {
// return false;
// }
//
// return member.powerLevel <= defaultUserLevel;
// },
// [room, defaultUserLevel],
// );
const hasLowerOrEqualLevelThanDefaultLevelFilter = useCallback(
(user: ICompletion) => hasLowerOrEqualLevelThanDefaultLevel(room, user, defaultUserLevel),
[room, defaultUserLevel],
);

const onSubmit = async (event: FormEvent) => {
event.preventDefault();
setIsLoading(true);

const userIds = selectedUsers
.filter(selectedUser => selectedUser.completionId !== undefined)
// undefined completionId's are filtered out but TypeScript does not seem to understand.
.map(selectedUser => selectedUser.completionId!);
const userIds = getUserIdsFromCompletions(selectedUsers);
const powerLevelEvent = room.currentState.getStateEvents(EventType.RoomPowerLevels, "");

try {
Expand Down Expand Up @@ -93,7 +78,7 @@ export const AddPrivilegedUsers: React.FC<AddPrivilegedUsersProps> = ({ room, de
placeholder={_t("Search users in this room…")}
onSelectionChange={setSelectedUsers}
selection={selectedUsers}
// additionalFilter={filterSuggestions}
additionalFilter={hasLowerOrEqualLevelThanDefaultLevelFilter}
/>
<PowerSelector value={powerLevel} onChange={setPowerLevel} />
<AccessibleButton
Expand All @@ -110,3 +95,28 @@ export const AddPrivilegedUsers: React.FC<AddPrivilegedUsersProps> = ({ room, de
</form>
);
};

export const hasLowerOrEqualLevelThanDefaultLevel = (
room: Room,
user: ICompletion,
defaultUserLevel: number,
) => {
if (user.completionId === undefined) {
return false;
}

const member = room.getMember(user.completionId);

if (member === null) {
return false;
}

return member.powerLevel <= defaultUserLevel;
};

export const getUserIdsFromCompletions = (completions: ICompletion[]) => {
const completionsWithId = completions.filter(completion => completion.completionId !== undefined);

// undefined completionId's are filtered out above but TypeScript does not seem to understand.
return completionsWithId.map(completion => completion.completionId!);
};
39 changes: 34 additions & 5 deletions test/components/views/settings/AddPrivilegedUsers-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,30 +17,45 @@ import React from 'react';
import { act, fireEvent, render, waitFor } from '@testing-library/react';
import userEvent from "@testing-library/user-event";
import { mocked } from "jest-mock";
import { RoomMember } from "matrix-js-sdk/src/matrix";

import {
getMockClientWithEventEmitter,
makeRoomWithStateEvents,
} from "../../../test-utils";
import MatrixClientContext from '../../../../src/contexts/MatrixClientContext';
import { AddPrivilegedUsers } from "../../../../src/components/views/settings/AddPrivilegedUsers";
import {
AddPrivilegedUsers,
getUserIdsFromCompletions, hasLowerOrEqualLevelThanDefaultLevel,
} from "../../../../src/components/views/settings/AddPrivilegedUsers";
import UserProvider from "../../../../src/autocomplete/UserProvider";
import { ICompletion } from "../../../../src/autocomplete/Autocompleter";

jest.mock('../../../../src/autocomplete/UserProvider');

const completions: ICompletion[] = [
{ type: 'user', completion: 'user_1', completionId: '@user_1:host.local', range: { start: 1, end: 1 } },
{ type: 'user', completion: 'user_2', completionId: '@user_2:host.local', range: { start: 1, end: 1 } },
{ type: 'user', completion: 'user_without_completion_id', range: { start: 1, end: 1 } },
];

describe('<AddPrivilegedUsers />', () => {
const provider = mocked(UserProvider, { shallow: true });
provider.prototype.getCompletions.mockResolvedValue([
{ type: 'user', completion: 'user_1', completionId: '@user_1:host.local', range: { start: 1, end: 1 } },
{ type: 'user', completion: 'user_2', completionId: '@user_2:host.local', range: { start: 1, end: 1 } },
]);
provider.prototype.getCompletions.mockResolvedValue(completions);

const mockClient = getMockClientWithEventEmitter({
// `makeRoomWithStateEvents` only work's if `getRoom` is present.
getRoom: jest.fn(),
setPowerLevel: jest.fn(),
});

const room = makeRoomWithStateEvents([], { roomId: 'room_id', mockClient: mockClient });
room.getMember = (userId: string) => {
const member = new RoomMember('room_id', userId);
member.powerLevel = 0;

return member;
};

const getComponent = () =>
<MatrixClientContext.Provider value={mockClient}>
Expand Down Expand Up @@ -111,4 +126,18 @@ describe('<AddPrivilegedUsers />', () => {
expect((getByTestId('power-level-option-50') as HTMLOptionElement).selected).toBeFalsy();
expect((getByTestId('power-level-option-100') as HTMLOptionElement).selected).toBeFalsy();
});

it('getUserIdsFromCompletions() should map completions to user id\'s', () => {
expect(getUserIdsFromCompletions(completions)).toStrictEqual(['@user_1:host.local', '@user_2:host.local']);
});

it.each([
{ defaultUserLevel: -50, expectation: false },
{ defaultUserLevel: 0, expectation: true },
{ defaultUserLevel: 50, expectation: true },
])('hasLowerOrEqualLevelThanDefaultLevel() should return $expectation for default level $defaultUserLevel',
({ defaultUserLevel, expectation }) => {
expect(hasLowerOrEqualLevelThanDefaultLevel(room, completions[0], defaultUserLevel)).toBe(expectation);
},
);
});

0 comments on commit 360a7bd

Please sign in to comment.