Migrate Enzyme to RTL (#9842)

pull/28788/head^2
Germain 2022-12-29 15:35:19 +00:00 committed by GitHub
parent 6d2d13fdee
commit 1e8b59ea40
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 234 additions and 227 deletions

View File

@ -103,7 +103,7 @@ const RoomLiveShareWarningInner: React.FC<RoomLiveShareWarningInnerProps> = ({ l
<AccessibleButton <AccessibleButton
className="mx_RoomLiveShareWarning_stopButton" className="mx_RoomLiveShareWarning_stopButton"
data-test-id="room-live-share-primary-button" data-testid="room-live-share-primary-button"
onClick={stopPropagationWrapper(onButtonClick)} onClick={stopPropagationWrapper(onButtonClick)}
kind="danger" kind="danger"
element="button" element="button"
@ -113,7 +113,7 @@ const RoomLiveShareWarningInner: React.FC<RoomLiveShareWarningInnerProps> = ({ l
</AccessibleButton> </AccessibleButton>
{hasLocationPublishError && ( {hasLocationPublishError && (
<AccessibleButton <AccessibleButton
data-test-id="room-live-share-wire-error-close-button" data-testid="room-live-share-wire-error-close-button"
title={_t("Stop and close")} title={_t("Stop and close")}
element="button" element="button"
className="mx_RoomLiveShareWarning_closeButton" className="mx_RoomLiveShareWarning_closeButton"

View File

@ -16,16 +16,14 @@ limitations under the License.
import React from "react"; import React from "react";
import { act } from "react-dom/test-utils"; import { act } from "react-dom/test-utils";
// eslint-disable-next-line deprecate/import import { Room, Beacon, BeaconEvent, getBeaconInfoIdentifier, MatrixEvent } from "matrix-js-sdk/src/matrix";
import { mount } from "enzyme";
import { Room, Beacon, BeaconEvent, getBeaconInfoIdentifier } from "matrix-js-sdk/src/matrix";
import { logger } from "matrix-js-sdk/src/logger"; import { logger } from "matrix-js-sdk/src/logger";
import { fireEvent, getByTestId, render, screen, waitFor } from "@testing-library/react";
import RoomLiveShareWarning from "../../../../src/components/views/beacon/RoomLiveShareWarning"; import RoomLiveShareWarning from "../../../../src/components/views/beacon/RoomLiveShareWarning";
import { OwnBeaconStore, OwnBeaconStoreEvent } from "../../../../src/stores/OwnBeaconStore"; import { OwnBeaconStore, OwnBeaconStoreEvent } from "../../../../src/stores/OwnBeaconStore";
import { import {
advanceDateAndTime, advanceDateAndTime,
findByTestId,
flushPromisesWithFakeTimers, flushPromisesWithFakeTimers,
getMockClientWithEventEmitter, getMockClientWithEventEmitter,
makeBeaconInfoEvent, makeBeaconInfoEvent,
@ -70,7 +68,7 @@ describe("<RoomLiveShareWarning />", () => {
// make fresh rooms every time // make fresh rooms every time
// as we update room state // as we update room state
const makeRoomsWithStateEvents = (stateEvents = []): [Room, Room] => { const makeRoomsWithStateEvents = (stateEvents: MatrixEvent[] = []): [Room, Room] => {
const room1 = new Room(room1Id, mockClient, aliceId); const room1 = new Room(room1Id, mockClient, aliceId);
const room2 = new Room(room2Id, mockClient, aliceId); const room2 = new Room(room2Id, mockClient, aliceId);
@ -92,13 +90,7 @@ describe("<RoomLiveShareWarning />", () => {
roomId: room1Id, roomId: room1Id,
}; };
const getComponent = (props = {}) => { const getComponent = (props = {}) => {
let component; return render(<RoomLiveShareWarning {...defaultProps} {...props} />);
// component updates on render
// wrap in act
act(() => {
component = mount(<RoomLiveShareWarning {...defaultProps} {...props} />);
});
return component;
}; };
const localStorageSpy = jest.spyOn(localStorage.__proto__, "getItem").mockReturnValue(undefined); const localStorageSpy = jest.spyOn(localStorage.__proto__, "getItem").mockReturnValue(undefined);
@ -125,12 +117,10 @@ describe("<RoomLiveShareWarning />", () => {
jest.spyOn(defaultDispatcher, "dispatch").mockRestore(); jest.spyOn(defaultDispatcher, "dispatch").mockRestore();
}); });
const getExpiryText = (wrapper) => findByTestId(wrapper, "room-live-share-expiry").text();
it("renders nothing when user has no live beacons at all", async () => { it("renders nothing when user has no live beacons at all", async () => {
await makeOwnBeaconStore(); await makeOwnBeaconStore();
const component = getComponent(); const { asFragment } = getComponent();
expect(component.html()).toBe(null); expect(asFragment()).toMatchInlineSnapshot(`<DocumentFragment />`);
}); });
it("renders nothing when user has no live beacons in room", async () => { it("renders nothing when user has no live beacons in room", async () => {
@ -138,8 +128,8 @@ describe("<RoomLiveShareWarning />", () => {
await makeRoomsWithStateEvents([room2Beacon1]); await makeRoomsWithStateEvents([room2Beacon1]);
await makeOwnBeaconStore(); await makeOwnBeaconStore();
}); });
const component = getComponent({ roomId: room1Id }); const { asFragment } = getComponent({ roomId: room1Id });
expect(component.html()).toBe(null); expect(asFragment()).toMatchInlineSnapshot(`<DocumentFragment />`);
}); });
it("does not render when geolocation is not working", async () => { it("does not render when geolocation is not working", async () => {
@ -150,13 +140,10 @@ describe("<RoomLiveShareWarning />", () => {
await makeRoomsWithStateEvents([room1Beacon1, room2Beacon1, room2Beacon2]); await makeRoomsWithStateEvents([room1Beacon1, room2Beacon1, room2Beacon2]);
await makeOwnBeaconStore(); await makeOwnBeaconStore();
}); });
const component = getComponent({ roomId: room1Id }); const { asFragment } = getComponent({ roomId: room1Id });
// beacons have generated ids that break snapshots expect(asFragment()).toMatchInlineSnapshot(`<DocumentFragment />`);
// assert on html
expect(component.html()).toBeNull();
}); });
describe("when user has live beacons and geolocation is available", () => { describe("when user has live beacons and geolocation is available", () => {
beforeEach(async () => { beforeEach(async () => {
await act(async () => { await act(async () => {
@ -166,25 +153,25 @@ describe("<RoomLiveShareWarning />", () => {
}); });
it("renders correctly with one live beacon in room", () => { it("renders correctly with one live beacon in room", () => {
const component = getComponent({ roomId: room1Id }); const { asFragment } = getComponent({ roomId: room1Id });
// beacons have generated ids that break snapshots // beacons have generated ids that break snapshots
// assert on html // assert on html
expect(component.html()).toMatchSnapshot(); expect(asFragment()).toMatchSnapshot();
}); });
it("renders correctly with two live beacons in room", () => { it("renders correctly with two live beacons in room", () => {
const component = getComponent({ roomId: room2Id }); const { asFragment, container } = getComponent({ roomId: room2Id });
// beacons have generated ids that break snapshots // beacons have generated ids that break snapshots
// assert on html // assert on html
expect(component.html()).toMatchSnapshot(); expect(asFragment()).toMatchSnapshot();
// later expiry displayed // later expiry displayed
expect(getExpiryText(component)).toEqual("12h left"); expect(container).toHaveTextContent("12h left");
}); });
it("removes itself when user stops having live beacons", async () => { it("removes itself when user stops having live beacons", async () => {
const component = getComponent({ roomId: room1Id }); const { container } = getComponent({ roomId: room1Id });
// started out rendered // started out rendered
expect(component.html()).toBeTruthy(); expect(container.firstChild).toBeTruthy();
// time travel until room1Beacon1 is expired // time travel until room1Beacon1 is expired
act(() => { act(() => {
@ -192,57 +179,51 @@ describe("<RoomLiveShareWarning />", () => {
}); });
act(() => { act(() => {
mockClient.emit(BeaconEvent.LivenessChange, false, new Beacon(room1Beacon1)); mockClient.emit(BeaconEvent.LivenessChange, false, new Beacon(room1Beacon1));
component.setProps({});
}); });
expect(component.html()).toBe(null); await waitFor(() => expect(container.firstChild).toBeFalsy());
}); });
it("removes itself when user stops monitoring live position", async () => { it("removes itself when user stops monitoring live position", async () => {
const component = getComponent({ roomId: room1Id }); const { container } = getComponent({ roomId: room1Id });
// started out rendered // started out rendered
expect(component.html()).toBeTruthy(); expect(container.firstChild).toBeTruthy();
act(() => { act(() => {
// cheat to clear this // cheat to clear this
// @ts-ignore // @ts-ignore
OwnBeaconStore.instance.clearPositionWatch = undefined; OwnBeaconStore.instance.clearPositionWatch = undefined;
OwnBeaconStore.instance.emit(OwnBeaconStoreEvent.MonitoringLivePosition); OwnBeaconStore.instance.emit(OwnBeaconStoreEvent.MonitoringLivePosition);
component.setProps({});
}); });
expect(component.html()).toBe(null); await waitFor(() => expect(container.firstChild).toBeFalsy());
}); });
it("renders when user adds a live beacon", async () => { it("renders when user adds a live beacon", async () => {
const component = getComponent({ roomId: room3Id }); const { container } = getComponent({ roomId: room3Id });
// started out not rendered // started out not rendered
expect(component.html()).toBeFalsy(); expect(container.firstChild).toBeFalsy();
act(() => { act(() => {
mockClient.emit(BeaconEvent.New, room3Beacon1, new Beacon(room3Beacon1)); mockClient.emit(BeaconEvent.New, room3Beacon1, new Beacon(room3Beacon1));
component.setProps({});
}); });
expect(component.html()).toBeTruthy(); await waitFor(() => expect(container.firstChild).toBeTruthy());
}); });
it("updates beacon time left periodically", () => { it("updates beacon time left periodically", () => {
const component = getComponent({ roomId: room1Id }); const { container } = getComponent({ roomId: room1Id });
expect(getExpiryText(component)).toEqual("1h left"); expect(container).toHaveTextContent("1h left");
act(() => { act(() => {
advanceDateAndTime(MINUTE_MS * 25); advanceDateAndTime(MINUTE_MS * 25);
}); });
expect(getExpiryText(component)).toEqual("35m left"); expect(container).toHaveTextContent("35m left");
}); });
it("updates beacon time left when beacon updates", () => { it("updates beacon time left when beacon updates", () => {
const component = getComponent({ roomId: room1Id }); const { container } = getComponent({ roomId: room1Id });
expect(getExpiryText(component)).toEqual("1h left"); expect(container).toHaveTextContent("1h left");
expect(getExpiryText(component)).toEqual("1h left");
act(() => { act(() => {
const beacon = OwnBeaconStore.instance.getBeaconById(getBeaconInfoIdentifier(room1Beacon1)); const beacon = OwnBeaconStore.instance.getBeaconById(getBeaconInfoIdentifier(room1Beacon1));
@ -255,31 +236,29 @@ describe("<RoomLiveShareWarning />", () => {
}, },
"$0", "$0",
); );
beacon.update(room1Beacon1Update); beacon?.update(room1Beacon1Update);
}); });
// update to expiry of new beacon // update to expiry of new beacon
expect(getExpiryText(component)).toEqual("3h left"); expect(container).toHaveTextContent("3h left");
}); });
it("clears expiry time interval on unmount", () => { it("clears expiry time interval on unmount", () => {
const clearIntervalSpy = jest.spyOn(global, "clearInterval"); const clearIntervalSpy = jest.spyOn(global, "clearInterval");
const component = getComponent({ roomId: room1Id }); const { container, unmount } = getComponent({ roomId: room1Id });
expect(getExpiryText(component)).toEqual("1h left"); expect(container).toHaveTextContent("1h left");
act(() => { unmount();
component.unmount();
});
expect(clearIntervalSpy).toHaveBeenCalled(); expect(clearIntervalSpy).toHaveBeenCalled();
}); });
it("navigates to beacon tile on click", () => { it("navigates to beacon tile on click", () => {
const dispatcherSpy = jest.spyOn(defaultDispatcher, "dispatch"); const dispatcherSpy = jest.spyOn(defaultDispatcher, "dispatch");
const component = getComponent({ roomId: room1Id }); const { container } = getComponent({ roomId: room1Id });
act(() => { act(() => {
component.simulate("click"); fireEvent.click(container.firstChild! as Node);
}); });
expect(dispatcherSpy).toHaveBeenCalledWith({ expect(dispatcherSpy).toHaveBeenCalledWith({
@ -293,21 +272,23 @@ describe("<RoomLiveShareWarning />", () => {
}); });
describe("stopping beacons", () => { describe("stopping beacons", () => {
it("stops beacon on stop sharing click", () => { it("stops beacon on stop sharing click", async () => {
const component = getComponent({ roomId: room2Id }); const { container } = getComponent({ roomId: room2Id });
act(() => { const btn = getByTestId(container, "room-live-share-primary-button");
findByTestId(component, "room-live-share-primary-button").at(0).simulate("click");
component.setProps({}); fireEvent.click(btn);
});
expect(mockClient.unstable_setLiveBeacon).toHaveBeenCalled(); expect(mockClient.unstable_setLiveBeacon).toHaveBeenCalled();
expect(component.find("Spinner").length).toBeTruthy();
expect(findByTestId(component, "room-live-share-primary-button").at(0).props().disabled).toBeTruthy(); await waitFor(() => expect(screen.queryByTestId("spinner")).toBeInTheDocument());
expect(btn.hasAttribute("disabled")).toBe(true);
}); });
it("displays error when stop sharing fails", async () => { it("displays error when stop sharing fails", async () => {
const component = getComponent({ roomId: room1Id }); const { container, asFragment } = getComponent({ roomId: room1Id });
const btn = getByTestId(container, "room-live-share-primary-button");
// fail first time // fail first time
mockClient.unstable_setLiveBeacon mockClient.unstable_setLiveBeacon
@ -315,16 +296,14 @@ describe("<RoomLiveShareWarning />", () => {
.mockResolvedValue({ event_id: "1" }); .mockResolvedValue({ event_id: "1" });
await act(async () => { await act(async () => {
findByTestId(component, "room-live-share-primary-button").at(0).simulate("click"); fireEvent.click(btn);
await flushPromisesWithFakeTimers(); await flushPromisesWithFakeTimers();
}); });
component.setProps({});
expect(component.html()).toMatchSnapshot(); expect(asFragment()).toMatchSnapshot();
act(() => { act(() => {
findByTestId(component, "room-live-share-primary-button").at(0).simulate("click"); fireEvent.click(btn);
component.setProps({});
}); });
expect(mockClient.unstable_setLiveBeacon).toHaveBeenCalledTimes(2); expect(mockClient.unstable_setLiveBeacon).toHaveBeenCalledTimes(2);
@ -332,11 +311,12 @@ describe("<RoomLiveShareWarning />", () => {
it("displays again with correct state after stopping a beacon", () => { it("displays again with correct state after stopping a beacon", () => {
// make sure the loading state is reset correctly after removing a beacon // make sure the loading state is reset correctly after removing a beacon
const component = getComponent({ roomId: room1Id }); const { container } = getComponent({ roomId: room1Id });
const btn = getByTestId(container, "room-live-share-primary-button");
// stop the beacon // stop the beacon
act(() => { act(() => {
findByTestId(component, "room-live-share-primary-button").at(0).simulate("click"); fireEvent.click(btn);
}); });
// time travel until room1Beacon1 is expired // time travel until room1Beacon1 is expired
act(() => { act(() => {
@ -352,8 +332,7 @@ describe("<RoomLiveShareWarning />", () => {
}); });
// button not disabled and expiry time shown // button not disabled and expiry time shown
expect(findByTestId(component, "room-live-share-primary-button").at(0).props().disabled).toBeFalsy(); expect(btn.hasAttribute("disabled")).toBe(true);
expect(findByTestId(component, "room-live-share-expiry").text()).toEqual("1h left");
}); });
}); });
@ -362,9 +341,9 @@ describe("<RoomLiveShareWarning />", () => {
const locationPublishErrorSpy = jest const locationPublishErrorSpy = jest
.spyOn(OwnBeaconStore.instance, "beaconHasLocationPublishError") .spyOn(OwnBeaconStore.instance, "beaconHasLocationPublishError")
.mockReturnValue(true); .mockReturnValue(true);
const component = getComponent({ roomId: room2Id }); const { asFragment } = getComponent({ roomId: room2Id });
expect(component).toMatchSnapshot(); expect(asFragment()).toMatchSnapshot();
expect(locationPublishErrorSpy).toHaveBeenCalledWith(getBeaconInfoIdentifier(room2Beacon1), 0, [ expect(locationPublishErrorSpy).toHaveBeenCalledWith(getBeaconInfoIdentifier(room2Beacon1), 0, [
getBeaconInfoIdentifier(room2Beacon1), getBeaconInfoIdentifier(room2Beacon1),
]); ]);
@ -377,7 +356,7 @@ describe("<RoomLiveShareWarning />", () => {
const locationPublishErrorSpy = jest const locationPublishErrorSpy = jest
.spyOn(OwnBeaconStore.instance, "beaconHasLocationPublishError") .spyOn(OwnBeaconStore.instance, "beaconHasLocationPublishError")
.mockReturnValue(false); .mockReturnValue(false);
const component = getComponent({ roomId: room2Id }); const { container } = getComponent({ roomId: room2Id });
// update mock and emit event // update mock and emit event
act(() => { act(() => {
@ -387,13 +366,13 @@ describe("<RoomLiveShareWarning />", () => {
getBeaconInfoIdentifier(room2Beacon1), getBeaconInfoIdentifier(room2Beacon1),
); );
}); });
component.setProps({});
// renders wire error ui // renders wire error ui
expect(component.find(".mx_RoomLiveShareWarning_label").text()).toEqual( expect(container).toHaveTextContent(
"An error occurred whilst sharing your live location, please try again", "An error occurred whilst sharing your live location, please try again",
); );
expect(findByTestId(component, "room-live-share-wire-error-close-button").length).toBeTruthy();
expect(screen.queryByTestId("room-live-share-wire-error-close-button")).toBeInTheDocument();
}, },
); );
@ -401,7 +380,7 @@ describe("<RoomLiveShareWarning />", () => {
const locationPublishErrorSpy = jest const locationPublishErrorSpy = jest
.spyOn(OwnBeaconStore.instance, "beaconHasLocationPublishError") .spyOn(OwnBeaconStore.instance, "beaconHasLocationPublishError")
.mockReturnValue(true); .mockReturnValue(true);
const component = getComponent({ roomId: room2Id }); const { container } = getComponent({ roomId: room2Id });
// update mock and emit event // update mock and emit event
act(() => { act(() => {
@ -411,23 +390,21 @@ describe("<RoomLiveShareWarning />", () => {
getBeaconInfoIdentifier(room2Beacon1), getBeaconInfoIdentifier(room2Beacon1),
); );
}); });
component.setProps({});
// renders error-free ui // renders error-free ui
expect(component.find(".mx_RoomLiveShareWarning_label").text()).toEqual( expect(container).toHaveTextContent("You are sharing your live location");
"You are sharing your live location", expect(screen.queryByTestId("room-live-share-wire-error-close-button")).not.toBeInTheDocument();
);
expect(findByTestId(component, "room-live-share-wire-error-close-button").length).toBeFalsy();
}); });
it("clicking retry button resets location publish errors", async () => { it("clicking retry button resets location publish errors", async () => {
jest.spyOn(OwnBeaconStore.instance, "beaconHasLocationPublishError").mockReturnValue(true); jest.spyOn(OwnBeaconStore.instance, "beaconHasLocationPublishError").mockReturnValue(true);
const resetErrorSpy = jest.spyOn(OwnBeaconStore.instance, "resetLocationPublishError"); const resetErrorSpy = jest.spyOn(OwnBeaconStore.instance, "resetLocationPublishError");
const component = getComponent({ roomId: room2Id }); const { container } = getComponent({ roomId: room2Id });
const btn = getByTestId(container, "room-live-share-primary-button");
act(() => { act(() => {
findByTestId(component, "room-live-share-primary-button").at(0).simulate("click"); fireEvent.click(btn);
}); });
expect(resetErrorSpy).toHaveBeenCalledWith(getBeaconInfoIdentifier(room2Beacon1)); expect(resetErrorSpy).toHaveBeenCalledWith(getBeaconInfoIdentifier(room2Beacon1));
@ -437,10 +414,10 @@ describe("<RoomLiveShareWarning />", () => {
jest.spyOn(OwnBeaconStore.instance, "beaconHasLocationPublishError").mockReturnValue(true); jest.spyOn(OwnBeaconStore.instance, "beaconHasLocationPublishError").mockReturnValue(true);
const stopBeaconSpy = jest.spyOn(OwnBeaconStore.instance, "stopBeacon"); const stopBeaconSpy = jest.spyOn(OwnBeaconStore.instance, "stopBeacon");
const component = getComponent({ roomId: room2Id }); const { container } = getComponent({ roomId: room2Id });
const btn = getByTestId(container, "room-live-share-wire-error-close-button");
act(() => { act(() => {
findByTestId(component, "room-live-share-wire-error-close-button").at(0).simulate("click"); fireEvent.click(btn);
}); });
expect(stopBeaconSpy).toHaveBeenCalledWith(getBeaconInfoIdentifier(room2Beacon1)); expect(stopBeaconSpy).toHaveBeenCalledWith(getBeaconInfoIdentifier(room2Beacon1));

View File

@ -1,87 +1,124 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`<RoomLiveShareWarning /> when user has live beacons and geolocation is available renders correctly with one live beacon in room 1`] = `"<div class="mx_RoomLiveShareWarning"><div class="mx_StyledLiveBeaconIcon mx_RoomLiveShareWarning_icon"></div><span class="mx_RoomLiveShareWarning_label">You are sharing your live location</span><span data-test-id="room-live-share-expiry" class="mx_LiveTimeRemaining">1h left</span><button data-test-id="room-live-share-primary-button" role="button" tabindex="0" class="mx_AccessibleButton mx_RoomLiveShareWarning_stopButton mx_AccessibleButton_hasKind mx_AccessibleButton_kind_danger">Stop</button></div>"`; exports[`<RoomLiveShareWarning /> when user has live beacons and geolocation is available renders correctly with one live beacon in room 1`] = `
<DocumentFragment>
exports[`<RoomLiveShareWarning /> when user has live beacons and geolocation is available renders correctly with two live beacons in room 1`] = `"<div class="mx_RoomLiveShareWarning"><div class="mx_StyledLiveBeaconIcon mx_RoomLiveShareWarning_icon"></div><span class="mx_RoomLiveShareWarning_label">You are sharing your live location</span><span data-test-id="room-live-share-expiry" class="mx_LiveTimeRemaining">12h left</span><button data-test-id="room-live-share-primary-button" role="button" tabindex="0" class="mx_AccessibleButton mx_RoomLiveShareWarning_stopButton mx_AccessibleButton_hasKind mx_AccessibleButton_kind_danger">Stop</button></div>"`; <div
class="mx_RoomLiveShareWarning"
exports[`<RoomLiveShareWarning /> when user has live beacons and geolocation is available stopping beacons displays error when stop sharing fails 1`] = `"<div class="mx_RoomLiveShareWarning"><div class="mx_StyledLiveBeaconIcon mx_RoomLiveShareWarning_icon mx_StyledLiveBeaconIcon_error"></div><span class="mx_RoomLiveShareWarning_label">An error occurred while stopping your live location, please try again</span><button data-test-id="room-live-share-primary-button" role="button" tabindex="0" class="mx_AccessibleButton mx_RoomLiveShareWarning_stopButton mx_AccessibleButton_hasKind mx_AccessibleButton_kind_danger">Retry</button></div>"`;
exports[`<RoomLiveShareWarning /> when user has live beacons and geolocation is available with location publish errors displays location publish error when mounted with location publish errors 1`] = `
<RoomLiveShareWarning
roomId="$room2:server.org"
>
<RoomLiveShareWarningInner
liveBeaconIds={
[
"$room2:server.org_@alice:server.org",
]
}
roomId="$room2:server.org"
> >
<div <div
className="mx_RoomLiveShareWarning" class="mx_StyledLiveBeaconIcon mx_RoomLiveShareWarning_icon"
onClick={[Function]} />
<span
class="mx_RoomLiveShareWarning_label"
> >
<StyledLiveBeaconIcon You are sharing your live location
className="mx_RoomLiveShareWarning_icon" </span>
withError={true} <span
> class="mx_LiveTimeRemaining"
<div data-test-id="room-live-share-expiry"
className="mx_StyledLiveBeaconIcon mx_RoomLiveShareWarning_icon mx_StyledLiveBeaconIcon_error" >
/> 1h left
</StyledLiveBeaconIcon> </span>
<span <button
className="mx_RoomLiveShareWarning_label" class="mx_AccessibleButton mx_RoomLiveShareWarning_stopButton mx_AccessibleButton_hasKind mx_AccessibleButton_kind_danger"
> data-testid="room-live-share-primary-button"
An error occurred whilst sharing your live location, please try again role="button"
</span> tabindex="0"
<AccessibleButton >
className="mx_RoomLiveShareWarning_stopButton" Stop
data-test-id="room-live-share-primary-button" </button>
disabled={false} </div>
element="button" </DocumentFragment>
kind="danger" `;
onClick={[Function]}
role="button" exports[`<RoomLiveShareWarning /> when user has live beacons and geolocation is available renders correctly with two live beacons in room 1`] = `
tabIndex={0} <DocumentFragment>
> <div
<button class="mx_RoomLiveShareWarning"
className="mx_AccessibleButton mx_RoomLiveShareWarning_stopButton mx_AccessibleButton_hasKind mx_AccessibleButton_kind_danger" >
data-test-id="room-live-share-primary-button" <div
onClick={[Function]} class="mx_StyledLiveBeaconIcon mx_RoomLiveShareWarning_icon"
onKeyDown={[Function]} />
onKeyUp={[Function]} <span
role="button" class="mx_RoomLiveShareWarning_label"
tabIndex={0} >
> You are sharing your live location
Retry </span>
</button> <span
</AccessibleButton> class="mx_LiveTimeRemaining"
<AccessibleButton data-test-id="room-live-share-expiry"
className="mx_RoomLiveShareWarning_closeButton" >
data-test-id="room-live-share-wire-error-close-button" 12h left
element="button" </span>
onClick={[Function]} <button
role="button" class="mx_AccessibleButton mx_RoomLiveShareWarning_stopButton mx_AccessibleButton_hasKind mx_AccessibleButton_kind_danger"
tabIndex={0} data-testid="room-live-share-primary-button"
title="Stop and close" role="button"
> tabindex="0"
<button >
className="mx_AccessibleButton mx_RoomLiveShareWarning_closeButton" Stop
data-test-id="room-live-share-wire-error-close-button" </button>
onClick={[Function]} </div>
onKeyDown={[Function]} </DocumentFragment>
onKeyUp={[Function]} `;
role="button"
tabIndex={0} exports[`<RoomLiveShareWarning /> when user has live beacons and geolocation is available stopping beacons displays error when stop sharing fails 1`] = `
title="Stop and close" <DocumentFragment>
> <div
<div class="mx_RoomLiveShareWarning"
className="mx_RoomLiveShareWarning_closeButtonIcon" >
/> <div
</button> class="mx_StyledLiveBeaconIcon mx_RoomLiveShareWarning_icon mx_StyledLiveBeaconIcon_error"
</AccessibleButton> />
</div> <span
</RoomLiveShareWarningInner> class="mx_RoomLiveShareWarning_label"
</RoomLiveShareWarning> >
An error occurred while stopping your live location, please try again
</span>
<button
class="mx_AccessibleButton mx_RoomLiveShareWarning_stopButton mx_AccessibleButton_hasKind mx_AccessibleButton_kind_danger"
data-testid="room-live-share-primary-button"
role="button"
tabindex="0"
>
Retry
</button>
</div>
</DocumentFragment>
`;
exports[`<RoomLiveShareWarning /> when user has live beacons and geolocation is available with location publish errors displays location publish error when mounted with location publish errors 1`] = `
<DocumentFragment>
<div
class="mx_RoomLiveShareWarning"
>
<div
class="mx_StyledLiveBeaconIcon mx_RoomLiveShareWarning_icon mx_StyledLiveBeaconIcon_error"
/>
<span
class="mx_RoomLiveShareWarning_label"
>
An error occurred whilst sharing your live location, please try again
</span>
<button
class="mx_AccessibleButton mx_RoomLiveShareWarning_stopButton mx_AccessibleButton_hasKind mx_AccessibleButton_kind_danger"
data-testid="room-live-share-primary-button"
role="button"
tabindex="0"
>
Retry
</button>
<button
class="mx_AccessibleButton mx_RoomLiveShareWarning_closeButton"
data-testid="room-live-share-wire-error-close-button"
role="button"
tabindex="0"
title="Stop and close"
>
<div
class="mx_RoomLiveShareWarning_closeButtonIcon"
/>
</button>
</div>
</DocumentFragment>
`; `;

View File

@ -15,15 +15,14 @@ limitations under the License.
*/ */
import React from "react"; import React from "react";
// eslint-disable-next-line deprecate/import
import { mount } from "enzyme";
import { act } from "react-dom/test-utils"; import { act } from "react-dom/test-utils";
import * as maplibregl from "maplibre-gl"; import * as maplibregl from "maplibre-gl";
import { ClientEvent } from "matrix-js-sdk/src/matrix"; import { ClientEvent } from "matrix-js-sdk/src/matrix";
import { logger } from "matrix-js-sdk/src/logger"; import { logger } from "matrix-js-sdk/src/logger";
import { fireEvent, getByTestId, render } from "@testing-library/react";
import Map from "../../../../src/components/views/location/Map"; import Map from "../../../../src/components/views/location/Map";
import { findByTestId, getMockClientWithEventEmitter } from "../../../test-utils"; import { getMockClientWithEventEmitter } from "../../../test-utils";
import MatrixClientContext from "../../../../src/contexts/MatrixClientContext"; import MatrixClientContext from "../../../../src/contexts/MatrixClientContext";
import { TILE_SERVER_WK_KEY } from "../../../../src/utils/WellKnownUtils"; import { TILE_SERVER_WK_KEY } from "../../../../src/utils/WellKnownUtils";
@ -39,11 +38,12 @@ describe("<Map />", () => {
[TILE_SERVER_WK_KEY.name]: { map_style_url: "maps.com" }, [TILE_SERVER_WK_KEY.name]: { map_style_url: "maps.com" },
}), }),
}); });
const getComponent = (props = {}) => const getComponent = (props = {}, renderingFn?: any) =>
mount(<Map {...defaultProps} {...props} />, { (renderingFn ?? render)(
wrappingComponent: MatrixClientContext.Provider, <MatrixClientContext.Provider value={matrixClient}>
wrappingComponentProps: { value: matrixClient }, <Map {...defaultProps} {...props} />
}); </MatrixClientContext.Provider>,
);
beforeEach(() => { beforeEach(() => {
jest.clearAllMocks(); jest.clearAllMocks();
@ -58,8 +58,8 @@ describe("<Map />", () => {
const mockMap = new maplibregl.Map(mapOptions); const mockMap = new maplibregl.Map(mapOptions);
it("renders", () => { it("renders", () => {
const component = getComponent(); const { container } = getComponent();
expect(component).toBeTruthy(); expect(container.firstChild).not.toBeNull();
}); });
describe("onClientWellKnown emits", () => { describe("onClientWellKnown emits", () => {
@ -107,10 +107,10 @@ describe("<Map />", () => {
}); });
it("updates map center when centerGeoUri prop changes", () => { it("updates map center when centerGeoUri prop changes", () => {
const component = getComponent({ centerGeoUri: "geo:51,42" }); const { rerender } = getComponent({ centerGeoUri: "geo:51,42" });
component.setProps({ centerGeoUri: "geo:53,45" }); getComponent({ centerGeoUri: "geo:53,45" }, rerender);
component.setProps({ centerGeoUri: "geo:56,47" }); getComponent({ centerGeoUri: "geo:56,47" }, rerender);
expect(mockMap.setCenter).toHaveBeenCalledWith({ lat: 51, lon: 42 }); expect(mockMap.setCenter).toHaveBeenCalledWith({ lat: 51, lon: 42 });
expect(mockMap.setCenter).toHaveBeenCalledWith({ lat: 53, lon: 45 }); expect(mockMap.setCenter).toHaveBeenCalledWith({ lat: 53, lon: 45 });
expect(mockMap.setCenter).toHaveBeenCalledWith({ lat: 56, lon: 47 }); expect(mockMap.setCenter).toHaveBeenCalledWith({ lat: 56, lon: 47 });
@ -141,12 +141,13 @@ describe("<Map />", () => {
}); });
it("updates map bounds when bounds prop changes", () => { it("updates map bounds when bounds prop changes", () => {
const component = getComponent({ centerGeoUri: "geo:51,42" }); const { rerender } = getComponent({ centerGeoUri: "geo:51,42" });
const bounds = { north: 51, south: 50, east: 42, west: 41 }; const bounds = { north: 51, south: 50, east: 42, west: 41 };
const bounds2 = { north: 53, south: 51, east: 45, west: 44 }; const bounds2 = { north: 53, south: 51, east: 45, west: 44 };
component.setProps({ bounds });
component.setProps({ bounds: bounds2 }); getComponent({ bounds }, rerender);
getComponent({ bounds: bounds2 }, rerender);
expect(mockMap.fitBounds).toHaveBeenCalledTimes(2); expect(mockMap.fitBounds).toHaveBeenCalledTimes(2);
}); });
}); });
@ -154,31 +155,28 @@ describe("<Map />", () => {
describe("children", () => { describe("children", () => {
it("renders without children", () => { it("renders without children", () => {
const component = getComponent({ children: null }); const component = getComponent({ children: null });
component.setProps({});
// no error // no error
expect(component).toBeTruthy(); expect(component).toBeTruthy();
}); });
it("renders children with map renderProp", () => { it("renders children with map renderProp", () => {
const children = ({ map }) => ( const children = ({ map }: { map: maplibregl.Map }) => (
<div data-test-id="test-child" data-map={map}> <div data-testid="test-child" data-map={map}>
Hello, world Hello, world
</div> </div>
); );
const component = getComponent({ children }); const { container } = getComponent({ children });
// renders child with map instance // passes the map instance to the react children
expect(findByTestId(component, "test-child").props()["data-map"]).toEqual(mockMap); expect(getByTestId(container, "test-child").dataset.map).toBeTruthy();
}); });
}); });
describe("onClick", () => { describe("onClick", () => {
it("eats clicks to maplibre attribution button", () => { it("eats clicks to maplibre attribution button", () => {
const onClick = jest.fn(); const onClick = jest.fn();
const component = getComponent({ onClick }); getComponent({ onClick });
act(() => { act(() => {
// this is added to the dom by maplibregl // this is added to the dom by maplibregl
@ -186,7 +184,7 @@ describe("<Map />", () => {
// just fake the target // just fake the target
const fakeEl = document.createElement("div"); const fakeEl = document.createElement("div");
fakeEl.className = "maplibregl-ctrl-attrib-button"; fakeEl.className = "maplibregl-ctrl-attrib-button";
component.simulate("click", { target: fakeEl }); fireEvent.click(fakeEl);
}); });
expect(onClick).not.toHaveBeenCalled(); expect(onClick).not.toHaveBeenCalled();
@ -194,10 +192,10 @@ describe("<Map />", () => {
it("calls onClick", () => { it("calls onClick", () => {
const onClick = jest.fn(); const onClick = jest.fn();
const component = getComponent({ onClick }); const { container } = getComponent({ onClick });
act(() => { act(() => {
component.simulate("click"); fireEvent.click(container.firstChild);
}); });
expect(onClick).toHaveBeenCalled(); expect(onClick).toHaveBeenCalled();

View File

@ -15,9 +15,8 @@ limitations under the License.
*/ */
import React from "react"; import React from "react";
// eslint-disable-next-line deprecate/import
import { mount } from "enzyme";
import { RoomMember } from "matrix-js-sdk/src/matrix"; import { RoomMember } from "matrix-js-sdk/src/matrix";
import { getByTestId, render } from "@testing-library/react";
import Marker from "../../../../src/components/views/location/Marker"; import Marker from "../../../../src/components/views/location/Marker";
@ -25,27 +24,27 @@ describe("<Marker />", () => {
const defaultProps = { const defaultProps = {
id: "abc123", id: "abc123",
}; };
const getComponent = (props = {}) => mount(<Marker {...defaultProps} {...props} />); const getComponent = (props = {}) => render(<Marker {...defaultProps} {...props} />);
it("renders with location icon when no room member", () => { it("renders with location icon when no room member", () => {
const component = getComponent(); const { asFragment } = getComponent();
expect(component).toMatchSnapshot(); expect(asFragment()).toMatchSnapshot();
}); });
it("does not try to use member color without room member", () => { it("does not try to use member color without room member", () => {
const component = getComponent({ useMemberColor: true }); const { container } = getComponent({ useMemberColor: true });
expect(component.find("div").at(0).props().className).toEqual("mx_Marker mx_Marker_defaultColor"); expect(container.querySelector(".mx_Marker.mx_Marker_defaultColor")).toBeInTheDocument();
}); });
it("uses member color class", () => { it("uses member color class", () => {
const member = new RoomMember("!room:server", "@user:server"); const member = new RoomMember("!room:server", "@user:server");
const component = getComponent({ useMemberColor: true, roomMember: member }); const { container } = getComponent({ useMemberColor: true, roomMember: member });
expect(component.find("div").at(0).props().className).toEqual("mx_Marker mx_Username_color3"); expect(container.querySelector(".mx_Marker.mx_Username_color3")).toBeInTheDocument();
}); });
it("renders member avatar when roomMember is truthy", () => { it("renders member avatar when roomMember is truthy", () => {
const member = new RoomMember("!room:server", "@user:server"); const member = new RoomMember("!room:server", "@user:server");
const component = getComponent({ roomMember: member }); const { container } = getComponent({ roomMember: member });
expect(component.find("MemberAvatar").length).toBeTruthy(); expect(getByTestId(container, "avatar-img")).toBeInTheDocument();
}); });
}); });

View File

@ -1,22 +1,18 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`<Marker /> renders with location icon when no room member 1`] = ` exports[`<Marker /> renders with location icon when no room member 1`] = `
<ForwardRef <DocumentFragment>
id="abc123"
>
<div <div
className="mx_Marker mx_Marker_defaultColor" class="mx_Marker mx_Marker_defaultColor"
id="abc123" id="abc123"
> >
<OptionalTooltip> <div
class="mx_Marker_border"
>
<div <div
className="mx_Marker_border" class="mx_Marker_icon"
> />
<div </div>
className="mx_Marker_icon"
/>
</div>
</OptionalTooltip>
</div> </div>
</ForwardRef> </DocumentFragment>
`; `;