Update usages of test utilities preferring RTL (#10203)

This commit is contained in:
Michael Telatynski 2023-02-22 10:52:55 +00:00 committed by GitHub
parent 17bbd4eaac
commit c29e5f18ff
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
37 changed files with 341 additions and 424 deletions

View file

@ -167,7 +167,6 @@
"@types/react": "17.0.49",
"@types/react-beautiful-dnd": "^13.0.0",
"@types/react-dom": "17.0.17",
"@types/react-test-renderer": "^17.0.1",
"@types/react-transition-group": "^4.4.0",
"@types/sanitize-html": "2.8.0",
"@types/tar-js": "^0.3.2",
@ -212,7 +211,6 @@
"postcss-scss": "^4.0.4",
"prettier": "2.8.0",
"raw-loader": "^4.0.2",
"react-test-renderer": "^17.0.2",
"rimraf": "^3.0.2",
"stylelint": "^14.9.1",
"stylelint-config-prettier": "^9.0.4",

View file

@ -399,7 +399,7 @@ export default class AliasSettings extends React.Component<IProps, IState> {
return (
<div className="mx_AliasSettings">
<SettingsFieldset
data-test-id="published-address-fieldset"
data-testid="published-address-fieldset"
legend={_t("Published Addresses")}
description={
<>
@ -450,7 +450,7 @@ export default class AliasSettings extends React.Component<IProps, IState> {
/>
</SettingsFieldset>
<SettingsFieldset
data-test-id="local-address-fieldset"
data-testid="local-address-fieldset"
legend={_t("Local Addresses")}
description={
isSpaceRoom

View file

@ -93,7 +93,7 @@ const SpaceSettingsVisibilityTab: React.FC<IProps> = ({ matrixClient: cli, space
advancedSection = (
<div>
<AccessibleButton
data-test-id="toggle-guest-access-btn"
data-testid="toggle-guest-access-btn"
onClick={toggleAdvancedSection}
kind="link"
className="mx_SettingsTab_showAdvanced"
@ -141,13 +141,13 @@ const SpaceSettingsVisibilityTab: React.FC<IProps> = ({ matrixClient: cli, space
<div className="mx_SettingsTab_heading">{_t("Visibility")}</div>
{error && (
<div data-test-id="space-settings-error" className="mx_SpaceRoomView_errorText">
<div data-testid="space-settings-error" className="mx_SpaceRoomView_errorText">
{error}
</div>
)}
<SettingsFieldset
data-test-id="access-fieldset"
data-testid="access-fieldset"
legend={_t("Access")}
description={_t("Decide who can view and join %(spaceName)s.", { spaceName: space.name })}
>

View file

@ -15,7 +15,7 @@ limitations under the License.
*/
import { EventType, MatrixClient, MatrixEvent, Room, RoomMember } from "matrix-js-sdk/src/matrix";
import TestRenderer from "react-test-renderer";
import { render } from "@testing-library/react";
import { ReactElement } from "react";
import { Mocked, mocked } from "jest-mock";
@ -46,43 +46,6 @@ function mockPinnedEvent(pinnedMessageIds?: string[], prevPinnedMessageIds?: str
});
}
// Helper function that renders a component to a plain text string.
// Once snapshots are introduced in tests, this function will no longer be necessary,
// and should be replaced with snapshots.
function renderComponent(component: TestRenderer.ReactTestRenderer): string {
const serializeObject = (
object:
| TestRenderer.ReactTestRendererJSON
| TestRenderer.ReactTestRendererJSON[]
| TestRenderer.ReactTestRendererNode
| TestRenderer.ReactTestRendererNode[],
): string => {
if (typeof object === "string") {
return object === " " ? "" : object;
}
if (Array.isArray(object) && object.length === 1 && typeof object[0] === "string") {
return object[0];
}
if (!Array.isArray(object) && object["type"] !== undefined && typeof object["children"] !== undefined) {
return serializeObject(object.children!);
}
if (!Array.isArray(object)) {
return "";
}
return object
.map((child) => {
return serializeObject(child);
})
.join("");
};
return serializeObject(component.toJSON()!);
}
describe("TextForEvent", () => {
describe("getSenderName()", () => {
it("Prefers sender.name", () => {
@ -105,71 +68,71 @@ describe("TextForEvent", () => {
it("mentions message when a single message was pinned, with no previously pinned messages", () => {
const event = mockPinnedEvent(["message-1"]);
const plainText = textForEvent(event);
const component = TestRenderer.create(textForEvent(event, true) as ReactElement);
const component = render(textForEvent(event, true) as ReactElement);
const expectedText = "@foo:example.com pinned a message to this room. See all pinned messages.";
expect(plainText).toBe(expectedText);
expect(renderComponent(component)).toBe(expectedText);
expect(component.container).toHaveTextContent(expectedText);
});
it("mentions message when a single message was pinned, with multiple previously pinned messages", () => {
const event = mockPinnedEvent(["message-1", "message-2", "message-3"], ["message-1", "message-2"]);
const plainText = textForEvent(event);
const component = TestRenderer.create(textForEvent(event, true) as ReactElement);
const component = render(textForEvent(event, true) as ReactElement);
const expectedText = "@foo:example.com pinned a message to this room. See all pinned messages.";
expect(plainText).toBe(expectedText);
expect(renderComponent(component)).toBe(expectedText);
expect(component.container).toHaveTextContent(expectedText);
});
it("mentions message when a single message was unpinned, with a single message previously pinned", () => {
const event = mockPinnedEvent([], ["message-1"]);
const plainText = textForEvent(event);
const component = TestRenderer.create(textForEvent(event, true) as ReactElement);
const component = render(textForEvent(event, true) as ReactElement);
const expectedText = "@foo:example.com unpinned a message from this room. See all pinned messages.";
expect(plainText).toBe(expectedText);
expect(renderComponent(component)).toBe(expectedText);
expect(component.container).toHaveTextContent(expectedText);
});
it("mentions message when a single message was unpinned, with multiple previously pinned messages", () => {
const event = mockPinnedEvent(["message-2"], ["message-1", "message-2"]);
const plainText = textForEvent(event);
const component = TestRenderer.create(textForEvent(event, true) as ReactElement);
const component = render(textForEvent(event, true) as ReactElement);
const expectedText = "@foo:example.com unpinned a message from this room. See all pinned messages.";
expect(plainText).toBe(expectedText);
expect(renderComponent(component)).toBe(expectedText);
expect(component.container).toHaveTextContent(expectedText);
});
it("shows generic text when multiple messages were pinned", () => {
const event = mockPinnedEvent(["message-1", "message-2", "message-3"], ["message-1"]);
const plainText = textForEvent(event);
const component = TestRenderer.create(textForEvent(event, true) as ReactElement);
const component = render(textForEvent(event, true) as ReactElement);
const expectedText = "@foo:example.com changed the pinned messages for the room.";
expect(plainText).toBe(expectedText);
expect(renderComponent(component)).toBe(expectedText);
expect(component.container).toHaveTextContent(expectedText);
});
it("shows generic text when multiple messages were unpinned", () => {
const event = mockPinnedEvent(["message-3"], ["message-1", "message-2", "message-3"]);
const plainText = textForEvent(event);
const component = TestRenderer.create(textForEvent(event, true) as ReactElement);
const component = render(textForEvent(event, true) as ReactElement);
const expectedText = "@foo:example.com changed the pinned messages for the room.";
expect(plainText).toBe(expectedText);
expect(renderComponent(component)).toBe(expectedText);
expect(component.container).toHaveTextContent(expectedText);
});
it("shows generic text when one message was pinned, and another unpinned", () => {
const event = mockPinnedEvent(["message-2"], ["message-1"]);
const plainText = textForEvent(event);
const component = TestRenderer.create(textForEvent(event, true) as ReactElement);
const component = render(textForEvent(event, true) as ReactElement);
const expectedText = "@foo:example.com changed the pinned messages for the room.";
expect(plainText).toBe(expectedText);
expect(renderComponent(component)).toBe(expectedText);
expect(component.container).toHaveTextContent(expectedText);
});
});

View file

@ -16,7 +16,6 @@ limitations under the License.
*/
import React from "react";
import ReactDOM from "react-dom";
import { EventEmitter } from "events";
import { MatrixEvent, Room, RoomMember } from "matrix-js-sdk/src/matrix";
import FakeTimers from "@sinonjs/fake-timers";
@ -358,7 +357,7 @@ describe("MessagePanel", function () {
const [rm] = container.getElementsByClassName("mx_RoomView_myReadMarker_container");
// it should follow the <li> which wraps the event tile for event 4
const eventContainer = ReactDOM.findDOMNode(tiles[4]);
const eventContainer = tiles[4];
expect(rm.previousSibling).toEqual(eventContainer);
});

View file

@ -15,8 +15,7 @@ limitations under the License.
*/
import React from "react";
import { fireEvent, render } from "@testing-library/react";
import { act } from "react-dom/test-utils";
import { act, fireEvent, render } from "@testing-library/react";
import TabbedView, { Tab, TabLocation } from "../../../src/components/structures/TabbedView";

View file

@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import { getByTestId, render, RenderResult, waitFor } from "@testing-library/react";
import { act, getByTestId, render, RenderResult, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { mocked } from "jest-mock";
import { MsgType, RelationType } from "matrix-js-sdk/src/@types/event";
@ -23,7 +23,6 @@ import { MatrixEvent } from "matrix-js-sdk/src/models/event";
import { Room } from "matrix-js-sdk/src/models/room";
import { THREAD_RELATION_TYPE } from "matrix-js-sdk/src/models/thread";
import React, { useState } from "react";
import { act } from "react-dom/test-utils";
import ThreadView from "../../../src/components/structures/ThreadView";
import MatrixClientContext from "../../../src/contexts/MatrixClientContext";

View file

@ -15,10 +15,9 @@ limitations under the License.
*/
import React from "react";
import { fireEvent, render } from "@testing-library/react";
import { act, fireEvent, render } from "@testing-library/react";
import { Beacon, RoomMember, MatrixEvent } from "matrix-js-sdk/src/matrix";
import { LocationAssetType } from "matrix-js-sdk/src/@types/location";
import { act } from "react-dom/test-utils";
import BeaconListItem from "../../../../src/components/views/beacon/BeaconListItem";
import MatrixClientContext from "../../../../src/contexts/MatrixClientContext";

View file

@ -15,9 +15,8 @@ limitations under the License.
*/
import React from "react";
import { render, screen } from "@testing-library/react";
import { act, render, screen } from "@testing-library/react";
import * as maplibregl from "maplibre-gl";
import { act } from "react-dom/test-utils";
import { Beacon, Room, RoomMember, MatrixEvent, getBeaconInfoIdentifier } from "matrix-js-sdk/src/matrix";
import BeaconMarker from "../../../../src/components/views/beacon/BeaconMarker";

View file

@ -15,8 +15,7 @@ limitations under the License.
*/
import React, { ComponentProps } from "react";
import { fireEvent, render } from "@testing-library/react";
import { act } from "react-dom/test-utils";
import { act, fireEvent, render } from "@testing-library/react";
import DialogSidebar from "../../../../src/components/views/beacon/DialogSidebar";
import MatrixClientContext from "../../../../src/contexts/MatrixClientContext";

View file

@ -16,8 +16,7 @@ limitations under the License.
import React from "react";
import { mocked } from "jest-mock";
import { fireEvent, render } from "@testing-library/react";
import { act } from "react-dom/test-utils";
import { act, fireEvent, render } from "@testing-library/react";
import { Beacon, BeaconIdentifier } from "matrix-js-sdk/src/matrix";
import LeftPanelLiveShareWarning from "../../../../src/components/views/beacon/LeftPanelLiveShareWarning";

View file

@ -15,10 +15,9 @@ limitations under the License.
*/
import React from "react";
import { act } from "react-dom/test-utils";
import { Room, PendingEventOrdering, MatrixClient, RoomMember, RoomStateEvent } from "matrix-js-sdk/src/matrix";
import { ClientWidgetApi, Widget } from "matrix-widget-api";
import { cleanup, render, screen } from "@testing-library/react";
import { act, cleanup, render, screen } from "@testing-library/react";
import { mocked, Mocked } from "jest-mock";
import { mkRoomMember, MockedCall, setupAsyncStoreWithClient, stubClient, useMockedCalls } from "../../../test-utils";

View file

@ -15,10 +15,9 @@ limitations under the License.
*/
import React from "react";
import { act } from "react-dom/test-utils";
import { Room, Beacon, BeaconEvent, getBeaconInfoIdentifier, MatrixEvent } from "matrix-js-sdk/src/matrix";
import { logger } from "matrix-js-sdk/src/logger";
import { fireEvent, getByTestId, render, screen, waitFor } from "@testing-library/react";
import { act, fireEvent, getByTestId, render, screen, waitFor } from "@testing-library/react";
import RoomLiveShareWarning from "../../../../src/components/views/beacon/RoomLiveShareWarning";
import { OwnBeaconStore, OwnBeaconStoreEvent } from "../../../../src/stores/OwnBeaconStore";

View file

@ -15,11 +15,10 @@ limitations under the License.
*/
import React from "react";
import { act } from "react-dom/test-utils";
import { MatrixEvent, EventType } from "matrix-js-sdk/src/matrix";
import { LocationAssetType, M_ASSET, M_LOCATION, M_TIMESTAMP } from "matrix-js-sdk/src/@types/location";
import { M_TEXT } from "matrix-js-sdk/src/@types/extensible_events";
import { fireEvent, getByTestId, render, RenderResult, screen } from "@testing-library/react";
import { act, fireEvent, getByTestId, render, RenderResult, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { MatrixClientPeg } from "../../../../src/MatrixClientPeg";

View file

@ -12,8 +12,8 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import { render } from "@testing-library/react";
import React from "react";
import { renderIntoDocument } from "react-dom/test-utils";
import ExternalLink from "../../../../src/components/views/elements/ExternalLink";
@ -22,15 +22,10 @@ describe("<ExternalLink />", () => {
"href": "test.com",
"onClick": jest.fn(),
"className": "myCustomClass",
"data-test-id": "test",
"data-testid": "test",
};
const getComponent = (props = {}) => {
const wrapper = renderIntoDocument<HTMLDivElement>(
<div>
<ExternalLink {...defaultProps} {...props} />
</div>,
) as HTMLDivElement;
return wrapper.children[0];
return render(<ExternalLink {...defaultProps} {...props} />);
};
it("renders link correctly", () => {
@ -39,18 +34,19 @@ describe("<ExternalLink />", () => {
react element <b>children</b>
</span>
);
expect(getComponent({ children, target: "_self", rel: "noopener" })).toMatchSnapshot();
expect(getComponent({ children, target: "_self", rel: "noopener" }).asFragment()).toMatchSnapshot();
});
it("defaults target and rel", () => {
const children = "test";
const component = getComponent({ children });
expect(component.getAttribute("rel")).toEqual("noreferrer noopener");
expect(component.getAttribute("target")).toEqual("_blank");
const { getByTestId } = getComponent({ children });
const container = getByTestId("test");
expect(container.getAttribute("rel")).toEqual("noreferrer noopener");
expect(container.getAttribute("target")).toEqual("_blank");
});
it("renders plain text link correctly", () => {
const children = "test";
expect(getComponent({ children })).toMatchSnapshot();
expect(getComponent({ children }).asFragment()).toMatchSnapshot();
});
});

View file

@ -15,8 +15,7 @@ limitations under the License.
*/
import React from "react";
import { renderIntoDocument, Simulate } from "react-dom/test-utils";
import { act } from "react-dom/test-utils";
import { act, renderIntoDocument, Simulate } from "react-dom/test-utils";
import { Alignment } from "../../../../src/components/views/elements/Tooltip";
import TooltipTarget from "../../../../src/components/views/elements/TooltipTarget";

View file

@ -1,13 +1,14 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`<ExternalLink /> renders link correctly 1`] = `
<a
<DocumentFragment>
<a
class="mx_ExternalLink myCustomClass"
data-test-id="test"
data-testid="test"
href="test.com"
rel="noopener"
target="_self"
>
>
<span>
react element
<b>
@ -17,20 +18,23 @@ exports[`<ExternalLink /> renders link correctly 1`] = `
<i
class="mx_ExternalLink_icon"
/>
</a>
</a>
</DocumentFragment>
`;
exports[`<ExternalLink /> renders plain text link correctly 1`] = `
<a
<DocumentFragment>
<a
class="mx_ExternalLink myCustomClass"
data-test-id="test"
data-testid="test"
href="test.com"
rel="noreferrer noopener"
target="_blank"
>
>
test
<i
class="mx_ExternalLink_icon"
/>
</a>
</a>
</DocumentFragment>
`;

View file

@ -15,9 +15,8 @@ limitations under the License.
*/
import React from "react";
import { fireEvent, render, RenderResult } from "@testing-library/react";
import { act, fireEvent, render, RenderResult } from "@testing-library/react";
import * as maplibregl from "maplibre-gl";
import { act } from "react-dom/test-utils";
import { RoomMember } from "matrix-js-sdk/src/models/room-member";
import { MatrixClient } from "matrix-js-sdk/src/client";
import { mocked } from "jest-mock";

View file

@ -21,8 +21,7 @@ import { MatrixClient } from "matrix-js-sdk/src/client";
import { RelationType } from "matrix-js-sdk/src/matrix";
import { logger } from "matrix-js-sdk/src/logger";
import { M_ASSET, LocationAssetType } from "matrix-js-sdk/src/@types/location";
import { act } from "react-dom/test-utils";
import { fireEvent, render, RenderResult } from "@testing-library/react";
import { act, fireEvent, render, RenderResult } from "@testing-library/react";
import * as maplibregl from "maplibre-gl";
import LocationShareMenu from "../../../../src/components/views/location/LocationShareMenu";

View file

@ -15,8 +15,7 @@ limitations under the License.
*/
import React from "react";
import { act } from "react-dom/test-utils";
import { fireEvent, getByTestId, render } from "@testing-library/react";
import { act, fireEvent, getByTestId, render } from "@testing-library/react";
import * as maplibregl from "maplibre-gl";
import { ClientEvent } from "matrix-js-sdk/src/matrix";
import { logger } from "matrix-js-sdk/src/logger";

View file

@ -15,7 +15,7 @@ limitations under the License.
*/
import React from "react";
import TestRenderer from "react-test-renderer";
import { render } from "@testing-library/react";
import { EventEmitter } from "events";
import { MatrixEvent, EventType } from "matrix-js-sdk/src/matrix";
import { CryptoEvent } from "matrix-js-sdk/src/crypto";
@ -72,29 +72,29 @@ describe("MKeyVerificationConclusion", () => {
it("shouldn't render if there's no verificationRequest", () => {
const event = new MatrixEvent({});
const renderer = TestRenderer.create(<MKeyVerificationConclusion mxEvent={event} />);
expect(renderer.toJSON()).toBeNull();
const { container } = render(<MKeyVerificationConclusion mxEvent={event} />);
expect(container).toBeEmpty();
});
it("shouldn't render if the verificationRequest is pending", () => {
const event = new MatrixEvent({});
event.verificationRequest = getMockVerificationRequest({ pending: true });
const renderer = TestRenderer.create(<MKeyVerificationConclusion mxEvent={event} />);
expect(renderer.toJSON()).toBeNull();
const { container } = render(<MKeyVerificationConclusion mxEvent={event} />);
expect(container).toBeEmpty();
});
it("shouldn't render if the event type is cancel but the request type isn't", () => {
const event = new MatrixEvent({ type: EventType.KeyVerificationCancel });
event.verificationRequest = getMockVerificationRequest({ cancelled: false });
const renderer = TestRenderer.create(<MKeyVerificationConclusion mxEvent={event} />);
expect(renderer.toJSON()).toBeNull();
const { container } = render(<MKeyVerificationConclusion mxEvent={event} />);
expect(container).toBeEmpty();
});
it("shouldn't render if the event type is done but the request type isn't", () => {
const event = new MatrixEvent({ type: "m.key.verification.done" });
event.verificationRequest = getMockVerificationRequest({ done: false });
const renderer = TestRenderer.create(<MKeyVerificationConclusion mxEvent={event} />);
expect(renderer.toJSON()).toBeNull();
const { container } = render(<MKeyVerificationConclusion mxEvent={event} />);
expect(container).toBeEmpty();
});
it("shouldn't render if the user isn't actually trusted", () => {
@ -102,8 +102,8 @@ describe("MKeyVerificationConclusion", () => {
const event = new MatrixEvent({ type: "m.key.verification.done" });
event.verificationRequest = getMockVerificationRequest({ done: true });
const renderer = TestRenderer.create(<MKeyVerificationConclusion mxEvent={event} />);
expect(renderer.toJSON()).toBeNull();
const { container } = render(<MKeyVerificationConclusion mxEvent={event} />);
expect(container).toBeEmpty();
});
it("should rerender appropriately if user trust status changes", () => {
@ -111,8 +111,8 @@ describe("MKeyVerificationConclusion", () => {
const event = new MatrixEvent({ type: "m.key.verification.done" });
event.verificationRequest = getMockVerificationRequest({ done: true, otherUserId: "@someuser:domain" });
const renderer = TestRenderer.create(<MKeyVerificationConclusion mxEvent={event} />);
expect(renderer.toJSON()).toBeNull();
const { container } = render(<MKeyVerificationConclusion mxEvent={event} />);
expect(container).toBeEmpty();
mockClient.checkUserTrust.mockReturnValue(trustworthy);
@ -122,7 +122,7 @@ describe("MKeyVerificationConclusion", () => {
"@anotheruser:domain",
new UserTrustLevel(true, true, true),
);
expect(renderer.toJSON()).toBeNull();
expect(container).toBeEmpty();
/* But when our user changes, we do rerender */
mockClient.emit(
@ -130,6 +130,6 @@ describe("MKeyVerificationConclusion", () => {
event.verificationRequest.otherUserId,
new UserTrustLevel(true, true, true),
);
expect(renderer.toJSON()).not.toBeNull();
expect(container).not.toBeEmpty();
});
});

View file

@ -18,9 +18,8 @@ import React from "react";
import { MatrixClient } from "matrix-js-sdk/src/client";
import { Room } from "matrix-js-sdk/src/matrix";
import { EventType } from "matrix-js-sdk/src/@types/event";
import { act } from "react-dom/test-utils";
import { mocked } from "jest-mock";
import { render, screen, fireEvent, RenderResult } from "@testing-library/react";
import { act, render, screen, fireEvent, RenderResult } from "@testing-library/react";
import SpaceStore from "../../../../src/stores/spaces/SpaceStore";
import { MetaSpace } from "../../../../src/stores/spaces";

View file

@ -14,8 +14,8 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import React, { ReactElement } from "react";
import ReactDOM from "react-dom";
import React from "react";
import { render } from "@testing-library/react";
import { MatrixClient } from "matrix-js-sdk/src/matrix";
import { MatrixClientPeg } from "../../../../src/MatrixClientPeg";
@ -37,16 +37,9 @@ describe("CryptographyPanel", () => {
const rendered = render(<CryptographyPanel />);
// Then it displays info about the user's session
const codes = rendered.querySelectorAll("code");
const codes = rendered.container.querySelectorAll("code");
expect(codes.length).toEqual(2);
expect(codes[0].innerHTML).toEqual(sessionId);
expect(codes[1].innerHTML).toEqual(sessionKeyFormatted);
});
});
function render(component: ReactElement<CryptographyPanel>): HTMLDivElement {
const parentDiv = document.createElement("div");
document.body.appendChild(parentDiv);
ReactDOM.render(component, parentDiv);
return parentDiv;
}

View file

@ -14,8 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import React from "react";
import { fireEvent, render } from "@testing-library/react";
import { act } from "react-dom/test-utils";
import { act, fireEvent, render } from "@testing-library/react";
import { CrossSigningInfo } from "matrix-js-sdk/src/crypto/CrossSigning";
import { DeviceInfo } from "matrix-js-sdk/src/crypto/deviceinfo";
import { sleep } from "matrix-js-sdk/src/utils";

View file

@ -25,8 +25,7 @@ import {
PushRuleActionName,
} from "matrix-js-sdk/src/matrix";
import { IThreepid, ThreepidMedium } from "matrix-js-sdk/src/@types/threepids";
import { act } from "react-dom/test-utils";
import { fireEvent, getByTestId, render, screen, waitFor } from "@testing-library/react";
import { act, fireEvent, getByTestId, render, screen, waitFor } from "@testing-library/react";
import Notifications from "../../../../src/components/views/settings/Notifications";
import SettingsStore from "../../../../src/settings/SettingsStore";

View file

@ -12,8 +12,8 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import { render } from "@testing-library/react";
import React from "react";
import { renderIntoDocument } from "react-dom/test-utils";
import SettingsFieldset from "../../../../src/components/views/settings/SettingsFieldset";
@ -21,24 +21,19 @@ describe("<SettingsFieldset />", () => {
const defaultProps = {
"legend": "Who can read history?",
"children": <div>test</div>,
"data-test-id": "test",
"data-testid": "test",
};
const getComponent = (props = {}) => {
const wrapper = renderIntoDocument<HTMLDivElement>(
<div>
<SettingsFieldset {...defaultProps} {...props} />
</div>,
) as HTMLDivElement;
return wrapper.children[0];
return render(<SettingsFieldset {...defaultProps} {...props} />);
};
it("renders fieldset without description", () => {
expect(getComponent()).toMatchSnapshot();
expect(getComponent().asFragment()).toMatchSnapshot();
});
it("renders fieldset with plain text description", () => {
const description = "Changes to who can read history.";
expect(getComponent({ description })).toMatchSnapshot();
expect(getComponent({ description }).asFragment()).toMatchSnapshot();
});
it("renders fieldset with react description", () => {
@ -48,6 +43,6 @@ describe("<SettingsFieldset />", () => {
<a href="#test">a link</a>
</>
);
expect(getComponent({ description })).toMatchSnapshot();
expect(getComponent({ description }).asFragment()).toMatchSnapshot();
});
});

View file

@ -1,10 +1,11 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`<SettingsFieldset /> renders fieldset with plain text description 1`] = `
<fieldset
<DocumentFragment>
<fieldset
class="mx_SettingsFieldset"
data-test-id="test"
>
data-testid="test"
>
<legend
class="mx_SettingsFieldset_legend"
>
@ -18,14 +19,16 @@ exports[`<SettingsFieldset /> renders fieldset with plain text description 1`] =
<div>
test
</div>
</fieldset>
</fieldset>
</DocumentFragment>
`;
exports[`<SettingsFieldset /> renders fieldset with react description 1`] = `
<fieldset
<DocumentFragment>
<fieldset
class="mx_SettingsFieldset"
data-test-id="test"
>
data-testid="test"
>
<legend
class="mx_SettingsFieldset_legend"
>
@ -46,14 +49,16 @@ exports[`<SettingsFieldset /> renders fieldset with react description 1`] = `
<div>
test
</div>
</fieldset>
</fieldset>
</DocumentFragment>
`;
exports[`<SettingsFieldset /> renders fieldset without description 1`] = `
<fieldset
<DocumentFragment>
<fieldset
class="mx_SettingsFieldset"
data-test-id="test"
>
data-testid="test"
>
<legend
class="mx_SettingsFieldset_legend"
>
@ -62,5 +67,6 @@ exports[`<SettingsFieldset /> renders fieldset without description 1`] = `
<div>
test
</div>
</fieldset>
</fieldset>
</DocumentFragment>
`;

View file

@ -15,8 +15,7 @@ limitations under the License.
*/
import React from "react";
import { fireEvent, render } from "@testing-library/react";
import { act } from "react-dom/test-utils";
import { act, fireEvent, render } from "@testing-library/react";
import CurrentDeviceSection from "../../../../../src/components/views/settings/devices/CurrentDeviceSection";
import { DeviceType } from "../../../../../src/utils/device/parseUserAgent";

View file

@ -14,9 +14,8 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import { fireEvent, render } from "@testing-library/react";
import { act, fireEvent, render } from "@testing-library/react";
import React from "react";
import { act } from "react-dom/test-utils";
import SelectableDeviceTile from "../../../../../src/components/views/settings/devices/SelectableDeviceTile";
import { DeviceType } from "../../../../../src/utils/device/parseUserAgent";

View file

@ -15,8 +15,7 @@ limitations under the License.
*/
import React from "react";
import { fireEvent, render, RenderResult } from "@testing-library/react";
import { act } from "react-dom/test-utils";
import { act, fireEvent, render, RenderResult } from "@testing-library/react";
import { DeviceInfo } from "matrix-js-sdk/src/crypto/deviceinfo";
import { logger } from "matrix-js-sdk/src/logger";
import { DeviceTrustLevel } from "matrix-js-sdk/src/crypto/CrossSigning";

View file

@ -16,8 +16,8 @@ limitations under the License.
import React from "react";
import { mocked } from "jest-mock";
import { renderIntoDocument, Simulate } from "react-dom/test-utils";
import { act } from "react-dom/test-utils";
import { act, Simulate } from "react-dom/test-utils";
import { fireEvent, render, RenderResult } from "@testing-library/react";
import { EventType, MatrixClient, Room } from "matrix-js-sdk/src/matrix";
import { GuestAccess, HistoryVisibility, JoinRule } from "matrix-js-sdk/src/@types/partials";
@ -83,25 +83,18 @@ describe("<SpaceSettingsVisibilityTab />", () => {
};
const getComponent = (props = {}) => {
const wrapper = renderIntoDocument<HTMLSpanElement>(
// wrap in element so renderIntoDocument can render functional component
<span>
<SpaceSettingsVisibilityTab {...defaultProps} {...props} />
</span>,
) as HTMLSpanElement;
return wrapper.children[0];
return render(<SpaceSettingsVisibilityTab {...defaultProps} {...props} />);
};
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")!;
await act(async () => {
Simulate.click(toggleButton);
});
const toggleGuestAccessSection = async ({ getByTestId }: RenderResult) => {
const toggleButton = getByTestId("toggle-guest-access-btn")!;
fireEvent.click(toggleButton);
};
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;
const getGuestAccessToggle = ({ container }: RenderResult) =>
container.querySelector('[aria-label="Enable guest access"]');
const getHistoryVisibilityToggle = ({ container }: RenderResult) =>
container.querySelector('[aria-label="Preview Space"]');
const getErrorMessage = ({ getByTestId }: RenderResult) => getByTestId("space-settings-error")?.textContent;
beforeEach(() => {
(mockMatrixClient.sendStateEvent as jest.Mock).mockClear().mockResolvedValue({});
@ -113,18 +106,18 @@ describe("<SpaceSettingsVisibilityTab />", () => {
});
it("renders container", () => {
const component = getComponent();
expect(component).toMatchSnapshot();
const { asFragment } = getComponent();
expect(asFragment()).toMatchSnapshot();
});
describe("for a private space", () => {
const joinRule = JoinRule.Invite;
it("does not render addresses section", () => {
const space = makeMockSpace(mockMatrixClient, joinRule);
const component = getComponent({ space });
const { queryByTestId } = getComponent({ space });
expect(getByTestId(component, "published-address-fieldset")).toBeFalsy();
expect(getByTestId(component, "local-address-fieldset")).toBeFalsy();
expect(queryByTestId("published-address-fieldset")).toBeFalsy();
expect(queryByTestId("local-address-fieldset")).toBeFalsy();
});
});
@ -152,10 +145,7 @@ describe("<SpaceSettingsVisibilityTab />", () => {
expect(guestAccessInput?.getAttribute("aria-checked")).toEqual("true");
await act(async () => {
Simulate.click(guestAccessInput!);
});
fireEvent.click(guestAccessInput!);
expect(mockMatrixClient.sendStateEvent).toHaveBeenCalledWith(
mockSpaceId,
EventType.RoomGuestAccess,
@ -200,17 +190,14 @@ describe("<SpaceSettingsVisibilityTab />", () => {
expect(getHistoryVisibilityToggle(component)?.getAttribute("aria-checked")).toEqual("false");
});
it("updates history visibility on toggle", async () => {
it("updates history visibility on toggle", () => {
const space = makeMockSpace(mockMatrixClient, joinRule, guestRule, historyRule);
const component = getComponent({ space });
// toggle off because space settings is != WorldReadable
expect(getHistoryVisibilityToggle(component)?.getAttribute("aria-checked")).toEqual("false");
await act(async () => {
Simulate.click(getHistoryVisibilityToggle(component)!);
});
fireEvent.click(getHistoryVisibilityToggle(component)!);
expect(mockMatrixClient.sendStateEvent).toHaveBeenCalledWith(
mockSpaceId,
EventType.RoomHistoryVisibility,
@ -243,10 +230,10 @@ describe("<SpaceSettingsVisibilityTab />", () => {
it("renders addresses section", () => {
const space = makeMockSpace(mockMatrixClient, joinRule, guestRule);
const component = getComponent({ space });
const { getByTestId } = getComponent({ space });
expect(getByTestId(component, "published-address-fieldset")).toBeTruthy();
expect(getByTestId(component, "local-address-fieldset")).toBeTruthy();
expect(getByTestId("published-address-fieldset")).toBeTruthy();
expect(getByTestId("local-address-fieldset")).toBeTruthy();
});
});
});

View file

@ -16,18 +16,18 @@ exports[`<SpaceSettingsVisibilityTab /> for a public space Access renders guest
`;
exports[`<SpaceSettingsVisibilityTab /> renders container 1`] = `
<div
<DocumentFragment>
<div
class="mx_SettingsTab"
>
>
<div
class="mx_SettingsTab_heading"
>
Visibility
</div>
<fieldset
class="mx_SettingsFieldset"
data-test-id="access-fieldset"
data-testid="access-fieldset"
>
<legend
class="mx_SettingsFieldset_legend"
@ -129,5 +129,6 @@ exports[`<SpaceSettingsVisibilityTab /> renders container 1`] = `
</p>
</div>
</fieldset>
</div>
</div>
</DocumentFragment>
`;

View file

@ -14,37 +14,32 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import { render } from "@testing-library/react";
import React from "react";
import { renderIntoDocument } from "react-dom/test-utils";
import Heading from "../../../../src/components/views/typography/Heading";
describe("<Heading />", () => {
const defaultProps = {
size: "h1",
children: <div>test</div>,
["data-test-id"]: "test",
className: "test",
"size": "h1",
"children": <div>test</div>,
"data-testid": "test",
"className": "test",
} as any;
const getComponent = (props = {}) => {
const wrapper = renderIntoDocument<HTMLDivElement>(
<div>
<Heading {...defaultProps} {...props} />
</div>,
) as HTMLDivElement;
return wrapper.children[0];
return render(<Heading {...defaultProps} {...props} />);
};
it("renders h1 with correct attributes", () => {
expect(getComponent({ size: "h1" })).toMatchSnapshot();
expect(getComponent({ size: "h1" }).asFragment()).toMatchSnapshot();
});
it("renders h2 with correct attributes", () => {
expect(getComponent({ size: "h2" })).toMatchSnapshot();
expect(getComponent({ size: "h2" }).asFragment()).toMatchSnapshot();
});
it("renders h3 with correct attributes", () => {
expect(getComponent({ size: "h3" })).toMatchSnapshot();
expect(getComponent({ size: "h3" }).asFragment()).toMatchSnapshot();
});
it("renders h4 with correct attributes", () => {
expect(getComponent({ size: "h4" })).toMatchSnapshot();
expect(getComponent({ size: "h4" }).asFragment()).toMatchSnapshot();
});
});

View file

@ -1,45 +1,53 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`<Heading /> renders h1 with correct attributes 1`] = `
<h1
<DocumentFragment>
<h1
class="mx_Heading_h1 test"
data-test-id="test"
>
data-testid="test"
>
<div>
test
</div>
</h1>
</h1>
</DocumentFragment>
`;
exports[`<Heading /> renders h2 with correct attributes 1`] = `
<h2
<DocumentFragment>
<h2
class="mx_Heading_h2 test"
data-test-id="test"
>
data-testid="test"
>
<div>
test
</div>
</h2>
</h2>
</DocumentFragment>
`;
exports[`<Heading /> renders h3 with correct attributes 1`] = `
<h3
<DocumentFragment>
<h3
class="mx_Heading_h3 test"
data-test-id="test"
>
data-testid="test"
>
<div>
test
</div>
</h3>
</h3>
</DocumentFragment>
`;
exports[`<Heading /> renders h4 with correct attributes 1`] = `
<h4
<DocumentFragment>
<h4
class="mx_Heading_h4 test"
data-test-id="test"
>
data-testid="test"
>
<div>
test
</div>
</h4>
</h4>
</DocumentFragment>
`;

View file

@ -16,8 +16,7 @@ limitations under the License.
import React from "react";
import { Room } from "matrix-js-sdk/src/models/room";
import { act } from "react-dom/test-utils";
import { render, screen } from "@testing-library/react";
import { act, render, screen } from "@testing-library/react";
import { useTopic } from "../src/hooks/room/useTopic";
import { mkEvent, stubClient } from "./test-utils";

View file

@ -12,7 +12,6 @@ limitations under the License.
*/
import React from "react";
import { Container } from "react-dom";
import { MatrixClient, Room, RoomMember } from "matrix-js-sdk/src/matrix";
import { render, RenderResult } from "@testing-library/react";
@ -33,7 +32,7 @@ describe("VoiceBroadcastHeader", () => {
let client: MatrixClient;
let room: Room;
const sender = new RoomMember(roomId, userId);
let container: Container;
let container: RenderResult["container"];
const renderHeader = (live: VoiceBroadcastLiveness, showBroadcast?: boolean, buffering?: boolean): RenderResult => {
return render(

View file

@ -2336,13 +2336,6 @@
hoist-non-react-statics "^3.3.0"
redux "^4.0.0"
"@types/react-test-renderer@^17.0.1":
version "17.0.2"
resolved "https://registry.yarnpkg.com/@types/react-test-renderer/-/react-test-renderer-17.0.2.tgz#5f800a39b12ac8d2a2149e7e1885215bcf4edbbf"
integrity sha512-+F1KONQTBHDBBhbHuT2GNydeMpPuviduXIVJRB7Y4nma4NR5DrTJfMMZ+jbhEHbpwL+Uqhs1WXh4KHiyrtYTPg==
dependencies:
"@types/react" "^17"
"@types/react-transition-group@^4.4.0":
version "4.4.5"
resolved "https://registry.yarnpkg.com/@types/react-transition-group/-/react-transition-group-4.4.5.tgz#aae20dcf773c5aa275d5b9f7cdbca638abc5e416"
@ -7494,7 +7487,7 @@ react-shallow-renderer@^16.13.1:
object-assign "^4.1.1"
react-is "^16.12.0 || ^17.0.0 || ^18.0.0"
react-test-renderer@^17.0.0, react-test-renderer@^17.0.2:
react-test-renderer@^17.0.0:
version "17.0.2"
resolved "https://registry.yarnpkg.com/react-test-renderer/-/react-test-renderer-17.0.2.tgz#4cd4ae5ef1ad5670fc0ef776e8cc7e1231d9866c"
integrity sha512-yaQ9cB89c17PUb0x6UfWRs7kQCorVdHlutU1boVPEsB8IDZH6n9tHxMacc3y0JoXOJUsZb/t/Mb8FUWMKaM7iQ==