Apply prettier formatting

This commit is contained in:
Michael Weimann 2022-12-12 12:24:14 +01:00
parent 1cac306093
commit 526645c791
No known key found for this signature in database
GPG key ID: 53F535A266BB9584
1576 changed files with 65385 additions and 62478 deletions

View file

@ -14,14 +14,14 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import React from 'react';
import React from "react";
// eslint-disable-next-line deprecate/import
import { mount, ReactWrapper } from 'enzyme';
import { act } from 'react-dom/test-utils';
import { IPassphraseInfo } from 'matrix-js-sdk/src/crypto/api';
import { mount, ReactWrapper } from "enzyme";
import { act } from "react-dom/test-utils";
import { IPassphraseInfo } from "matrix-js-sdk/src/crypto/api";
import { findByAttr, getMockClientWithEventEmitter, unmockClientPeg } from '../../../test-utils';
import { findById, flushPromises } from '../../../test-utils';
import { findByAttr, getMockClientWithEventEmitter, unmockClientPeg } from "../../../test-utils";
import { findById, flushPromises } from "../../../test-utils";
import AccessSecretStorageDialog from "../../../../src/components/views/dialogs/security/AccessSecretStorageDialog";
describe("AccessSecretStorageDialog", () => {
@ -35,12 +35,12 @@ describe("AccessSecretStorageDialog", () => {
checkPrivateKey: jest.fn(),
keyInfo: undefined,
};
const getComponent = (props ={}): ReactWrapper =>
const getComponent = (props = {}): ReactWrapper =>
mount(<AccessSecretStorageDialog {...defaultProps} {...props} />);
beforeEach(() => {
jest.clearAllMocks();
mockClient.keyBackupKeyFromRecoveryKey.mockReturnValue('a raw key' as unknown as Uint8Array);
mockClient.keyBackupKeyFromRecoveryKey.mockReturnValue("a raw key" as unknown as Uint8Array);
mockClient.isValidRecoveryKey.mockReturnValue(false);
});
@ -63,7 +63,7 @@ describe("AccessSecretStorageDialog", () => {
const e = { preventDefault: () => {} };
act(() => {
wrapper.find('form').simulate('submit', e);
wrapper.find("form").simulate("submit", e);
});
await flushPromises();
@ -75,13 +75,13 @@ describe("AccessSecretStorageDialog", () => {
it("Considers a valid key to be valid", async () => {
const checkPrivateKey = jest.fn().mockResolvedValue(true);
const wrapper = getComponent({ checkPrivateKey });
mockClient.keyBackupKeyFromRecoveryKey.mockReturnValue('a raw key' as unknown as Uint8Array);
mockClient.keyBackupKeyFromRecoveryKey.mockReturnValue("a raw key" as unknown as Uint8Array);
mockClient.checkSecretStorageKey.mockResolvedValue(true);
const v = "asdf";
const e = { target: { value: v } };
act(() => {
findById(wrapper, 'mx_securityKey').find('input').simulate('change', e);
findById(wrapper, "mx_securityKey").find("input").simulate("change", e);
wrapper.setProps({});
});
await act(async () => {
@ -91,10 +91,10 @@ describe("AccessSecretStorageDialog", () => {
wrapper.setProps({});
});
const submitButton = findByAttr('data-testid')(wrapper, 'dialog-primary-button').at(0);
const submitButton = findByAttr("data-testid")(wrapper, "dialog-primary-button").at(0);
// submit button is enabled when key is valid
expect(submitButton.props().disabled).toBeFalsy();
expect(wrapper.find('.mx_AccessSecretStorageDialog_recoveryKeyFeedback').text()).toEqual('Looks good!');
expect(wrapper.find(".mx_AccessSecretStorageDialog_recoveryKeyFeedback").text()).toEqual("Looks good!");
});
it("Notifies the user if they input an invalid Security Key", async () => {
@ -106,36 +106,36 @@ describe("AccessSecretStorageDialog", () => {
});
act(() => {
findById(wrapper, 'mx_securityKey').find('input').simulate('change', e);
findById(wrapper, "mx_securityKey").find("input").simulate("change", e);
});
// force a validation now because it debounces
// @ts-ignore private
await wrapper.instance().validateRecoveryKey();
const submitButton = findByAttr('data-testid')(wrapper, 'dialog-primary-button').at(0);
const submitButton = findByAttr("data-testid")(wrapper, "dialog-primary-button").at(0);
// submit button is disabled when recovery key is invalid
expect(submitButton.props().disabled).toBeTruthy();
expect(
wrapper.find('.mx_AccessSecretStorageDialog_recoveryKeyFeedback').text(),
).toEqual('Invalid Security Key');
expect(wrapper.find(".mx_AccessSecretStorageDialog_recoveryKeyFeedback").text()).toEqual(
"Invalid Security Key",
);
wrapper.setProps({});
const notification = wrapper.find(".mx_AccessSecretStorageDialog_recoveryKeyFeedback");
expect(notification.props().children).toEqual("Invalid Security Key");
});
it("Notifies the user if they input an invalid passphrase", async function() {
it("Notifies the user if they input an invalid passphrase", async function () {
const keyInfo = {
name: 'test',
algorithm: 'test',
iv: 'test',
mac: '1:2:3:4',
name: "test",
algorithm: "test",
iv: "test",
mac: "1:2:3:4",
passphrase: {
// this type is weird in js-sdk
// cast 'm.pbkdf2' to itself
algorithm: 'm.pbkdf2' as IPassphraseInfo['algorithm'],
algorithm: "m.pbkdf2" as IPassphraseInfo["algorithm"],
iterations: 2,
salt: 'nonempty',
salt: "nonempty",
},
};
const checkPrivateKey = jest.fn().mockResolvedValue(false);
@ -145,23 +145,24 @@ describe("AccessSecretStorageDialog", () => {
// update passphrase
act(() => {
const e = { target: { value: "a" } };
findById(wrapper, 'mx_passPhraseInput').at(1).simulate('change', e);
findById(wrapper, "mx_passPhraseInput").at(1).simulate("change", e);
});
wrapper.setProps({});
// input updated
expect(findById(wrapper, 'mx_passPhraseInput').at(0).props().value).toEqual('a');
expect(findById(wrapper, "mx_passPhraseInput").at(0).props().value).toEqual("a");
// submit the form
act(() => {
wrapper.find('form').at(0).simulate('submit');
wrapper.find("form").at(0).simulate("submit");
});
await flushPromises();
wrapper.setProps({});
const notification = wrapper.find(".mx_AccessSecretStorageDialog_keyStatus");
expect(notification.props().children).toEqual(
["\uD83D\uDC4E ", "Unable to access secret storage. Please verify that you " +
"entered the correct Security Phrase."]);
expect(notification.props().children).toEqual([
"\uD83D\uDC4E ",
"Unable to access secret storage. Please verify that you " + "entered the correct Security Phrase.",
]);
});
});

View file

@ -35,11 +35,13 @@ describe("<ChangelogDialog />", () => {
ahead_by: 24,
behind_by: 0,
total_commits: 24,
commits: [{
sha: "commit-sha",
html_url: "https://api.github.com/repos/vector-im/element-web/commit/commit-sha",
commit: { message: "This is the first commit message" },
}],
commits: [
{
sha: "commit-sha",
html_url: "https://api.github.com/repos/vector-im/element-web/commit/commit-sha",
commit: { message: "This is the first commit message" },
},
],
files: [],
});
const reactUrl = "https://riot.im/github/repos/matrix-org/matrix-react-sdk/compare/oldsha2...newsha2";
@ -55,11 +57,13 @@ describe("<ChangelogDialog />", () => {
ahead_by: 83,
behind_by: 0,
total_commits: 83,
commits: [{
sha: "commit-sha0",
html_url: "https://api.github.com/repos/matrix-org/matrix-react-sdk/commit/commit-sha",
commit: { message: "This is a commit message" },
}],
commits: [
{
sha: "commit-sha0",
html_url: "https://api.github.com/repos/matrix-org/matrix-react-sdk/commit/commit-sha",
commit: { message: "This is a commit message" },
},
],
files: [],
});
const jsUrl = "https://riot.im/github/repos/matrix-org/matrix-js-sdk/compare/oldsha3...newsha3";
@ -75,23 +79,26 @@ describe("<ChangelogDialog />", () => {
ahead_by: 48,
behind_by: 0,
total_commits: 48,
commits: [{
sha: "commit-sha1",
html_url: "https://api.github.com/repos/matrix-org/matrix-js-sdk/commit/commit-sha1",
commit: { message: "This is a commit message" },
}, {
sha: "commit-sha2",
html_url: "https://api.github.com/repos/matrix-org/matrix-js-sdk/commit/commit-sha2",
commit: { message: "This is another commit message" },
}],
commits: [
{
sha: "commit-sha1",
html_url: "https://api.github.com/repos/matrix-org/matrix-js-sdk/commit/commit-sha1",
commit: { message: "This is a commit message" },
},
{
sha: "commit-sha2",
html_url: "https://api.github.com/repos/matrix-org/matrix-js-sdk/commit/commit-sha2",
commit: { message: "This is another commit message" },
},
],
files: [],
});
const newVersion = "newsha1-react-newsha2-js-newsha3";
const oldVersion = "oldsha1-react-oldsha2-js-oldsha3";
const { asFragment } = render((
<ChangelogDialog newVersion={newVersion} version={oldVersion} onFinished={jest.fn()} />
));
const { asFragment } = render(
<ChangelogDialog newVersion={newVersion} version={oldVersion} onFinished={jest.fn()} />,
);
// Wait for spinners to go away
await waitForElementToBeRemoved(screen.getAllByRole("progressbar"));

View file

@ -14,33 +14,33 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import React from 'react';
import React from "react";
// eslint-disable-next-line deprecate/import
import { mount } from 'enzyme';
import { mocked } from 'jest-mock';
import { mount } from "enzyme";
import { mocked } from "jest-mock";
import { act } from "react-dom/test-utils";
import { Room } from 'matrix-js-sdk/src/matrix';
import { Room } from "matrix-js-sdk/src/matrix";
import ExportDialog from '../../../../src/components/views/dialogs/ExportDialog';
import { ExportType, ExportFormat } from '../../../../src/utils/exportUtils/exportUtils';
import { createTestClient, mkStubRoom } from '../../../test-utils';
import { MatrixClientPeg } from '../../../../src/MatrixClientPeg';
import ExportDialog from "../../../../src/components/views/dialogs/ExportDialog";
import { ExportType, ExportFormat } from "../../../../src/utils/exportUtils/exportUtils";
import { createTestClient, mkStubRoom } from "../../../test-utils";
import { MatrixClientPeg } from "../../../../src/MatrixClientPeg";
import HTMLExporter from "../../../../src/utils/exportUtils/HtmlExport";
import ChatExport from '../../../../src/customisations/ChatExport';
import PlainTextExporter from '../../../../src/utils/exportUtils/PlainTextExport';
import ChatExport from "../../../../src/customisations/ChatExport";
import PlainTextExporter from "../../../../src/utils/exportUtils/PlainTextExport";
jest.useFakeTimers();
const htmlExporterInstance = ({
const htmlExporterInstance = {
export: jest.fn().mockResolvedValue({}),
});
const plainTextExporterInstance = ({
};
const plainTextExporterInstance = {
export: jest.fn().mockResolvedValue({}),
});
};
jest.mock("../../../../src/utils/exportUtils/HtmlExport", () => jest.fn());
jest.mock("../../../../src/utils/exportUtils/PlainTextExport", () => jest.fn());
jest.mock('../../../../src/customisations/ChatExport', () => ({
jest.mock("../../../../src/customisations/ChatExport", () => ({
getForceChatExportParameters: jest.fn().mockReturnValue({}),
}));
@ -48,13 +48,13 @@ const ChatExportMock = mocked(ChatExport);
const HTMLExporterMock = mocked(HTMLExporter);
const PlainTextExporterMock = mocked(PlainTextExporter);
describe('<ExportDialog />', () => {
describe("<ExportDialog />", () => {
const mockClient = createTestClient();
jest.spyOn(MatrixClientPeg, 'get').mockReturnValue(mockClient);
jest.spyOn(MatrixClientPeg, "get").mockReturnValue(mockClient);
const roomId = 'test:test.org';
const roomId = "test:test.org";
const defaultProps = {
room: mkStubRoom(roomId, 'test', mockClient) as unknown as Room,
room: mkStubRoom(roomId, "test", mockClient) as unknown as Room,
onFinished: jest.fn(),
};
@ -68,32 +68,38 @@ describe('<ExportDialog />', () => {
const getPrimaryButton = (component) => component.find('[data-testid="dialog-primary-button"]');
const getSecondaryButton = (component) => component.find('[data-testid="dialog-cancel-button"]');
const submitForm = async (component) => act(async () => {
getPrimaryButton(component).simulate('click');
component.setProps({});
});
const selectExportFormat = async (component, format: ExportFormat) => act(async () => {
getExportFormatInput(component, format).simulate('change');
component.setProps({});
});
const selectExportType = async (component, type: ExportType) => act(async () => {
getExportTypeInput(component).simulate('change', { target: { value: type } });
component.setProps({});
});
const setMessageCount = async (component, count: number) => act(async () => {
getMessageCountInput(component).simulate('change', { target: { value: count } });
component.setProps({});
});
const submitForm = async (component) =>
act(async () => {
getPrimaryButton(component).simulate("click");
component.setProps({});
});
const selectExportFormat = async (component, format: ExportFormat) =>
act(async () => {
getExportFormatInput(component, format).simulate("change");
component.setProps({});
});
const selectExportType = async (component, type: ExportType) =>
act(async () => {
getExportTypeInput(component).simulate("change", { target: { value: type } });
component.setProps({});
});
const setMessageCount = async (component, count: number) =>
act(async () => {
getMessageCountInput(component).simulate("change", { target: { value: count } });
component.setProps({});
});
const setSizeLimit = async (component, limit: number) => act(async () => {
getSizeInput(component).simulate('change', { target: { value: limit } });
component.setProps({});
});
const setSizeLimit = async (component, limit: number) =>
act(async () => {
getSizeInput(component).simulate("change", { target: { value: limit } });
component.setProps({});
});
const setIncludeAttachments = async (component, checked) => act(async () => {
getAttachmentsCheckbox(component).simulate('change', { target: { checked } });
component.setProps({});
});
const setIncludeAttachments = async (component, checked) =>
act(async () => {
getAttachmentsCheckbox(component).simulate("change", { target: { checked } });
component.setProps({});
});
beforeEach(() => {
HTMLExporterMock.mockClear().mockImplementation(jest.fn().mockReturnValue(htmlExporterInstance));
@ -105,21 +111,21 @@ describe('<ExportDialog />', () => {
ChatExportMock.getForceChatExportParameters.mockClear().mockReturnValue({});
});
it('renders export dialog', () => {
it("renders export dialog", () => {
const component = getComponent();
expect(component.find('.mx_ExportDialog')).toMatchSnapshot();
expect(component.find(".mx_ExportDialog")).toMatchSnapshot();
});
it('calls onFinished when cancel button is clicked', () => {
it("calls onFinished when cancel button is clicked", () => {
const onFinished = jest.fn();
const component = getComponent({ onFinished });
act(() => {
getSecondaryButton(component).simulate('click');
getSecondaryButton(component).simulate("click");
});
expect(onFinished).toHaveBeenCalledWith(false);
});
it('exports room on submit', async () => {
it("exports room on submit", async () => {
const component = getComponent();
await submitForm(component);
@ -137,7 +143,7 @@ describe('<ExportDialog />', () => {
expect(htmlExporterInstance.export).toHaveBeenCalled();
});
it('exports room using values set from ForceRoomExportParameters', async () => {
it("exports room using values set from ForceRoomExportParameters", async () => {
ChatExportMock.getForceChatExportParameters.mockReturnValue({
format: ExportFormat.PlainText,
range: ExportType.Beginning,
@ -162,35 +168,35 @@ describe('<ExportDialog />', () => {
expect(plainTextExporterInstance.export).toHaveBeenCalled();
});
it('renders success screen when export is finished', async () => {
it("renders success screen when export is finished", async () => {
const component = getComponent();
await submitForm(component);
component.setProps({});
jest.runAllTimers();
expect(component.find('.mx_InfoDialog .mx_Dialog_content')).toMatchSnapshot();
expect(component.find(".mx_InfoDialog .mx_Dialog_content")).toMatchSnapshot();
});
describe('export format', () => {
it('renders export format with html selected by default', () => {
describe("export format", () => {
it("renders export format with html selected by default", () => {
const component = getComponent();
expect(getExportFormatInput(component, ExportFormat.Html).props().checked).toBeTruthy();
});
it('sets export format on radio button click', async () => {
it("sets export format on radio button click", async () => {
const component = getComponent();
await selectExportFormat(component, ExportFormat.PlainText);
expect(getExportFormatInput(component, ExportFormat.PlainText).props().checked).toBeTruthy();
expect(getExportFormatInput(component, ExportFormat.Html).props().checked).toBeFalsy();
});
it('hides export format input when format is valid in ForceRoomExportParameters', () => {
it("hides export format input when format is valid in ForceRoomExportParameters", () => {
const component = getComponent();
expect(getExportFormatInput(component, ExportFormat.Html).props().checked).toBeTruthy();
});
it('does not render export format when set in ForceRoomExportParameters', () => {
it("does not render export format when set in ForceRoomExportParameters", () => {
ChatExportMock.getForceChatExportParameters.mockReturnValue({
format: ExportFormat.PlainText,
});
@ -199,19 +205,19 @@ describe('<ExportDialog />', () => {
});
});
describe('export type', () => {
it('renders export type with timeline selected by default', () => {
describe("export type", () => {
it("renders export type with timeline selected by default", () => {
const component = getComponent();
expect(getExportTypeInput(component).props().value).toEqual(ExportType.Timeline);
});
it('sets export type on change', async () => {
it("sets export type on change", async () => {
const component = getComponent();
await selectExportType(component, ExportType.Beginning);
expect(getExportTypeInput(component).props().value).toEqual(ExportType.Beginning);
});
it('does not render export type when set in ForceRoomExportParameters', () => {
it("does not render export type when set in ForceRoomExportParameters", () => {
ChatExportMock.getForceChatExportParameters.mockReturnValue({
range: ExportType.Beginning,
});
@ -219,25 +225,25 @@ describe('<ExportDialog />', () => {
expect(getExportTypeInput(component).length).toBeFalsy();
});
it('does not render message count input', async () => {
it("does not render message count input", async () => {
const component = getComponent();
expect(getMessageCountInput(component).length).toBeFalsy();
});
it('renders message count input with default value 100 when export type is lastNMessages', async () => {
it("renders message count input with default value 100 when export type is lastNMessages", async () => {
const component = getComponent();
await selectExportType(component, ExportType.LastNMessages);
expect(getMessageCountInput(component).props().value).toEqual("100");
});
it('sets message count on change', async () => {
it("sets message count on change", async () => {
const component = getComponent();
await selectExportType(component, ExportType.LastNMessages);
await setMessageCount(component, 10);
expect(getMessageCountInput(component).props().value).toEqual("10");
});
it('does not export when export type is lastNMessages and message count is falsy', async () => {
it("does not export when export type is lastNMessages and message count is falsy", async () => {
const component = getComponent();
await selectExportType(component, ExportType.LastNMessages);
await setMessageCount(component, 0);
@ -246,7 +252,7 @@ describe('<ExportDialog />', () => {
expect(htmlExporterInstance.export).not.toHaveBeenCalled();
});
it('does not export when export type is lastNMessages and message count is more than max', async () => {
it("does not export when export type is lastNMessages and message count is more than max", async () => {
const component = getComponent();
await selectExportType(component, ExportType.LastNMessages);
await setMessageCount(component, 99999999999);
@ -255,7 +261,7 @@ describe('<ExportDialog />', () => {
expect(htmlExporterInstance.export).not.toHaveBeenCalled();
});
it('exports when export type is NOT lastNMessages and message count is falsy', async () => {
it("exports when export type is NOT lastNMessages and message count is falsy", async () => {
const component = getComponent();
await selectExportType(component, ExportType.LastNMessages);
await setMessageCount(component, 0);
@ -266,19 +272,19 @@ describe('<ExportDialog />', () => {
});
});
describe('size limit', () => {
it('renders size limit input with default value', () => {
describe("size limit", () => {
it("renders size limit input with default value", () => {
const component = getComponent();
expect(getSizeInput(component).props().value).toEqual("8");
});
it('updates size limit on change', async () => {
it("updates size limit on change", async () => {
const component = getComponent();
await setSizeLimit(component, 20);
expect(getSizeInput(component).props().value).toEqual("20");
});
it('does not export when size limit is falsy', async () => {
it("does not export when size limit is falsy", async () => {
const component = getComponent();
await setSizeLimit(component, 0);
await submitForm(component);
@ -286,7 +292,7 @@ describe('<ExportDialog />', () => {
expect(htmlExporterInstance.export).not.toHaveBeenCalled();
});
it('does not export when size limit is larger than max', async () => {
it("does not export when size limit is larger than max", async () => {
const component = getComponent();
await setSizeLimit(component, 2001);
await submitForm(component);
@ -294,7 +300,7 @@ describe('<ExportDialog />', () => {
expect(htmlExporterInstance.export).not.toHaveBeenCalled();
});
it('exports when size limit is max', async () => {
it("exports when size limit is max", async () => {
const component = getComponent();
await setSizeLimit(component, 2000);
await submitForm(component);
@ -302,7 +308,7 @@ describe('<ExportDialog />', () => {
expect(htmlExporterInstance.export).toHaveBeenCalled();
});
it('does not render size limit input when set in ForceRoomExportParameters', () => {
it("does not render size limit input when set in ForceRoomExportParameters", () => {
ChatExportMock.getForceChatExportParameters.mockReturnValue({
sizeMb: 10000,
});
@ -313,7 +319,7 @@ describe('<ExportDialog />', () => {
/**
* 2000mb size limit does not apply when higher limit is configured in config
*/
it('exports when size limit set in ForceRoomExportParameters is larger than 2000', async () => {
it("exports when size limit set in ForceRoomExportParameters is larger than 2000", async () => {
ChatExportMock.getForceChatExportParameters.mockReturnValue({
sizeMb: 10000,
});
@ -324,19 +330,19 @@ describe('<ExportDialog />', () => {
});
});
describe('include attachments', () => {
it('renders input with default value of false', () => {
describe("include attachments", () => {
it("renders input with default value of false", () => {
const component = getComponent();
expect(getAttachmentsCheckbox(component).props().checked).toEqual(false);
});
it('updates include attachments on change', async () => {
it("updates include attachments on change", async () => {
const component = getComponent();
await setIncludeAttachments(component, true);
expect(getAttachmentsCheckbox(component).props().checked).toEqual(true);
});
it('does not render input when set in ForceRoomExportParameters', () => {
it("does not render input when set in ForceRoomExportParameters", () => {
ChatExportMock.getForceChatExportParameters.mockReturnValue({
includeAttachments: false,
});
@ -345,4 +351,3 @@ describe('<ExportDialog />', () => {
});
});
});

View file

@ -59,22 +59,22 @@ describe("ForwardDialog", () => {
getRoom: jest.fn(),
getAccountData: jest.fn().mockReturnValue(accountDataEvent),
getPushActionsForEvent: jest.fn(),
mxcUrlToHttp: jest.fn().mockReturnValue(''),
mxcUrlToHttp: jest.fn().mockReturnValue(""),
isRoomEncrypted: jest.fn().mockReturnValue(false),
getProfileInfo: jest.fn().mockResolvedValue({
displayname: 'Alice',
displayname: "Alice",
}),
decryptEventIfNeeded: jest.fn(),
sendEvent: jest.fn(),
getClientWellKnown: jest.fn().mockReturnValue({
[TILE_SERVER_WK_KEY.name]: { map_style_url: 'maps.com' },
[TILE_SERVER_WK_KEY.name]: { map_style_url: "maps.com" },
}),
});
const defaultRooms = ["a", "A", "b"].map(name => mkStubRoom(name, name, mockClient));
const defaultRooms = ["a", "A", "b"].map((name) => mkStubRoom(name, name, mockClient));
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));
const wrapper: RenderResult = render(
<ForwardDialog
@ -96,7 +96,7 @@ describe("ForwardDialog", () => {
});
afterAll(() => {
jest.spyOn(MatrixClientPeg, 'get').mockRestore();
jest.spyOn(MatrixClientPeg, "get").mockRestore();
});
it("shows a preview with us as the sender", async () => {
@ -127,10 +127,13 @@ describe("ForwardDialog", () => {
// Make sendEvent require manual resolution so we can see the sending state
let finishSend;
let cancelSend;
mockClient.sendEvent.mockImplementation(<T extends {}>() => new Promise<T>((resolve, reject) => {
finishSend = resolve;
cancelSend = reject;
}));
mockClient.sendEvent.mockImplementation(
<T extends {}>() =>
new Promise<T>((resolve, reject) => {
finishSend = resolve;
cancelSend = reject;
}),
);
let firstButton;
let secondButton;
@ -141,28 +144,32 @@ describe("ForwardDialog", () => {
expect(firstButton.className).toContain("mx_ForwardList_canSend");
act(() => { fireEvent.click(firstButton); });
act(() => {
fireEvent.click(firstButton);
});
update();
expect(firstButton.className).toContain("mx_ForwardList_sending");
await act(async () => {
cancelSend();
// Wait one tick for the button to realize the send failed
await new Promise(resolve => setImmediate(resolve));
await new Promise((resolve) => setImmediate(resolve));
});
update();
expect(firstButton.className).toContain("mx_ForwardList_sendFailed");
expect(secondButton.className).toContain("mx_ForwardList_canSend");
act(() => { fireEvent.click(secondButton); });
act(() => {
fireEvent.click(secondButton);
});
update();
expect(secondButton.className).toContain("mx_ForwardList_sending");
await act(async () => {
finishSend();
// Wait one tick for the button to realize the send succeeded
await new Promise(resolve => setImmediate(resolve));
await new Promise((resolve) => setImmediate(resolve));
});
update();
expect(secondButton.className).toContain("mx_ForwardList_sent");
@ -203,7 +210,7 @@ describe("ForwardDialog", () => {
expect(secondButton.getAttribute("aria-disabled")).toBeFalsy();
});
describe('Location events', () => {
describe("Location events", () => {
// 14.03.2022 16:15
const now = 1647270879403;
const roomId = "a";
@ -215,11 +222,11 @@ describe("ForwardDialog", () => {
beforeEach(() => {
// legacy events will default timestamp to Date.now()
// mock a stable now for easy assertion
jest.spyOn(Date, 'now').mockReturnValue(now);
jest.spyOn(Date, "now").mockReturnValue(now);
});
afterAll(() => {
jest.spyOn(Date, 'now').mockRestore();
jest.spyOn(Date, "now").mockRestore();
});
const sendToFirstRoom = (container: HTMLElement): void =>
@ -228,7 +235,7 @@ describe("ForwardDialog", () => {
fireEvent.click(sendToFirstRoomButton!);
});
it('converts legacy location events to pin drop shares', async () => {
it("converts legacy location events to pin drop shares", async () => {
const { container } = mountForwardDialog(legacyLocationEvent);
expect(container.querySelector(".mx_MLocationBody")).toBeTruthy();
@ -250,11 +257,13 @@ describe("ForwardDialog", () => {
},
};
expect(mockClient.sendEvent).toHaveBeenCalledWith(
roomId, legacyLocationEvent.getType(), expectedStrippedContent,
roomId,
legacyLocationEvent.getType(),
expectedStrippedContent,
);
});
it('removes personal information from static self location shares', async () => {
it("removes personal information from static self location shares", async () => {
const { container } = mountForwardDialog(modernLocationEvent);
expect(container.querySelector(".mx_MLocationBody")).toBeTruthy();
@ -275,13 +284,15 @@ describe("ForwardDialog", () => {
},
};
expect(mockClient.sendEvent).toHaveBeenCalledWith(
roomId, modernLocationEvent.getType(), expectedStrippedContent,
roomId,
modernLocationEvent.getType(),
expectedStrippedContent,
);
});
it('forwards beacon location as a pin drop event', async () => {
it("forwards beacon location as a pin drop event", async () => {
const timestamp = 123456;
const beaconEvent = makeBeaconEvent('@alice:server.org', { geoUri, timestamp });
const beaconEvent = makeBeaconEvent("@alice:server.org", { geoUri, timestamp });
const text = `Location ${geoUri} at ${new Date(timestamp).toISOString()}`;
const expectedContent = {
msgtype: "m.location",
@ -301,12 +312,10 @@ describe("ForwardDialog", () => {
sendToFirstRoom(container);
expect(mockClient.sendEvent).toHaveBeenCalledWith(
roomId, EventType.RoomMessage, expectedContent,
);
expect(mockClient.sendEvent).toHaveBeenCalledWith(roomId, EventType.RoomMessage, expectedContent);
});
it('forwards pin drop event', async () => {
it("forwards pin drop event", async () => {
const { container } = mountForwardDialog(pinDropLocationEvent);
expect(container.querySelector(".mx_MLocationBody")).toBeTruthy();
@ -314,7 +323,9 @@ describe("ForwardDialog", () => {
sendToFirstRoom(container);
expect(mockClient.sendEvent).toHaveBeenCalledWith(
roomId, pinDropLocationEvent.getType(), pinDropLocationEvent.getContent(),
roomId,
pinDropLocationEvent.getType(),
pinDropLocationEvent.getContent(),
);
});
});

View file

@ -15,17 +15,17 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import React from 'react';
import { act } from 'react-dom/test-utils';
import React from "react";
import { act } from "react-dom/test-utils";
// eslint-disable-next-line deprecate/import
import { mount, ReactWrapper } from 'enzyme';
import { mount, ReactWrapper } from "enzyme";
import InteractiveAuthDialog from "../../../../src/components/views/dialogs/InteractiveAuthDialog";
import { flushPromises, getMockClientWithEventEmitter, unmockClientPeg } from '../../../test-utils';
import { flushPromises, getMockClientWithEventEmitter, unmockClientPeg } from "../../../test-utils";
describe('InteractiveAuthDialog', function() {
describe("InteractiveAuthDialog", function () {
const mockClient = getMockClientWithEventEmitter({
generateClientSecret: jest.fn().mockReturnValue('t35tcl1Ent5ECr3T'),
generateClientSecret: jest.fn().mockReturnValue("t35tcl1Ent5ECr3T"),
});
const defaultProps = {
@ -33,12 +33,9 @@ describe('InteractiveAuthDialog', function() {
makeRequest: jest.fn().mockResolvedValue(undefined),
onFinished: jest.fn(),
};
const getComponent = (props = {}) => mount(<InteractiveAuthDialog
{...defaultProps}
{...props}
/>);
const getComponent = (props = {}) => mount(<InteractiveAuthDialog {...defaultProps} {...props} />);
beforeEach(function() {
beforeEach(function () {
jest.clearAllMocks();
mockClient.credentials = null;
});
@ -49,16 +46,14 @@ describe('InteractiveAuthDialog', function() {
const getSubmitButton = (wrapper: ReactWrapper) => wrapper.find('[type="submit"]').at(0);
it('Should successfully complete a password flow', async () => {
it("Should successfully complete a password flow", async () => {
const onFinished = jest.fn();
const makeRequest = jest.fn().mockResolvedValue({ a: 1 });
mockClient.credentials = { userId: "@user:id" };
const authData = {
session: "sess",
flows: [
{ "stages": ["m.login.password"] },
],
flows: [{ stages: ["m.login.password"] }],
};
const wrapper = getComponent({ makeRequest, onFinished, authData });
@ -66,7 +61,7 @@ describe('InteractiveAuthDialog', function() {
const passwordNode = wrapper.find('input[type="password"]').at(0);
const submitNode = getSubmitButton(wrapper);
const formNode = wrapper.find('form').at(0);
const formNode = wrapper.find("form").at(0);
expect(passwordNode).toBeTruthy();
expect(submitNode).toBeTruthy();
@ -75,7 +70,7 @@ describe('InteractiveAuthDialog', function() {
// put something in the password box
act(() => {
passwordNode.simulate('change', { target: { value: "s3kr3t" } });
passwordNode.simulate("change", { target: { value: "s3kr3t" } });
wrapper.setProps({});
});
@ -84,22 +79,24 @@ describe('InteractiveAuthDialog', function() {
// hit enter; that should trigger a request
act(() => {
formNode.simulate('submit');
formNode.simulate("submit");
});
// wait for auth request to resolve
await flushPromises();
expect(makeRequest).toHaveBeenCalledTimes(1);
expect(makeRequest).toBeCalledWith(expect.objectContaining({
session: "sess",
type: "m.login.password",
password: "s3kr3t",
identifier: {
type: "m.id.user",
user: "@user:id",
},
}));
expect(makeRequest).toBeCalledWith(
expect.objectContaining({
session: "sess",
type: "m.login.password",
password: "s3kr3t",
identifier: {
type: "m.id.user",
user: "@user:id",
},
}),
);
expect(onFinished).toBeCalledTimes(1);
expect(onFinished).toBeCalledWith(true, { a: 1 });

View file

@ -28,9 +28,11 @@ import { ValidatedServerConfig } from "../../../../src/utils/ValidatedServerConf
import { IConfigOptions } from "../../../../src/IConfigOptions";
const mockGetAccessToken = jest.fn().mockResolvedValue("getAccessToken");
jest.mock("../../../../src/IdentityAuthClient", () => jest.fn().mockImplementation(() => ({
getAccessToken: mockGetAccessToken,
})));
jest.mock("../../../../src/IdentityAuthClient", () =>
jest.fn().mockImplementation(() => ({
getAccessToken: mockGetAccessToken,
})),
);
describe("InviteDialog", () => {
const roomId = "!111111111111111111:example.org";
@ -43,7 +45,7 @@ describe("InviteDialog", () => {
getRooms: jest.fn(),
getAccountData: jest.fn(),
getPushActionsForEvent: jest.fn(),
mxcUrlToHttp: jest.fn().mockReturnValue(''),
mxcUrlToHttp: jest.fn().mockReturnValue(""),
isRoomEncrypted: jest.fn().mockReturnValue(false),
getProfileInfo: jest.fn().mockRejectedValue({ errcode: "" }),
getIdentityServerUrl: jest.fn(),
@ -70,58 +72,46 @@ describe("InviteDialog", () => {
});
afterAll(() => {
jest.spyOn(MatrixClientPeg, 'get').mockRestore();
jest.spyOn(MatrixClientPeg, "get").mockRestore();
});
it("should label with space name", () => {
mockClient.getRoom(roomId).isSpaceRoom = jest.fn().mockReturnValue(true);
mockClient.getRoom(roomId).getType = jest.fn().mockReturnValue(RoomType.Space);
mockClient.getRoom(roomId).name = "Space";
render((
<InviteDialog
kind={KIND_INVITE}
roomId={roomId}
onFinished={jest.fn()}
/>
));
render(<InviteDialog kind={KIND_INVITE} roomId={roomId} onFinished={jest.fn()} />);
expect(screen.queryByText("Invite to Space")).toBeTruthy();
});
it("should label with room name", () => {
render((
<InviteDialog
kind={KIND_INVITE}
roomId={roomId}
onFinished={jest.fn()}
/>
));
render(<InviteDialog kind={KIND_INVITE} roomId={roomId} onFinished={jest.fn()} />);
expect(screen.queryByText("Invite to Room")).toBeTruthy();
});
it("should suggest valid MXIDs even if unknown", async () => {
render((
render(
<InviteDialog
kind={KIND_INVITE}
roomId={roomId}
onFinished={jest.fn()}
initialText="@localpart:server.tld"
/>
));
/>,
);
await screen.findAllByText("@localpart:server.tld"); // Using findAllByText as the MXID is used for name too
});
it("should not suggest invalid MXIDs", () => {
render((
render(
<InviteDialog
kind={KIND_INVITE}
roomId={roomId}
onFinished={jest.fn()}
initialText="@localpart:server:tld"
/>
));
/>,
);
expect(screen.queryByText("@localpart:server:tld")).toBeFalsy();
});
@ -138,14 +128,9 @@ describe("InviteDialog", () => {
avatar_url: "mxc://foo/bar",
});
render((
<InviteDialog
kind={KIND_INVITE}
roomId={roomId}
onFinished={jest.fn()}
initialText="foobar@email.com"
/>
));
render(
<InviteDialog kind={KIND_INVITE} roomId={roomId} onFinished={jest.fn()} initialText="foobar@email.com" />,
);
await screen.findByText("Mr. Foo");
await screen.findByText("@foobar:server");
@ -157,14 +142,9 @@ describe("InviteDialog", () => {
mockClient.getIdentityServerUrl.mockReturnValue("https://identity-server");
mockClient.lookupThreePid.mockResolvedValue({});
render((
<InviteDialog
kind={KIND_INVITE}
roomId={roomId}
onFinished={jest.fn()}
initialText="foobar@email.com"
/>
));
render(
<InviteDialog kind={KIND_INVITE} roomId={roomId} onFinished={jest.fn()} initialText="foobar@email.com" />,
);
await screen.findByText("foobar@email.com");
await screen.findByText("Invite by email");

View file

@ -54,16 +54,14 @@ interface MockClientOptions {
users?: IUserChunkMember[];
}
function mockClient(
{
userId = "testuser",
homeserver = "example.tld",
thirdPartyProtocols = {},
rooms = [],
members = [],
users = [],
}: MockClientOptions = {},
): MatrixClient {
function mockClient({
userId = "testuser",
homeserver = "example.tld",
thirdPartyProtocols = {},
rooms = [],
members = [],
users = [],
}: MockClientOptions = {}): MatrixClient {
stubClient();
const cli = MatrixClientPeg.get();
MatrixClientPeg.getHomeserverName = jest.fn(() => homeserver);
@ -72,13 +70,15 @@ function mockClient(
cli.getThirdpartyProtocols = jest.fn(() => Promise.resolve(thirdPartyProtocols));
cli.publicRooms = jest.fn((options) => {
const searchTerm = options?.filter?.generic_search_term?.toLowerCase();
const chunk = rooms.filter(it =>
!searchTerm ||
it.room_id.toLowerCase().includes(searchTerm) ||
it.name?.toLowerCase().includes(searchTerm) ||
sanitizeHtml(it?.topic, { allowedTags: [] }).toLowerCase().includes(searchTerm) ||
it.canonical_alias?.toLowerCase().includes(searchTerm) ||
it.aliases?.find(alias => alias.toLowerCase().includes(searchTerm)));
const chunk = rooms.filter(
(it) =>
!searchTerm ||
it.room_id.toLowerCase().includes(searchTerm) ||
it.name?.toLowerCase().includes(searchTerm) ||
sanitizeHtml(it?.topic, { allowedTags: [] }).toLowerCase().includes(searchTerm) ||
it.canonical_alias?.toLowerCase().includes(searchTerm) ||
it.aliases?.find((alias) => alias.toLowerCase().includes(searchTerm)),
);
return Promise.resolve({
chunk,
total_room_count_estimate: chunk.length,
@ -86,16 +86,19 @@ function mockClient(
});
cli.searchUserDirectory = jest.fn(({ term, limit }) => {
const searchTerm = term?.toLowerCase();
const results = users.filter(it => !searchTerm ||
it.user_id.toLowerCase().includes(searchTerm) ||
it.display_name.toLowerCase().includes(searchTerm));
const results = users.filter(
(it) =>
!searchTerm ||
it.user_id.toLowerCase().includes(searchTerm) ||
it.display_name.toLowerCase().includes(searchTerm),
);
return Promise.resolve({
results: results.slice(0, limit ?? +Infinity),
limited: limit && limit < results.length,
});
});
cli.getProfileInfo = jest.fn(async (userId) => {
const member = members.find(it => it.userId === userId);
const member = members.find((it) => it.userId === userId);
if (member) {
return Promise.resolve({
displayname: member.rawDisplayName,
@ -144,11 +147,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 initialFilter={null} onFinished={() => null} />);
await act(async () => {
await sleep(200);
});
@ -160,11 +159,7 @@ describe("Spotlight Dialog", () => {
wrapper.unmount();
});
it("with public room filter", async () => {
const wrapper = mount(
<SpotlightDialog
initialFilter={Filter.PublicRooms}
onFinished={() => null} />,
);
const wrapper = mount(<SpotlightDialog initialFilter={Filter.PublicRooms} onFinished={() => null} />);
await act(async () => {
await sleep(200);
});
@ -186,7 +181,8 @@ describe("Spotlight Dialog", () => {
<SpotlightDialog
initialFilter={Filter.People}
initialText={testPerson.display_name}
onFinished={() => null} />,
onFinished={() => null}
/>,
);
await act(async () => {
await sleep(200);
@ -208,10 +204,7 @@ describe("Spotlight Dialog", () => {
describe("should apply manually selected filter", () => {
it("with public rooms", async () => {
const wrapper = mount(
<SpotlightDialog
onFinished={() => null} />,
);
const wrapper = mount(<SpotlightDialog onFinished={() => null} />);
await act(async () => {
await sleep(1);
});
@ -234,11 +227,7 @@ describe("Spotlight Dialog", () => {
wrapper.unmount();
});
it("with people", async () => {
const wrapper = mount(
<SpotlightDialog
initialText={testPerson.display_name}
onFinished={() => null} />,
);
const wrapper = mount(<SpotlightDialog initialText={testPerson.display_name} onFinished={() => null} />);
await act(async () => {
await sleep(1);
});
@ -264,11 +253,7 @@ describe("Spotlight Dialog", () => {
describe("should allow clearing filter manually", () => {
it("with public room filter", async () => {
const wrapper = mount(
<SpotlightDialog
initialFilter={Filter.PublicRooms}
onFinished={() => null} />,
);
const wrapper = mount(<SpotlightDialog initialFilter={Filter.PublicRooms} onFinished={() => null} />);
await act(async () => {
await sleep(200);
});
@ -294,7 +279,8 @@ describe("Spotlight Dialog", () => {
<SpotlightDialog
initialFilter={Filter.People}
initialText={testPerson.display_name}
onFinished={() => null} />,
onFinished={() => null}
/>,
);
await act(async () => {
await sleep(200);
@ -323,11 +309,7 @@ describe("Spotlight Dialog", () => {
let options: ReactWrapper;
beforeAll(async () => {
wrapper = mount(
<SpotlightDialog
initialText="test23"
onFinished={() => null} />,
);
wrapper = mount(<SpotlightDialog initialText="test23" onFinished={() => null} />);
await act(async () => {
await sleep(200);
});
@ -357,7 +339,8 @@ describe("Spotlight Dialog", () => {
<SpotlightDialog
initialFilter={Filter.People}
initialText={testPerson.display_name}
onFinished={() => null} />,
onFinished={() => null}
/>,
);
await act(async () => {

View file

@ -14,30 +14,30 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import React, { ReactElement } from 'react';
import { render } from '@testing-library/react';
import { mocked } from 'jest-mock';
import React, { ReactElement } from "react";
import { render } from "@testing-library/react";
import { mocked } from "jest-mock";
import SettingsStore, { CallbackFn } from '../../../../src/settings/SettingsStore';
import SdkConfig from '../../../../src/SdkConfig';
import { UserTab } from '../../../../src/components/views/dialogs/UserTab';
import UserSettingsDialog from '../../../../src/components/views/dialogs/UserSettingsDialog';
import { IDialogProps } from '../../../../src/components/views/dialogs/IDialogProps';
import SettingsStore, { CallbackFn } from "../../../../src/settings/SettingsStore";
import SdkConfig from "../../../../src/SdkConfig";
import { UserTab } from "../../../../src/components/views/dialogs/UserTab";
import UserSettingsDialog from "../../../../src/components/views/dialogs/UserSettingsDialog";
import { IDialogProps } from "../../../../src/components/views/dialogs/IDialogProps";
import {
getMockClientWithEventEmitter,
mockClientMethodsUser,
mockClientMethodsServer,
mockPlatformPeg,
} from '../../../test-utils';
import { UIFeature } from '../../../../src/settings/UIFeature';
import { SettingLevel } from '../../../../src/settings/SettingLevel';
} from "../../../test-utils";
import { UIFeature } from "../../../../src/settings/UIFeature";
import { SettingLevel } from "../../../../src/settings/SettingLevel";
mockPlatformPeg({
supportsSpellCheckSettings: jest.fn().mockReturnValue(false),
getAppVersion: jest.fn().mockResolvedValue('1'),
getAppVersion: jest.fn().mockResolvedValue("1"),
});
jest.mock('../../../../src/settings/SettingsStore', () => ({
jest.mock("../../../../src/settings/SettingsStore", () => ({
getValue: jest.fn(),
getValueAt: jest.fn(),
canSetValue: jest.fn(),
@ -48,12 +48,12 @@ jest.mock('../../../../src/settings/SettingsStore', () => ({
getBetaInfo: jest.fn(),
}));
jest.mock('../../../../src/SdkConfig', () => ({
jest.mock("../../../../src/SdkConfig", () => ({
get: jest.fn(),
}));
describe('<UserSettingsDialog />', () => {
const userId = '@alice:server.org';
describe("<UserSettingsDialog />", () => {
const userId = "@alice:server.org";
const mockSettingsStore = mocked(SettingsStore);
const mockSdkConfig = mocked(SdkConfig);
getMockClientWithEventEmitter({
@ -62,7 +62,7 @@ describe('<UserSettingsDialog />', () => {
});
const defaultProps = { onFinished: jest.fn() };
const getComponent = (props: Partial<IDialogProps & {initialTabId?: UserTab}> = {}): ReactElement => (
const getComponent = (props: Partial<IDialogProps & { initialTabId?: UserTab }> = {}): ReactElement => (
<UserSettingsDialog {...defaultProps} {...props} />
);
@ -70,52 +70,52 @@ describe('<UserSettingsDialog />', () => {
jest.clearAllMocks();
mockSettingsStore.getValue.mockReturnValue(false);
mockSettingsStore.getFeatureSettingNames.mockReturnValue([]);
mockSdkConfig.get.mockReturnValue({ brand: 'Test' });
mockSdkConfig.get.mockReturnValue({ brand: "Test" });
});
const getActiveTabLabel = (container) => container.querySelector('.mx_TabbedView_tabLabel_active').textContent;
const getActiveTabHeading = (container) => container.querySelector('.mx_SettingsTab_heading').textContent;
const getActiveTabLabel = (container) => container.querySelector(".mx_TabbedView_tabLabel_active").textContent;
const getActiveTabHeading = (container) => container.querySelector(".mx_SettingsTab_heading").textContent;
it('should render general settings tab when no initialTabId', () => {
it("should render general settings tab when no initialTabId", () => {
const { container } = render(getComponent());
expect(getActiveTabLabel(container)).toEqual('General');
expect(getActiveTabHeading(container)).toEqual('General');
expect(getActiveTabLabel(container)).toEqual("General");
expect(getActiveTabHeading(container)).toEqual("General");
});
it('should render initial tab when initialTabId is set', () => {
it("should render initial tab when initialTabId is set", () => {
const { container } = render(getComponent({ initialTabId: UserTab.Help }));
expect(getActiveTabLabel(container)).toEqual('Help & About');
expect(getActiveTabHeading(container)).toEqual('Help & About');
expect(getActiveTabLabel(container)).toEqual("Help & About");
expect(getActiveTabHeading(container)).toEqual("Help & About");
});
it('should render general tab if initialTabId tab cannot be rendered', () => {
it("should render general tab if initialTabId tab cannot be rendered", () => {
// mjolnir tab is only rendered in some configs
const { container } = render(getComponent({ initialTabId: UserTab.Mjolnir }));
expect(getActiveTabLabel(container)).toEqual('General');
expect(getActiveTabHeading(container)).toEqual('General');
expect(getActiveTabLabel(container)).toEqual("General");
expect(getActiveTabHeading(container)).toEqual("General");
});
it('renders tabs correctly', () => {
it("renders tabs correctly", () => {
const { container } = render(getComponent());
expect(container.querySelectorAll('.mx_TabbedView_tabLabel')).toMatchSnapshot();
expect(container.querySelectorAll(".mx_TabbedView_tabLabel")).toMatchSnapshot();
});
it('renders ignored users tab when feature_mjolnir is enabled', () => {
it("renders ignored users tab when feature_mjolnir is enabled", () => {
mockSettingsStore.getValue.mockImplementation((settingName): any => settingName === "feature_mjolnir");
const { getByTestId } = render(getComponent());
expect(getByTestId(`settings-tab-${UserTab.Mjolnir}`)).toBeTruthy();
});
it('renders voip tab when voip is enabled', () => {
it("renders voip tab when voip is enabled", () => {
mockSettingsStore.getValue.mockImplementation((settingName): any => settingName === UIFeature.Voip);
const { getByTestId } = render(getComponent());
expect(getByTestId(`settings-tab-${UserTab.Voice}`)).toBeTruthy();
});
it('renders session manager tab when enabled', () => {
it("renders session manager tab when enabled", () => {
mockSettingsStore.getValue.mockImplementation((settingName): any => {
return settingName === "feature_new_device_manager";
});
@ -123,23 +123,23 @@ describe('<UserSettingsDialog />', () => {
expect(getByTestId(`settings-tab-${UserTab.SessionManager}`)).toBeTruthy();
});
it('renders labs tab when show_labs_settings is enabled in config', () => {
it("renders labs tab when show_labs_settings is enabled in config", () => {
// @ts-ignore simplified test stub
mockSdkConfig.get.mockImplementation((configName) => configName === "show_labs_settings");
const { getByTestId } = render(getComponent());
expect(getByTestId(`settings-tab-${UserTab.Labs}`)).toBeTruthy();
});
it('renders labs tab when some feature is in beta', () => {
mockSettingsStore.getFeatureSettingNames.mockReturnValue(['feature_beta_setting', 'feature_just_normal_labs']);
mockSettingsStore.getBetaInfo.mockImplementation(
(settingName) => settingName === 'feature_beta_setting' ? {} as any : undefined,
it("renders labs tab when some feature is in beta", () => {
mockSettingsStore.getFeatureSettingNames.mockReturnValue(["feature_beta_setting", "feature_just_normal_labs"]);
mockSettingsStore.getBetaInfo.mockImplementation((settingName) =>
settingName === "feature_beta_setting" ? ({} as any) : undefined,
);
const { getByTestId } = render(getComponent());
expect(getByTestId(`settings-tab-${UserTab.Labs}`)).toBeTruthy();
});
it('watches settings', () => {
it("watches settings", () => {
const watchSettingCallbacks: Record<string, CallbackFn> = {};
mockSettingsStore.watchSetting.mockImplementation((settingName, roomId, callback) => {
@ -150,17 +150,21 @@ describe('<UserSettingsDialog />', () => {
const { queryByTestId, unmount } = render(getComponent());
expect(queryByTestId(`settings-tab-${UserTab.Mjolnir}`)).toBeFalsy();
expect(mockSettingsStore.watchSetting.mock.calls[0][0]).toEqual('feature_mjolnir');
expect(mockSettingsStore.watchSetting.mock.calls[1][0]).toEqual('feature_new_device_manager');
expect(mockSettingsStore.watchSetting.mock.calls[0][0]).toEqual("feature_mjolnir");
expect(mockSettingsStore.watchSetting.mock.calls[1][0]).toEqual("feature_new_device_manager");
// call the watch setting callback
watchSettingCallbacks["feature_mjolnir"]("feature_mjolnir", '', SettingLevel.ACCOUNT, true, true);
watchSettingCallbacks["feature_mjolnir"]("feature_mjolnir", "", SettingLevel.ACCOUNT, true, true);
// tab is rendered now
expect(queryByTestId(`settings-tab-${UserTab.Mjolnir}`)).toBeTruthy();
// call the watch setting callback
watchSettingCallbacks["feature_new_device_manager"](
"feature_new_device_manager", '', SettingLevel.ACCOUNT, true, true,
"feature_new_device_manager",
"",
SettingLevel.ACCOUNT,
true,
true,
);
// tab is rendered now
expect(queryByTestId(`settings-tab-${UserTab.SessionManager}`)).toBeTruthy();
@ -168,7 +172,7 @@ describe('<UserSettingsDialog />', () => {
unmount();
// unwatches settings on unmount
expect(mockSettingsStore.unwatchSetting).toHaveBeenCalledWith('mock-watcher-id-feature_mjolnir');
expect(mockSettingsStore.unwatchSetting).toHaveBeenCalledWith('mock-watcher-id-feature_new_device_manager');
expect(mockSettingsStore.unwatchSetting).toHaveBeenCalledWith("mock-watcher-id-feature_mjolnir");
expect(mockSettingsStore.unwatchSetting).toHaveBeenCalledWith("mock-watcher-id-feature_new_device_manager");
});
});

View file

@ -22,19 +22,21 @@ import { PublicRoomResultDetails } from "../../../../../src/components/views/dia
describe("PublicRoomResultDetails", () => {
it("renders", () => {
const { asFragment } = render(<PublicRoomResultDetails
room={{
room_id: "room-id",
name: "hello?",
canonical_alias: "canonical-alias",
world_readable: true,
guest_can_join: false,
num_joined_members: 666,
}}
labelId="label-id"
descriptionId="description-id"
detailsId="details-id"
/>);
const { asFragment } = render(
<PublicRoomResultDetails
room={{
room_id: "room-id",
name: "hello?",
canonical_alias: "canonical-alias",
world_readable: true,
guest_can_join: false,
num_joined_members: 666,
}}
labelId="label-id"
descriptionId="description-id"
detailsId="details-id"
/>,
);
expect(asFragment()).toMatchSnapshot();
});
@ -57,12 +59,14 @@ describe("PublicRoomResultDetails", () => {
...partialPublicRoomChunk,
};
const { asFragment } = render(<PublicRoomResultDetails
room={roomChunk}
labelId="label-id"
descriptionId="description-id"
detailsId="details-id"
/>);
const { asFragment } = render(
<PublicRoomResultDetails
room={roomChunk}
labelId="label-id"
descriptionId="description-id"
detailsId="details-id"
/>,
);
expect(asFragment()).toMatchSnapshot();
});