Conform more code to strict null checking (#10153)

* Conform more code to strict null checking

* Conform more code to strict null checking

* Iterate

* Iterate
This commit is contained in:
Michael Telatynski 2023-02-15 13:36:22 +00:00 committed by GitHub
parent a4ff959aa1
commit 145a5a8a8d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
89 changed files with 520 additions and 551 deletions

View file

@ -345,7 +345,7 @@ describe("Notifier", () => {
tweaks: {},
});
Notifier.start();
Notifier.onSyncStateChange(SyncState.Syncing);
Notifier.onSyncStateChange(SyncState.Syncing, null);
});
afterEach(() => {

View file

@ -33,21 +33,23 @@ describe("SlashCommands", () => {
let localRoom: LocalRoom;
let command: Command;
const findCommand = (cmd: string): Command => {
const findCommand = (cmd: string): Command | undefined => {
return Commands.find((command: Command) => command.command === cmd);
};
const setCurrentRoom = (): void => {
mocked(SdkContextClass.instance.roomViewStore.getRoomId).mockReturnValue(roomId);
mocked(client.getRoom).mockImplementation((rId: string): Room => {
mocked(client.getRoom).mockImplementation((rId: string): Room | null => {
if (rId === roomId) return room;
return null;
});
};
const setCurrentLocalRoon = (): void => {
mocked(SdkContextClass.instance.roomViewStore.getRoomId).mockReturnValue(localRoomId);
mocked(client.getRoom).mockImplementation((rId: string): Room => {
mocked(client.getRoom).mockImplementation((rId: string): Room | null => {
if (rId === localRoomId) return localRoom;
return null;
});
};
@ -57,8 +59,8 @@ describe("SlashCommands", () => {
client = createTestClient();
jest.spyOn(MatrixClientPeg, "get").mockReturnValue(client);
room = new Room(roomId, client, client.getUserId());
localRoom = new LocalRoom(localRoomId, client, client.getUserId());
room = new Room(roomId, client, client.getUserId()!);
localRoom = new LocalRoom(localRoomId, client, client.getUserId()!);
jest.spyOn(SdkContextClass.instance.roomViewStore, "getRoomId");
});
@ -68,7 +70,7 @@ describe("SlashCommands", () => {
const command = getCommand("/topic pizza");
expect(command.cmd).toBeDefined();
expect(command.args).toBeDefined();
await command.cmd.run("room-id", null, command.args);
await command.cmd!.run("room-id", null, command.args);
expect(client.setRoomTopic).toHaveBeenCalledWith("room-id", "pizza", undefined);
});
});
@ -96,7 +98,7 @@ describe("SlashCommands", () => {
["converttoroom"],
])("/%s", (commandName: string) => {
beforeEach(() => {
command = findCommand(commandName);
command = findCommand(commandName)!;
});
describe("isEnabled", () => {
@ -114,7 +116,7 @@ describe("SlashCommands", () => {
describe("/tovirtual", () => {
beforeEach(() => {
command = findCommand("tovirtual");
command = findCommand("tovirtual")!;
});
describe("isEnabled", () => {
@ -154,7 +156,7 @@ describe("SlashCommands", () => {
describe("/remakeolm", () => {
beforeEach(() => {
command = findCommand("remakeolm");
command = findCommand("remakeolm")!;
});
describe("isEnabled", () => {
@ -198,39 +200,39 @@ describe("SlashCommands", () => {
describe("/part", () => {
it("should part room matching alias if found", async () => {
const room1 = new Room("room-id", client, client.getUserId());
const room1 = new Room("room-id", client, client.getUserId()!);
room1.getCanonicalAlias = jest.fn().mockReturnValue("#foo:bar");
const room2 = new Room("other-room", client, client.getUserId());
const room2 = new Room("other-room", client, client.getUserId()!);
room2.getCanonicalAlias = jest.fn().mockReturnValue("#baz:bar");
mocked(client.getRooms).mockReturnValue([room1, room2]);
const command = getCommand("/part #foo:bar");
expect(command.cmd).toBeDefined();
expect(command.args).toBeDefined();
await command.cmd.run("room-id", null, command.args);
await command.cmd!.run("room-id", null, command.args);
expect(client.leaveRoomChain).toHaveBeenCalledWith("room-id", expect.anything());
});
it("should part room matching alt alias if found", async () => {
const room1 = new Room("room-id", client, client.getUserId());
const room1 = new Room("room-id", client, client.getUserId()!);
room1.getAltAliases = jest.fn().mockReturnValue(["#foo:bar"]);
const room2 = new Room("other-room", client, client.getUserId());
const room2 = new Room("other-room", client, client.getUserId()!);
room2.getAltAliases = jest.fn().mockReturnValue(["#baz:bar"]);
mocked(client.getRooms).mockReturnValue([room1, room2]);
const command = getCommand("/part #foo:bar");
expect(command.cmd).toBeDefined();
expect(command.args).toBeDefined();
await command.cmd.run("room-id", null, command.args);
await command.cmd!.run("room-id", null, command.args);
expect(client.leaveRoomChain).toHaveBeenCalledWith("room-id", expect.anything());
});
});
describe.each(["rainbow", "rainbowme"])("/%s", (commandName: string) => {
const command = findCommand(commandName);
const command = findCommand(commandName)!;
it("should return usage if no args", () => {
expect(command.run(roomId, null, null).error).toBe(command.getUsage());
expect(command.run(roomId, null).error).toBe(command.getUsage());
});
it("should make things rainbowy", () => {

View file

@ -50,19 +50,19 @@ describe("SlidingSyncManager", () => {
});
it("adds a custom subscription for a lazy-loadable room", async () => {
const roomId = "!lazy:id";
const room = new Room(roomId, client, client.getUserId());
const room = new Room(roomId, client, client.getUserId()!);
room.getLiveTimeline().initialiseState([
new MatrixEvent({
type: "m.room.create",
state_key: "",
event_id: "$abc123",
sender: client.getUserId(),
sender: client.getUserId()!,
content: {
creator: client.getUserId(),
},
}),
]);
mocked(client.getRoom).mockImplementation((r: string): Room => {
mocked(client.getRoom).mockImplementation((r: string): Room | null => {
if (roomId === r) {
return room;
}

View file

@ -73,16 +73,16 @@ describe("EmojiProvider", function () {
add("😘"); //kissing_heart
add("😘");
add("😚"); //kissing_closed_eyes
const emojiProvider = new EmojiProvider(null);
const emojiProvider = new EmojiProvider(null!);
let completionsList = await emojiProvider.getCompletions(":kis", { beginning: true, end: 3, start: 3 });
expect(completionsList[0].component.props.title).toEqual(":kissing_heart:");
expect(completionsList[1].component.props.title).toEqual(":kissing_closed_eyes:");
expect(completionsList[0].component!.props.title).toEqual(":kissing_heart:");
expect(completionsList[1].component!.props.title).toEqual(":kissing_closed_eyes:");
completionsList = await emojiProvider.getCompletions(":kissing_c", { beginning: true, end: 3, start: 3 });
expect(completionsList[0].component.props.title).toEqual(":kissing_closed_eyes:");
expect(completionsList[0].component!.props.title).toEqual(":kissing_closed_eyes:");
completionsList = await emojiProvider.getCompletions(":so", { beginning: true, end: 2, start: 2 });
expect(completionsList[0].component.props.title).toEqual(":sob:");
expect(completionsList[0].component!.props.title).toEqual(":sob:");
});
});

View file

@ -46,7 +46,7 @@ jest.mock("../../../src/utils/beacon", () => ({
const roomId = "!roomId:server_name";
describe("MessagePanel", function () {
let clock: FakeTimers.InstalledClock | null = null;
let clock: FakeTimers.InstalledClock;
const realSetTimeout = window.setTimeout;
const events = mkEvents();
const userId = "@me:here";
@ -117,14 +117,11 @@ describe("MessagePanel", function () {
});
afterEach(function () {
if (clock) {
clock.uninstall();
clock = null;
}
clock?.uninstall();
});
function mkEvents() {
const events = [];
const events: MatrixEvent[] = [];
const ts0 = Date.now();
for (let i = 0; i < 10; i++) {
events.push(
@ -141,7 +138,7 @@ describe("MessagePanel", function () {
// Just to avoid breaking Dateseparator tests that might run at 00hrs
function mkOneDayEvents() {
const events = [];
const events: MatrixEvent[] = [];
const ts0 = Date.parse("09 May 2004 00:12:00 GMT");
for (let i = 0; i < 10; i++) {
events.push(
@ -158,7 +155,7 @@ describe("MessagePanel", function () {
// make a collection of events with some member events that should be collapsed with an EventListSummary
function mkMelsEvents() {
const events = [];
const events: MatrixEvent[] = [];
const ts0 = Date.now();
let i = 0;
@ -200,7 +197,7 @@ describe("MessagePanel", function () {
// A list of membership events only with nothing else
function mkMelsEventsOnly() {
const events = [];
const events: MatrixEvent[] = [];
const ts0 = Date.now();
let i = 0;
@ -323,7 +320,7 @@ describe("MessagePanel", function () {
}
function isReadMarkerVisible(rmContainer?: Element) {
return rmContainer?.children.length > 0;
return !!rmContainer?.children.length;
}
it("should show the events", function () {
@ -466,8 +463,8 @@ describe("MessagePanel", function () {
it("should collapse creation events", function () {
const events = mkCreationEvents();
const createEvent = events.find((event) => event.getType() === "m.room.create");
const encryptionEvent = events.find((event) => event.getType() === "m.room.encryption");
const createEvent = events.find((event) => event.getType() === "m.room.create")!;
const encryptionEvent = events.find((event) => event.getType() === "m.room.encryption")!;
client.getRoom.mockImplementation((id) => (id === createEvent!.getRoomId() ? room : null));
TestUtilsMatrix.upsertRoomStateEvents(room, events);
@ -493,8 +490,8 @@ describe("MessagePanel", function () {
it("should not collapse beacons as part of creation events", function () {
const events = mkCreationEvents();
const creationEvent = events.find((event) => event.getType() === "m.room.create");
const beaconInfoEvent = makeBeaconInfoEvent(creationEvent.getSender(), creationEvent.getRoomId(), {
const creationEvent = events.find((event) => event.getType() === "m.room.create")!;
const beaconInfoEvent = makeBeaconInfoEvent(creationEvent.getSender()!, creationEvent.getRoomId()!, {
isLive: true,
});
const combinedEvents = [...events, beaconInfoEvent];
@ -550,7 +547,7 @@ describe("MessagePanel", function () {
let els = container.getElementsByClassName("mx_GenericEventListSummary");
expect(els.length).toEqual(1);
expect(els[0].getAttribute("data-testid")).toEqual("eventlistsummary-" + events[0].getId());
expect(els[0].getAttribute("data-scroll-tokens").split(",").length).toEqual(10);
expect(els[0].getAttribute("data-scroll-tokens")?.split(",")).toHaveLength(10);
const updatedEvents = [
...events,
@ -570,7 +567,7 @@ describe("MessagePanel", function () {
els = container.getElementsByClassName("mx_GenericEventListSummary");
expect(els.length).toEqual(1);
expect(els[0].getAttribute("data-testid")).toEqual("eventlistsummary-" + events[0].getId());
expect(els[0].getAttribute("data-scroll-tokens").split(",").length).toEqual(11);
expect(els[0].getAttribute("data-scroll-tokens")?.split(",")).toHaveLength(11);
});
it("prepends events into summaries during backward pagination without changing key", () => {
@ -580,7 +577,7 @@ describe("MessagePanel", function () {
let els = container.getElementsByClassName("mx_GenericEventListSummary");
expect(els.length).toEqual(1);
expect(els[0].getAttribute("data-testid")).toEqual("eventlistsummary-" + events[0].getId());
expect(els[0].getAttribute("data-scroll-tokens").split(",").length).toEqual(10);
expect(els[0].getAttribute("data-scroll-tokens")?.split(",")).toHaveLength(10);
const updatedEvents = [
TestUtilsMatrix.mkMembership({
@ -600,7 +597,7 @@ describe("MessagePanel", function () {
els = container.getElementsByClassName("mx_GenericEventListSummary");
expect(els.length).toEqual(1);
expect(els[0].getAttribute("data-testid")).toEqual("eventlistsummary-" + events[0].getId());
expect(els[0].getAttribute("data-scroll-tokens").split(",").length).toEqual(11);
expect(els[0].getAttribute("data-scroll-tokens")?.split(",")).toHaveLength(11);
});
it("assigns different keys to summaries that get split up", () => {
@ -610,7 +607,7 @@ describe("MessagePanel", function () {
let els = container.getElementsByClassName("mx_GenericEventListSummary");
expect(els.length).toEqual(1);
expect(els[0].getAttribute("data-testid")).toEqual(`eventlistsummary-${events[0].getId()}`);
expect(els[0].getAttribute("data-scroll-tokens").split(",").length).toEqual(10);
expect(els[0].getAttribute("data-scroll-tokens")?.split(",")).toHaveLength(10);
const updatedEvents = [
...events.slice(0, 5),
@ -628,10 +625,10 @@ describe("MessagePanel", function () {
els = container.getElementsByClassName("mx_GenericEventListSummary");
expect(els.length).toEqual(2);
expect(els[0].getAttribute("data-testid")).toEqual(`eventlistsummary-${events[0].getId()}`);
expect(els[0].getAttribute("data-scroll-tokens").split(",").length).toEqual(5);
expect(els[0].getAttribute("data-scroll-tokens")?.split(",")).toHaveLength(5);
expect(els[1].getAttribute("data-testid")).toEqual(`eventlistsummary-${events[5].getId()}`);
expect(els[1].getAttribute("data-scroll-tokens").split(",").length).toEqual(5);
expect(els[1].getAttribute("data-scroll-tokens")?.split(",")).toHaveLength(5);
});
// We test this because setting lookups can be *slow*, and we don't want
@ -681,7 +678,7 @@ describe("MessagePanel", function () {
const els = container.getElementsByClassName("mx_GenericEventListSummary");
expect(els.length).toEqual(1);
expect(els[0].getAttribute("data-scroll-tokens").split(",").length).toEqual(3);
expect(els[0].getAttribute("data-scroll-tokens")?.split(",")).toHaveLength(3);
});
});

View file

@ -68,7 +68,7 @@ describe("ThreadPanel", () => {
const found = container.querySelector(".mx_ThreadPanel_dropdown");
expect(found).toBeTruthy();
expect(screen.queryByRole("menu")).toBeFalsy();
fireEvent.click(found);
fireEvent.click(found!);
expect(screen.queryByRole("menu")).toBeTruthy();
});
@ -80,11 +80,13 @@ describe("ThreadPanel", () => {
setFilterOption={() => undefined}
/>,
);
fireEvent.click(container.querySelector(".mx_ThreadPanel_dropdown"));
fireEvent.click(container.querySelector(".mx_ThreadPanel_dropdown")!);
const found = screen.queryAllByRole("menuitemradio");
expect(found).toHaveLength(2);
const foundButton = screen.queryByRole("menuitemradio", { checked: true });
expect(foundButton.textContent).toEqual(`${_t("All threads")}${_t("Shows all threads from current room")}`);
expect(foundButton?.textContent).toEqual(
`${_t("All threads")}${_t("Shows all threads from current room")}`,
);
expect(foundButton).toMatchSnapshot();
});
});

View file

@ -111,7 +111,7 @@ describe("<LeftPanelLiveShareWarning />", () => {
const { container } = getComponent();
const dispatchSpy = jest.spyOn(dispatcher, "dispatch");
fireEvent.click(container.querySelector("[role=button]"));
fireEvent.click(container.querySelector("[role=button]")!);
expect(dispatchSpy).toHaveBeenCalledWith({
action: Action.ViewRoom,
@ -144,7 +144,7 @@ describe("<LeftPanelLiveShareWarning />", () => {
const { container } = getComponent();
const dispatchSpy = jest.spyOn(dispatcher, "dispatch");
fireEvent.click(container.querySelector("[role=button]"));
fireEvent.click(container.querySelector("[role=button]")!);
expect(dispatchSpy).toHaveBeenCalledWith({
action: Action.ViewRoom,
@ -163,7 +163,7 @@ describe("<LeftPanelLiveShareWarning />", () => {
]);
const { container, rerender } = getComponent();
// error mode
expect(container.querySelector(".mx_LeftPanelLiveShareWarning").textContent).toEqual(
expect(container.querySelector(".mx_LeftPanelLiveShareWarning")?.textContent).toEqual(
"An error occurred whilst sharing your live location",
);
@ -175,7 +175,7 @@ describe("<LeftPanelLiveShareWarning />", () => {
rerender(<LeftPanelLiveShareWarning />);
// default mode
expect(container.querySelector(".mx_LeftPanelLiveShareWarning").textContent).toEqual(
expect(container.querySelector(".mx_LeftPanelLiveShareWarning")?.textContent).toEqual(
"You are sharing your live location",
);
});
@ -252,7 +252,7 @@ describe("<LeftPanelLiveShareWarning />", () => {
const { container } = getComponent();
const dispatchSpy = jest.spyOn(dispatcher, "dispatch");
fireEvent.click(container.querySelector("[role=button]"));
fireEvent.click(container.querySelector("[role=button]")!);
expect(dispatchSpy).toHaveBeenCalledWith({
action: Action.ViewRoom,

View file

@ -74,13 +74,13 @@ describe("ForwardDialog", () => {
const mountForwardDialog = (message = defaultMessage, rooms = defaultRooms) => {
mockClient.getVisibleRooms.mockReturnValue(rooms);
mockClient.getRoom.mockImplementation((roomId) => rooms.find((room) => room.roomId === roomId));
mockClient.getRoom.mockImplementation((roomId) => rooms.find((room) => room.roomId === roomId) || null);
const wrapper: RenderResult = render(
<ForwardDialog
matrixClient={mockClient}
event={message}
permalinkCreator={new RoomPermalinkCreator(undefined, sourceRoom)}
permalinkCreator={new RoomPermalinkCreator(undefined!, sourceRoom)}
onFinished={jest.fn()}
/>,
);
@ -135,8 +135,8 @@ describe("ForwardDialog", () => {
}),
);
let firstButton: Element;
let secondButton: Element;
let firstButton!: Element;
let secondButton!: Element;
const update = () => {
[firstButton, secondButton] = container.querySelectorAll(".mx_ForwardList_sendButton");
};
@ -253,7 +253,6 @@ describe("ForwardDialog", () => {
[M_ASSET.name]: { type: LocationAssetType.Pin },
[M_LOCATION.name]: {
uri: geoUri,
description: undefined as string,
},
};
expect(mockClient.sendEvent).toHaveBeenCalledWith(
@ -269,7 +268,7 @@ describe("ForwardDialog", () => {
expect(container.querySelector(".mx_MLocationBody")).toBeTruthy();
sendToFirstRoom(container);
const timestamp = M_TIMESTAMP.findIn<number>(modernLocationEvent.getContent());
const timestamp = M_TIMESTAMP.findIn<number>(modernLocationEvent.getContent())!;
// text and description from original event are removed
// text gets new default message from event values
const text = `Location ${geoUri} at ${new Date(timestamp).toISOString()}`;
@ -280,7 +279,6 @@ describe("ForwardDialog", () => {
[M_ASSET.name]: { type: LocationAssetType.Pin },
[M_LOCATION.name]: {
uri: geoUri,
description: undefined as string,
},
};
expect(mockClient.sendEvent).toHaveBeenCalledWith(
@ -301,7 +299,6 @@ describe("ForwardDialog", () => {
[M_ASSET.name]: { type: LocationAssetType.Pin },
[M_LOCATION.name]: {
uri: geoUri,
description: undefined as string,
},
geo_uri: geoUri,
[M_TIMESTAMP.name]: timestamp,

View file

@ -92,7 +92,7 @@ function mockClient({
(it) =>
!searchTerm ||
it.user_id.toLowerCase().includes(searchTerm) ||
it.display_name.toLowerCase().includes(searchTerm),
it.display_name?.toLowerCase().includes(searchTerm),
);
return Promise.resolve({
results: results.slice(0, limit ?? +Infinity),
@ -138,7 +138,7 @@ describe("Spotlight Dialog", () => {
mockedClient = mockClient({ rooms: [testPublicRoom], users: [testPerson] });
testRoom = mkRoom(mockedClient, "!test23:example.com");
mocked(testRoom.getMyMembership).mockReturnValue("join");
testLocalRoom = new LocalRoom(LOCAL_ROOM_ID_PREFIX + "test23", mockedClient, mockedClient.getUserId());
testLocalRoom = new LocalRoom(LOCAL_ROOM_ID_PREFIX + "test23", mockedClient, mockedClient.getUserId()!);
testLocalRoom.updateMyMembership("join");
mocked(mockedClient.getVisibleRooms).mockReturnValue([testRoom, testLocalRoom]);
@ -149,7 +149,7 @@ describe("Spotlight Dialog", () => {
describe("should apply filters supplied via props", () => {
it("without filter", async () => {
const wrapper = mount(<SpotlightDialog initialFilter={null} onFinished={() => null} />);
const wrapper = mount(<SpotlightDialog onFinished={() => null} />);
await act(async () => {
await sleep(200);
});

View file

@ -61,7 +61,7 @@ describe("<StyledRadioGroup />", () => {
value: optionC.value,
});
expect(getCheckedInput(component).value).toEqual(optionC.value);
expect(getCheckedInput(component)?.value).toEqual(optionC.value);
});
it("selects correct buttons when definitions have checked prop", () => {
@ -99,7 +99,7 @@ describe("<StyledRadioGroup />", () => {
onChange,
});
fireEvent.click(getInputByValue(component, optionB.value));
fireEvent.click(getInputByValue(component, optionB.value)!);
expect(onChange).toHaveBeenCalledWith(optionB.value);
});

View file

@ -62,7 +62,7 @@ describe("<TooltipTarget />", () => {
const alignmentKeys = Object.keys(Alignment).filter((o: any) => isNaN(o));
it.each(alignmentKeys)("displays %s aligned tooltip on mouseover", async (alignment: any) => {
const wrapper = getComponent({ alignment: Alignment[alignment] });
const wrapper = getComponent({ alignment: Alignment[alignment] })!;
act(() => {
Simulate.mouseOver(wrapper);
});
@ -70,7 +70,7 @@ describe("<TooltipTarget />", () => {
});
it("hides tooltip on mouseleave", () => {
const wrapper = getComponent();
const wrapper = getComponent()!;
act(() => {
Simulate.mouseOver(wrapper);
});
@ -82,7 +82,7 @@ describe("<TooltipTarget />", () => {
});
it("displays tooltip on focus", () => {
const wrapper = getComponent();
const wrapper = getComponent()!;
act(() => {
Simulate.focus(wrapper);
});
@ -90,7 +90,7 @@ describe("<TooltipTarget />", () => {
});
it("hides tooltip on blur", async () => {
const wrapper = getComponent();
const wrapper = getComponent()!;
act(() => {
Simulate.focus(wrapper);
});

View file

@ -53,7 +53,7 @@ describe("shareLocation", () => {
},
);
shareLocationFn = shareLocation(client, roomId, shareType, null, () => {});
shareLocationFn = shareLocation(client, roomId, shareType, undefined, () => {});
});
it("should forward the call to doMaybeLocalRoomAction", () => {

View file

@ -52,7 +52,7 @@ describe("EncryptionEvent", () => {
event = mkMessage({
event: true,
room: roomId,
user: client.getUserId(),
user: client.getUserId()!,
});
jest.spyOn(DMRoomMap, "shared").mockReturnValue({
getUserIdForRoomId: jest.fn(),
@ -61,9 +61,9 @@ describe("EncryptionEvent", () => {
describe("for an encrypted room", () => {
beforeEach(() => {
event.event.content.algorithm = algorithm;
event.event.content!.algorithm = algorithm;
mocked(client.isRoomEncrypted).mockReturnValue(true);
const room = new Room(roomId, client, client.getUserId());
const room = new Room(roomId, client, client.getUserId()!);
mocked(client.getRoom).mockReturnValue(room);
});
@ -91,7 +91,7 @@ describe("EncryptionEvent", () => {
describe("with unknown algorithm", () => {
beforeEach(() => {
event.event.content.algorithm = "unknown";
event.event.content!.algorithm = "unknown";
});
it("should show the expected texts", () => {
@ -115,9 +115,9 @@ describe("EncryptionEvent", () => {
describe("for an encrypted local room", () => {
beforeEach(() => {
event.event.content.algorithm = algorithm;
event.event.content!.algorithm = algorithm;
mocked(client.isRoomEncrypted).mockReturnValue(true);
const localRoom = new LocalRoom(roomId, client, client.getUserId());
const localRoom = new LocalRoom(roomId, client, client.getUserId()!);
mocked(client.getRoom).mockReturnValue(localRoom);
renderEncryptionEvent(client, event);
});

View file

@ -236,9 +236,7 @@ describe("<MessageActionBar />", () => {
it("opens message context menu on click", () => {
const { getByTestId, queryByLabelText } = getComponent({ mxEvent: alicesMessageEvent });
act(() => {
fireEvent.click(queryByLabelText("Options"));
});
fireEvent.click(queryByLabelText("Options")!);
expect(getByTestId("mx_MessageContextMenu")).toBeTruthy();
});
});
@ -269,9 +267,7 @@ describe("<MessageActionBar />", () => {
it("dispatches reply event on click", () => {
const { queryByLabelText } = getComponent({ mxEvent: alicesMessageEvent });
act(() => {
fireEvent.click(queryByLabelText("Reply"));
});
fireEvent.click(queryByLabelText("Reply")!);
expect(dispatcher.dispatch).toHaveBeenCalledWith({
action: "reply_to_event",
@ -306,9 +302,7 @@ describe("<MessageActionBar />", () => {
it("opens reaction picker on click", () => {
const { queryByLabelText, getByTestId } = getComponent({ mxEvent: alicesMessageEvent });
act(() => {
fireEvent.click(queryByLabelText("React"));
});
fireEvent.click(queryByLabelText("React")!);
expect(getByTestId("mx_EmojiPicker")).toBeTruthy();
});
});
@ -421,9 +415,7 @@ describe("<MessageActionBar />", () => {
jest.spyOn(SettingsStore, "getValue").mockReturnValue(false);
const { getByLabelText } = getComponent({ mxEvent: alicesMessageEvent });
act(() => {
fireEvent.click(getByLabelText("Reply in thread"));
});
fireEvent.click(getByLabelText("Reply in thread"));
expect(dispatcher.dispatch).toHaveBeenCalledWith({
action: Action.ViewUserSettings,
@ -453,9 +445,7 @@ describe("<MessageActionBar />", () => {
it("opens thread on click", () => {
const { getByLabelText } = getComponent({ mxEvent: alicesMessageEvent });
act(() => {
fireEvent.click(getByLabelText("Reply in thread"));
});
fireEvent.click(getByLabelText("Reply in thread"));
expect(dispatcher.dispatch).toHaveBeenCalledWith({
action: Action.ShowThread,
@ -482,9 +472,7 @@ describe("<MessageActionBar />", () => {
} as unknown as Thread);
const { getByLabelText } = getComponent({ mxEvent: threadReplyEvent });
act(() => {
fireEvent.click(getByLabelText("Reply in thread"));
});
fireEvent.click(getByLabelText("Reply in thread"));
expect(dispatcher.dispatch).toHaveBeenCalledWith({
action: Action.ShowThread,
@ -501,7 +489,7 @@ describe("<MessageActionBar />", () => {
describe("favourite button", () => {
//for multiple event usecase
const favButton = (evt: MatrixEvent) => {
return getComponent({ mxEvent: evt }).getByTestId(evt.getId());
return getComponent({ mxEvent: evt }).getByTestId(evt.getId()!);
};
describe("when favourite_messages feature is enabled", () => {
@ -538,9 +526,7 @@ describe("<MessageActionBar />", () => {
expect(localStorageMock.getItem("io_element_favouriteMessages")).toBeNull();
//if only alice's event is fired
act(() => {
fireEvent.click(alicesAction);
});
fireEvent.click(alicesAction);
expect(alicesAction.classList).toContain("mx_MessageActionBar_favouriteButton_fillstar");
expect(bobsAction.classList).not.toContain("mx_MessageActionBar_favouriteButton_fillstar");
@ -550,9 +536,7 @@ describe("<MessageActionBar />", () => {
);
//when bob's event is fired,both should be styled and stored in localStorage
act(() => {
fireEvent.click(bobsAction);
});
fireEvent.click(bobsAction);
expect(alicesAction.classList).toContain("mx_MessageActionBar_favouriteButton_fillstar");
expect(bobsAction.classList).toContain("mx_MessageActionBar_favouriteButton_fillstar");
@ -567,9 +551,7 @@ describe("<MessageActionBar />", () => {
);
//if decided to unfavourite bob's event by clicking again
act(() => {
fireEvent.click(bobsAction);
});
fireEvent.click(bobsAction);
expect(bobsAction.classList).not.toContain("mx_MessageActionBar_favouriteButton_fillstar");
expect(alicesAction.classList).toContain("mx_MessageActionBar_favouriteButton_fillstar");
expect(localStorageMock.getItem("io_element_favouriteMessages")).toEqual('["$alices_message"]');
@ -599,9 +581,7 @@ describe("<MessageActionBar />", () => {
event.preventDefault = jest.fn();
const { queryByTestId, queryByLabelText } = getComponent({ mxEvent: alicesMessageEvent });
act(() => {
fireEvent(queryByLabelText(buttonLabel), event);
});
fireEvent(queryByLabelText(buttonLabel)!, event);
expect(event.stopPropagation).toHaveBeenCalled();
expect(event.preventDefault).toHaveBeenCalled();
expect(queryByTestId("mx_MessageContextMenu")).toBeFalsy();
@ -610,9 +590,7 @@ describe("<MessageActionBar />", () => {
it("does shows context menu when right-clicking options", () => {
const { queryByTestId, queryByLabelText } = getComponent({ mxEvent: alicesMessageEvent });
act(() => {
fireEvent.contextMenu(queryByLabelText("Options"));
});
fireEvent.contextMenu(queryByLabelText("Options")!);
expect(queryByTestId("mx_MessageContextMenu")).toBeTruthy();
});
});

View file

@ -44,11 +44,11 @@ describe("MemberList", () => {
return room;
}
let parentDiv: HTMLDivElement = null;
let client: MatrixClient = null;
let root: Component = null;
let parentDiv: HTMLDivElement;
let client: MatrixClient;
let root: Component;
let memberListRoom: Room;
let memberList: MemberList = null;
let memberList: MemberList;
let adminUsers: RoomMember[] = [];
let moderatorUsers: RoomMember[] = [];
@ -140,14 +140,13 @@ describe("MemberList", () => {
if (parentDiv) {
ReactDOM.unmountComponentAtNode(parentDiv);
parentDiv.remove();
parentDiv = null;
}
done();
});
function expectOrderedByPresenceAndPowerLevel(memberTiles: MemberTile[], isPresenceEnabled: boolean) {
let prevMember = null;
let prevMember: RoomMember | undefined;
for (const tile of memberTiles) {
const memberA = prevMember;
const memberB = tile.props.member;
@ -160,8 +159,8 @@ describe("MemberList", () => {
console.log(memberList.memberString(memberA));
console.log(memberList.memberString(memberB));
const userA = memberA.user;
const userB = memberB.user;
const userA = memberA.user!;
const userB = memberB.user!;
let groupChange = false;
@ -229,16 +228,16 @@ describe("MemberList", () => {
const onlineUsers = [adminUsers[0]];
const offlineUsers = [...moderatorUsers, ...adminUsers.slice(1), ...defaultUsers.slice(1)];
activeUsers.forEach((u) => {
u.user.currentlyActive = true;
u.user.presence = "online";
u.user!.currentlyActive = true;
u.user!.presence = "online";
});
onlineUsers.forEach((u) => {
u.user.currentlyActive = false;
u.user.presence = "online";
u.user!.currentlyActive = false;
u.user!.presence = "online";
});
offlineUsers.forEach((u) => {
u.user.currentlyActive = false;
u.user.presence = "offline";
u.user!.currentlyActive = false;
u.user!.presence = "offline";
});
// Bypass all the event listeners and skip to the good part
@ -268,18 +267,18 @@ describe("MemberList", () => {
const inactiveUsers = [...moderatorUsers, ...adminUsers.slice(1), ...defaultUsers.slice(1)];
activeUsers.forEach((u) => {
u.powerLevel = 100; // set everyone to the same PL to avoid running that check
u.user.lastPresenceTs = 1000;
u.user.lastActiveAgo = 0;
u.user!.lastPresenceTs = 1000;
u.user!.lastActiveAgo = 0;
});
semiActiveUsers.forEach((u) => {
u.powerLevel = 100;
u.user.lastPresenceTs = 1000;
u.user.lastActiveAgo = 50;
u.user!.lastPresenceTs = 1000;
u.user!.lastActiveAgo = 50;
});
inactiveUsers.forEach((u) => {
u.powerLevel = 100;
u.user.lastPresenceTs = 1000;
u.user.lastActiveAgo = 100;
u.user!.lastPresenceTs = 1000;
u.user!.lastActiveAgo = 100;
});
// Bypass all the event listeners and skip to the good part
@ -294,10 +293,10 @@ describe("MemberList", () => {
// Intentionally put everyone on the same level to force a name comparison
const allUsers = [...adminUsers, ...moderatorUsers, ...defaultUsers];
allUsers.forEach((u) => {
u.user.currentlyActive = true;
u.user.presence = "online";
u.user.lastPresenceTs = 1000;
u.user.lastActiveAgo = 0;
u.user!.currentlyActive = true;
u.user!.presence = "online";
u.user!.lastPresenceTs = 1000;
u.user!.lastActiveAgo = 0;
u.powerLevel = 100;
});

View file

@ -37,13 +37,13 @@ describe("NotificationBadge", () => {
/>,
);
fireEvent.click(container.firstChild);
fireEvent.click(container.firstChild!);
expect(cb).toHaveBeenCalledTimes(1);
fireEvent.mouseEnter(container.firstChild);
fireEvent.mouseEnter(container.firstChild!);
expect(cb).toHaveBeenCalledTimes(2);
fireEvent.mouseLeave(container.firstChild);
fireEvent.mouseLeave(container.firstChild!);
expect(cb).toHaveBeenCalledTimes(3);
});

View file

@ -217,7 +217,7 @@ function createRoom(info: IRoomCreationInfo) {
const client: MatrixClient = MatrixClientPeg.get();
const roomId = "!1234567890:domain";
const userId = client.getUserId();
const userId = client.getUserId()!;
if (info.isDm) {
client.getAccountData = (eventType) => {
expect(eventType).toEqual("m.direct");
@ -231,7 +231,7 @@ function createRoom(info: IRoomCreationInfo) {
pendingEventOrdering: PendingEventOrdering.Detached,
});
const otherJoinEvents = [];
const otherJoinEvents: MatrixEvent[] = [];
for (const otherUserId of info.userIds) {
otherJoinEvents.push(mkJoinEvent(roomId, otherUserId));
}

View file

@ -88,7 +88,7 @@ describe("<SendMessageComposer/>", () => {
const documentOffset = new DocumentOffset(11, true);
model.update("hello world", "insertText", documentOffset);
const content = createMessageContent(model, null, undefined, permalinkCreator);
const content = createMessageContent(model, undefined, undefined, permalinkCreator);
expect(content).toEqual({
body: "hello world",
@ -101,7 +101,7 @@ describe("<SendMessageComposer/>", () => {
const documentOffset = new DocumentOffset(13, true);
model.update("hello *world*", "insertText", documentOffset);
const content = createMessageContent(model, null, undefined, permalinkCreator);
const content = createMessageContent(model, undefined, undefined, permalinkCreator);
expect(content).toEqual({
body: "hello *world*",
@ -116,7 +116,7 @@ describe("<SendMessageComposer/>", () => {
const documentOffset = new DocumentOffset(22, true);
model.update("/me blinks __quickly__", "insertText", documentOffset);
const content = createMessageContent(model, null, undefined, permalinkCreator);
const content = createMessageContent(model, undefined, undefined, permalinkCreator);
expect(content).toEqual({
body: "blinks __quickly__",
@ -132,7 +132,7 @@ describe("<SendMessageComposer/>", () => {
model.update("/me ✨sparkles✨", "insertText", documentOffset);
expect(model.parts.length).toEqual(4); // Emoji count as non-text
const content = createMessageContent(model, null, undefined, permalinkCreator);
const content = createMessageContent(model, undefined, undefined, permalinkCreator);
expect(content).toEqual({
body: "✨sparkles✨",
@ -146,7 +146,7 @@ describe("<SendMessageComposer/>", () => {
model.update("//dev/null is my favourite place", "insertText", documentOffset);
const content = createMessageContent(model, null, undefined, permalinkCreator);
const content = createMessageContent(model, undefined, undefined, permalinkCreator);
expect(content).toEqual({
body: "/dev/null is my favourite place",
@ -216,7 +216,7 @@ describe("<SendMessageComposer/>", () => {
// ensure the right state was persisted to localStorage
unmount();
expect(JSON.parse(localStorage.getItem(key))).toStrictEqual({
expect(JSON.parse(localStorage.getItem(key)!)).toStrictEqual({
parts: [{ type: "plain", text: "Test Text" }],
replyEventId: mockEvent.getId(),
});
@ -249,7 +249,7 @@ describe("<SendMessageComposer/>", () => {
// ensure the right state was persisted to localStorage
window.dispatchEvent(new Event("beforeunload"));
expect(JSON.parse(localStorage.getItem(key))).toStrictEqual({
expect(JSON.parse(localStorage.getItem(key)!)).toStrictEqual({
parts: [{ type: "plain", text: "Hello World" }],
});
});
@ -260,7 +260,7 @@ describe("<SendMessageComposer/>", () => {
const { container } = getComponent({ replyToEvent: mockEvent });
addTextToComposer(container, "This is a message");
fireEvent.keyDown(container.querySelector(".mx_SendMessageComposer"), { key: "Enter" });
fireEvent.keyDown(container.querySelector(".mx_SendMessageComposer")!, { key: "Enter" });
await waitFor(() => {
expect(spyDispatcher).toHaveBeenCalledWith({
@ -271,7 +271,7 @@ describe("<SendMessageComposer/>", () => {
});
expect(container.textContent).toBe("");
const str = sessionStorage.getItem(`mx_cider_history_${mockRoom.roomId}[0]`);
const str = sessionStorage.getItem(`mx_cider_history_${mockRoom.roomId}[0]`)!;
expect(JSON.parse(str)).toStrictEqual({
parts: [{ type: "plain", text: "This is a message" }],
replyEventId: mockEvent.getId(),
@ -289,7 +289,7 @@ describe("<SendMessageComposer/>", () => {
const { container } = getComponent();
addTextToComposer(container, "test message");
fireEvent.keyDown(container.querySelector(".mx_SendMessageComposer"), { key: "Enter" });
fireEvent.keyDown(container.querySelector(".mx_SendMessageComposer")!, { key: "Enter" });
expect(mockClient.sendMessage).toHaveBeenCalledWith("myfakeroom", null, {
body: "test message",

View file

@ -310,11 +310,8 @@ describe("<Notifications />", () => {
it("enables email notification when toggling on", async () => {
await getComponentAndWait();
const emailToggle = screen.getByTestId("notif-email-switch").querySelector('div[role="switch"]');
await act(async () => {
fireEvent.click(emailToggle);
});
const emailToggle = screen.getByTestId("notif-email-switch").querySelector('div[role="switch"]')!;
fireEvent.click(emailToggle);
expect(mockClient.setPusher).toHaveBeenCalledWith(
expect.objectContaining({
@ -332,11 +329,8 @@ describe("<Notifications />", () => {
mockClient.setPusher.mockRejectedValue({});
await getComponentAndWait();
const emailToggle = screen.getByTestId("notif-email-switch").querySelector('div[role="switch"]');
await act(async () => {
fireEvent.click(emailToggle);
});
const emailToggle = screen.getByTestId("notif-email-switch").querySelector('div[role="switch"]')!;
fireEvent.click(emailToggle);
// force render
await flushPromises();
@ -349,11 +343,8 @@ describe("<Notifications />", () => {
mockClient.getPushers.mockResolvedValue({ pushers: [testPusher] });
await getComponentAndWait();
const emailToggle = screen.getByTestId("notif-email-switch").querySelector('div[role="switch"]');
await act(async () => {
fireEvent.click(emailToggle);
});
const emailToggle = screen.getByTestId("notif-email-switch").querySelector('div[role="switch"]')!;
fireEvent.click(emailToggle);
expect(mockClient.setPusher).toHaveBeenCalledWith({
...testPusher,
@ -364,21 +355,19 @@ describe("<Notifications />", () => {
it("toggles and sets settings correctly", async () => {
await getComponentAndWait();
let audioNotifsToggle: HTMLDivElement;
let audioNotifsToggle!: HTMLDivElement;
const update = () => {
audioNotifsToggle = screen
.getByTestId("notif-setting-audioNotificationsEnabled")
.querySelector('div[role="switch"]');
.querySelector('div[role="switch"]')!;
};
update();
expect(audioNotifsToggle.getAttribute("aria-checked")).toEqual("true");
expect(SettingsStore.getValue("audioNotificationsEnabled")).toEqual(true);
act(() => {
fireEvent.click(audioNotifsToggle);
});
fireEvent.click(audioNotifsToggle);
update();
expect(audioNotifsToggle.getAttribute("aria-checked")).toEqual("false");
@ -422,7 +411,7 @@ describe("<Notifications />", () => {
const oneToOneRuleElement = screen.getByTestId(section + oneToOneRule.rule_id);
await act(async () => {
const offToggle = oneToOneRuleElement.querySelector('input[type="radio"]');
const offToggle = oneToOneRuleElement.querySelector('input[type="radio"]')!;
fireEvent.click(offToggle);
});

View file

@ -55,7 +55,7 @@ describe("RolesRoomSettingsTab", () => {
};
const getElementCallSwitch = (tab: RenderResult): HTMLElement => {
return tab.container.querySelector("[data-testid='element-call-switch']");
return tab.container.querySelector("[data-testid='element-call-switch']")!;
};
describe("correct state", () => {
@ -87,7 +87,7 @@ describe("RolesRoomSettingsTab", () => {
const tab = renderTab();
fireEvent.click(getElementCallSwitch(tab).querySelector(".mx_ToggleSwitch"));
fireEvent.click(getElementCallSwitch(tab).querySelector(".mx_ToggleSwitch")!);
await waitFor(() =>
expect(cli.sendStateEvent).toHaveBeenCalledWith(
room.roomId,
@ -107,7 +107,7 @@ describe("RolesRoomSettingsTab", () => {
const tab = renderTab();
fireEvent.click(getElementCallSwitch(tab).querySelector(".mx_ToggleSwitch"));
fireEvent.click(getElementCallSwitch(tab).querySelector(".mx_ToggleSwitch")!);
await waitFor(() =>
expect(cli.sendStateEvent).toHaveBeenCalledWith(
room.roomId,
@ -128,7 +128,7 @@ describe("RolesRoomSettingsTab", () => {
const tab = renderTab();
fireEvent.click(getElementCallSwitch(tab).querySelector(".mx_ToggleSwitch"));
fireEvent.click(getElementCallSwitch(tab).querySelector(".mx_ToggleSwitch")!);
await waitFor(() =>
expect(cli.sendStateEvent).toHaveBeenCalledWith(
room.roomId,

View file

@ -94,13 +94,13 @@ describe("<SpaceSettingsVisibilityTab />", () => {
const getByTestId = (container: Element, id: string) => container.querySelector(`[data-test-id=${id}]`);
const toggleGuestAccessSection = async (component: Element) => {
const toggleButton = getByTestId(component, "toggle-guest-access-btn");
const toggleButton = getByTestId(component, "toggle-guest-access-btn")!;
await act(async () => {
Simulate.click(toggleButton);
});
};
const getGuestAccessToggle = (component: Element) => component.querySelector('[aria-label="Enable guest access"');
const getHistoryVisibilityToggle = (component: Element) => component.querySelector('[aria-label="Preview Space"');
const getGuestAccessToggle = (component: Element) => component.querySelector('[aria-label="Enable guest access"]');
const getHistoryVisibilityToggle = (component: Element) => component.querySelector('[aria-label="Preview Space"]');
const getErrorMessage = (component: Element) => getByTestId(component, "space-settings-error")?.textContent;
beforeEach(() => {
@ -150,10 +150,10 @@ describe("<SpaceSettingsVisibilityTab />", () => {
await toggleGuestAccessSection(component);
const guestAccessInput = getGuestAccessToggle(component);
expect(guestAccessInput.getAttribute("aria-checked")).toEqual("true");
expect(guestAccessInput?.getAttribute("aria-checked")).toEqual("true");
await act(async () => {
Simulate.click(guestAccessInput);
Simulate.click(guestAccessInput!);
});
expect(mockMatrixClient.sendStateEvent).toHaveBeenCalledWith(
@ -165,7 +165,7 @@ describe("<SpaceSettingsVisibilityTab />", () => {
);
// toggled off
expect(guestAccessInput.getAttribute("aria-checked")).toEqual("false");
expect(guestAccessInput?.getAttribute("aria-checked")).toEqual("false");
});
it("renders error message when update fails", async () => {
@ -174,7 +174,7 @@ describe("<SpaceSettingsVisibilityTab />", () => {
const component = getComponent({ space });
await toggleGuestAccessSection(component);
await act(async () => {
Simulate.click(getGuestAccessToggle(component));
Simulate.click(getGuestAccessToggle(component)!);
});
expect(getErrorMessage(component)).toEqual("Failed to update the guest access of this space");
@ -187,7 +187,7 @@ describe("<SpaceSettingsVisibilityTab />", () => {
await toggleGuestAccessSection(component);
expect(getGuestAccessToggle(component).getAttribute("aria-disabled")).toEqual("true");
expect(getGuestAccessToggle(component)?.getAttribute("aria-disabled")).toEqual("true");
});
});
@ -197,7 +197,7 @@ describe("<SpaceSettingsVisibilityTab />", () => {
const component = getComponent({ space });
// toggle off because space settings is != WorldReadable
expect(getHistoryVisibilityToggle(component).getAttribute("aria-checked")).toEqual("false");
expect(getHistoryVisibilityToggle(component)?.getAttribute("aria-checked")).toEqual("false");
});
it("updates history visibility on toggle", async () => {
@ -205,10 +205,10 @@ describe("<SpaceSettingsVisibilityTab />", () => {
const component = getComponent({ space });
// toggle off because space settings is != WorldReadable
expect(getHistoryVisibilityToggle(component).getAttribute("aria-checked")).toEqual("false");
expect(getHistoryVisibilityToggle(component)?.getAttribute("aria-checked")).toEqual("false");
await act(async () => {
Simulate.click(getHistoryVisibilityToggle(component));
Simulate.click(getHistoryVisibilityToggle(component)!);
});
expect(mockMatrixClient.sendStateEvent).toHaveBeenCalledWith(
@ -218,7 +218,7 @@ describe("<SpaceSettingsVisibilityTab />", () => {
"",
);
expect(getHistoryVisibilityToggle(component).getAttribute("aria-checked")).toEqual("true");
expect(getHistoryVisibilityToggle(component)?.getAttribute("aria-checked")).toEqual("true");
});
it("renders error message when history update fails", async () => {
@ -227,7 +227,7 @@ describe("<SpaceSettingsVisibilityTab />", () => {
const component = getComponent({ space });
await act(async () => {
Simulate.click(getHistoryVisibilityToggle(component));
Simulate.click(getHistoryVisibilityToggle(component)!);
});
expect(getErrorMessage(component)).toEqual("Failed to update the history visibility of this space");
@ -237,7 +237,7 @@ describe("<SpaceSettingsVisibilityTab />", () => {
const space = makeMockSpace(mockMatrixClient, joinRule, guestRule, historyRule);
(space.currentState.maySendStateEvent as jest.Mock).mockReturnValue(false);
const component = getComponent({ space });
expect(getHistoryVisibilityToggle(component).getAttribute("aria-disabled")).toEqual("true");
expect(getHistoryVisibilityToggle(component)?.getAttribute("aria-disabled")).toEqual("true");
});
});

View file

@ -34,7 +34,7 @@ describe("languageHandler", function () {
const plurals = "and %(count)s others...";
const variableSub = "You are now ignoring %(userId)s";
type TestCase = [string, string, Record<string, unknown>, Record<string, unknown>, TranslatedString];
type TestCase = [string, string, Record<string, unknown>, Record<string, unknown> | undefined, TranslatedString];
const testCasesEn: TestCase[] = [
// description of the test case, translationString, variables, tags, expected result
["translates a basic string", basicString, {}, undefined, "Rooms"],
@ -82,7 +82,7 @@ describe("languageHandler", function () {
],
];
let oldNodeEnv: string;
let oldNodeEnv: string | undefined;
beforeAll(() => {
oldNodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = "test";
@ -110,7 +110,7 @@ describe("languageHandler", function () {
});
it.each(testCasesEn)("%s", (_d, translationString, variables, tags, result) => {
expect(_t(translationString, variables, tags)).toEqual(result);
expect(_t(translationString, variables, tags!)).toEqual(result);
});
it("replacements in the wrong order", function () {
@ -168,25 +168,25 @@ describe("languageHandler", function () {
describe("_t", () => {
it("translated correctly when plural string exists for count", () => {
expect(_t(lvExistingPlural, { count: 1, filename: "test.txt" }, undefined)).toEqual(
expect(_t(lvExistingPlural, { count: 1, filename: "test.txt" })).toEqual(
"Качване на test.txt и 1 друг",
);
});
it.each(pluralCases)("%s", (_d, translationString, variables, tags, result) => {
expect(_t(translationString, variables, tags)).toEqual(result);
expect(_t(translationString, variables, tags!)).toEqual(result);
});
});
describe("_tDom()", () => {
it("translated correctly when plural string exists for count", () => {
expect(_tDom(lvExistingPlural, { count: 1, filename: "test.txt" }, undefined)).toEqual(
expect(_tDom(lvExistingPlural, { count: 1, filename: "test.txt" })).toEqual(
"Качване на test.txt и 1 друг",
);
});
it.each(pluralCases)(
"%s and translates with fallback locale, attributes fallback locale",
(_d, translationString, variables, tags, result) => {
expect(_tDom(translationString, variables, tags)).toEqual(<span lang="en">{result}</span>);
expect(_tDom(translationString, variables, tags!)).toEqual(<span lang="en">{result}</span>);
},
);
});
@ -197,7 +197,7 @@ describe("languageHandler", function () {
it.each(testCasesEn)(
"%s and translates with fallback locale",
(_d, translationString, variables, tags, result) => {
expect(_t(translationString, variables, tags)).toEqual(result);
expect(_t(translationString, variables, tags!)).toEqual(result);
},
);
});
@ -206,7 +206,7 @@ describe("languageHandler", function () {
it.each(testCasesEn)(
"%s and translates with fallback locale, attributes fallback locale",
(_d, translationString, variables, tags, result) => {
expect(_tDom(translationString, variables, tags)).toEqual(<span lang="en">{result}</span>);
expect(_tDom(translationString, variables, tags!)).toEqual(<span lang="en">{result}</span>);
},
);
});
@ -216,12 +216,12 @@ describe("languageHandler", function () {
describe("when languages dont load", () => {
it("_t", () => {
const STRING_NOT_IN_THE_DICTIONARY = "a string that isn't in the translations dictionary";
expect(_t(STRING_NOT_IN_THE_DICTIONARY, {}, undefined)).toEqual(STRING_NOT_IN_THE_DICTIONARY);
expect(_t(STRING_NOT_IN_THE_DICTIONARY, {})).toEqual(STRING_NOT_IN_THE_DICTIONARY);
});
it("_tDom", () => {
const STRING_NOT_IN_THE_DICTIONARY = "a string that isn't in the translations dictionary";
expect(_tDom(STRING_NOT_IN_THE_DICTIONARY, {}, undefined)).toEqual(
expect(_tDom(STRING_NOT_IN_THE_DICTIONARY, {})).toEqual(
<span lang="en">{STRING_NOT_IN_THE_DICTIONARY}</span>,
);
});

View file

@ -383,7 +383,7 @@ describe("JitsiCall", () => {
await waitFor(
() =>
expect(
room.currentState.getStateEvents(JitsiCall.MEMBER_EVENT_TYPE, alice.userId).getContent(),
room.currentState.getStateEvents(JitsiCall.MEMBER_EVENT_TYPE, alice.userId)?.getContent(),
).toEqual({
devices: [client.getDeviceId()],
expires_ts: now1 + call.STUCK_DEVICE_TIMEOUT_MS,
@ -396,7 +396,7 @@ describe("JitsiCall", () => {
await waitFor(
() =>
expect(
room.currentState.getStateEvents(JitsiCall.MEMBER_EVENT_TYPE, alice.userId).getContent(),
room.currentState.getStateEvents(JitsiCall.MEMBER_EVENT_TYPE, alice.userId)?.getContent(),
).toEqual({
devices: [],
expires_ts: now2 + call.STUCK_DEVICE_TIMEOUT_MS,
@ -495,7 +495,7 @@ describe("JitsiCall", () => {
});
const expectDevices = (devices: IMyDevice[]) =>
expect(
room.currentState.getStateEvents(JitsiCall.MEMBER_EVENT_TYPE, alice.userId).getContent(),
room.currentState.getStateEvents(JitsiCall.MEMBER_EVENT_TYPE, alice.userId)?.getContent(),
).toEqual({
expires_ts: expect.any(Number),
devices: devices.map((d) => d.device_id),

View file

@ -37,12 +37,12 @@ function makeMatchMedia(values: any) {
}
return function matchMedia(query: string) {
return new FakeMediaQueryList(query);
return new FakeMediaQueryList(query) as unknown as MediaQueryList;
};
}
function makeGetValue(values: any) {
return function getValue<T = any>(settingName: string, _roomId: string = null, _excludeDefault = false): T {
return function getValue<T = any>(settingName: string, _roomId: string | null = null, _excludeDefault = false): T {
return values[settingName];
};
}
@ -51,7 +51,7 @@ function makeGetValueAt(values: any) {
return function getValueAt(
_level: SettingLevel,
settingName: string,
_roomId: string = null,
_roomId: string | null = null,
_explicit = false,
_excludeDefault = false,
): any {