Refactor the various email/phone management UI into a single component (#12884)

* Refactor the various email/phone management UI into a single component

These were basically the same component copied & pasted 3 times and
tweaked to match the behaviour of each case. This de-dupes them into
one component.

This all could really benefit from playwright tests, but would require
setting up a dummy ID server in the playwright tests. This is all legacy
pre-MAS stuff so its questionable whether its worth the effort.

* Basic test, remove old tests

* Use different text to confirm remove & put headers back

although the two texts are both 'Remove' in practice

* Remove string

This was never triggered anyway with sydent & synapse because they
don't seem to agree on what error to return. In any case, I think it
makes more sense for it to be consistent with the email path, ie. using
a dialog.

* Avoid nested forms

* Snapshots

* More snapshots

* Test the hs side

* Snapshots

* Test IS bind/revoke

* Test remove can be cancelled

* Test unvalidated cases & fix phone error

* Reset state between tests

* Import useState directly

* One more direct React import
This commit is contained in:
David Baker
2024-08-14 14:13:57 +01:00
committed by GitHub
parent de898d1b62
commit 4751c52d82
21 changed files with 1391 additions and 1981 deletions
@@ -1,167 +0,0 @@
/*
Copyright 2022 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import React from "react";
import { fireEvent, render, screen } from "@testing-library/react";
import { IThreepid, ThreepidMedium, IRequestTokenResponse, MatrixError } from "matrix-js-sdk/src/matrix";
import { TranslationKey, UserFriendlyError } from "../../../../../src/languageHandler";
import EmailAddresses, { EmailAddress } from "../../../../../src/components/views/settings/discovery/EmailAddresses";
import { clearAllModals, getMockClientWithEventEmitter } from "../../../../test-utils";
const mockGetAccessToken = jest.fn().mockResolvedValue("getAccessToken");
jest.mock("../../../../../src/IdentityAuthClient", () =>
jest.fn().mockImplementation(() => ({
getAccessToken: mockGetAccessToken,
})),
);
const emailThreepidFixture: IThreepid = {
medium: ThreepidMedium.Email,
address: "foo@bar.com",
validated_at: 12345,
added_at: 12342,
bound: false,
};
describe("<EmailAddress/>", () => {
const mockClient = getMockClientWithEventEmitter({
getIdentityServerUrl: jest.fn().mockReturnValue("https://fake-identity-server"),
generateClientSecret: jest.fn(),
requestEmailToken: jest.fn(),
bindThreePid: jest.fn(),
});
beforeEach(() => {
jest.useFakeTimers();
});
afterEach(async () => {
jest.useRealTimers();
await clearAllModals();
});
it("should track props.email.bound changes", async () => {
const { rerender } = render(<EmailAddress email={emailThreepidFixture} />);
await screen.findByText("Share");
rerender(
<EmailAddress
email={{
...emailThreepidFixture,
bound: true,
}}
/>,
);
await screen.findByText("Revoke");
});
describe("Email verification share phase", () => {
it("shows translated error message", async () => {
render(<EmailAddress email={emailThreepidFixture} />);
mockClient.requestEmailToken.mockRejectedValue(
new MatrixError(
{ errcode: "M_THREEPID_IN_USE", error: "Some fake MatrixError occured" },
400,
"https://fake-url/",
),
);
fireEvent.click(screen.getByText("Share"));
// Expect error dialog/modal to be shown. We have to wait for the UI to transition.
expect(await screen.findByText("This email address is already in use")).toBeInTheDocument();
});
});
describe("Email verification complete phase", () => {
beforeEach(async () => {
// Start these tests out at the "Complete" phase
render(<EmailAddress email={emailThreepidFixture} />);
mockClient.requestEmailToken.mockResolvedValue({ sid: "123-fake-sid" } satisfies IRequestTokenResponse);
fireEvent.click(screen.getByText("Share"));
// Then wait for the completion screen to come up
await screen.findByText("Complete");
});
it("Shows error dialog when share completion fails (email not verified yet)", async () => {
mockClient.bindThreePid.mockRejectedValue(
new MatrixError(
{ errcode: "M_THREEPID_AUTH_FAILED", error: "Some fake MatrixError occured" },
403,
"https://fake-url/",
),
);
await expect(screen.findByText("Complete")).resolves.not.toHaveAttribute("aria-disabled", "true");
fireEvent.click(screen.getByText("Complete"));
// Expect error dialog/modal to be shown. We have to wait for the UI to transition.
// Check the title
expect(await screen.findByText("Your email address hasn't been verified yet")).toBeInTheDocument();
// Check the description
expect(
await screen.findByText(
"Click the link in the email you received to verify and then click continue again.",
),
).toBeInTheDocument();
});
it("Shows error dialog when share completion fails (UserFriendlyError)", async () => {
const fakeErrorText = "Fake UserFriendlyError error in test" as TranslationKey;
mockClient.bindThreePid.mockRejectedValue(new UserFriendlyError(fakeErrorText));
await expect(screen.findByText("Complete")).resolves.not.toHaveAttribute("aria-disabled", "true");
fireEvent.click(screen.getByText("Complete"));
// Expect error dialog/modal to be shown. We have to wait for the UI to transition.
// Check the title
expect(await screen.findByText("Unable to verify email address.")).toBeInTheDocument();
// Check the description
expect(await screen.findByText(fakeErrorText)).toBeInTheDocument();
});
it("Shows error dialog when share completion fails (generic error)", async () => {
const fakeErrorText = "Fake plain error in test";
mockClient.bindThreePid.mockRejectedValue(new Error(fakeErrorText));
await expect(screen.findByText("Complete")).resolves.not.toHaveAttribute("aria-disabled", "true");
fireEvent.click(screen.getByText("Complete"));
// Expect error dialog/modal to be shown. We have to wait for the UI to transition.
// Check the title
expect(await screen.findByText("Unable to verify email address.")).toBeInTheDocument();
// Check the description
expect(await screen.findByText(fakeErrorText)).toBeInTheDocument();
});
});
});
describe("<EmailAddresses />", () => {
it("should render a loader while loading", async () => {
const { container } = render(<EmailAddresses emails={[emailThreepidFixture]} isLoading={true} />);
expect(container).toMatchSnapshot();
});
it("should render email addresses", async () => {
const { container } = render(<EmailAddresses emails={[emailThreepidFixture]} isLoading={false} />);
expect(container).toMatchSnapshot();
});
it("should handle no email addresses", async () => {
const { container } = render(<EmailAddresses emails={[]} isLoading={false} />);
expect(container).toMatchSnapshot();
});
});
@@ -1,101 +0,0 @@
/*
Copyright 2022 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import React from "react";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { IThreepid, ThreepidMedium } from "matrix-js-sdk/src/matrix";
import userEvent from "@testing-library/user-event";
import { mocked } from "jest-mock";
import PhoneNumbers, { PhoneNumber } from "../../../../../src/components/views/settings/discovery/PhoneNumbers";
import { stubClient } from "../../../../test-utils";
const msisdn: IThreepid = {
medium: ThreepidMedium.Phone,
address: "441111111111",
validated_at: 12345,
added_at: 12342,
bound: false,
};
describe("<PhoneNumber/>", () => {
it("should track props.msisdn.bound changes", async () => {
const { rerender } = render(<PhoneNumber msisdn={{ ...msisdn }} />);
await screen.findByText("Share");
rerender(<PhoneNumber msisdn={{ ...msisdn, bound: true }} />);
await screen.findByText("Revoke");
});
});
const mockGetAccessToken = jest.fn().mockResolvedValue("$$getAccessToken");
jest.mock("../../../../../src/IdentityAuthClient", () =>
jest.fn().mockImplementation(() => ({
getAccessToken: mockGetAccessToken,
})),
);
describe("<PhoneNumbers />", () => {
it("should render a loader while loading", async () => {
const { container } = render(<PhoneNumbers msisdns={[{ ...msisdn }]} isLoading={true} />);
expect(container).toMatchSnapshot();
});
it("should render phone numbers", async () => {
const { container } = render(<PhoneNumbers msisdns={[{ ...msisdn }]} isLoading={false} />);
expect(container).toMatchSnapshot();
});
it("should handle no numbers", async () => {
const { container } = render(<PhoneNumbers msisdns={[]} isLoading={false} />);
expect(container).toMatchSnapshot();
});
it("should allow binding msisdn", async () => {
const cli = stubClient();
const { getByText, getByLabelText, asFragment } = render(
<PhoneNumbers msisdns={[{ ...msisdn }]} isLoading={false} />,
);
mocked(cli.requestMsisdnToken).mockResolvedValue({
sid: "SID",
msisdn: "+447900111222",
submit_url: "https://server.url",
success: true,
intl_fmt: "no-clue",
});
fireEvent.click(getByText("Share"));
await waitFor(() =>
expect(cli.requestMsisdnToken).toHaveBeenCalledWith(
null,
"+441111111111",
"t35tcl1Ent5ECr3T",
1,
undefined,
"$$getAccessToken",
),
);
expect(asFragment()).toMatchSnapshot();
const verificationCodeField = getByLabelText("Verification code");
await userEvent.type(verificationCodeField, "123666{Enter}");
expect(cli.submitMsisdnToken).toHaveBeenCalledWith("SID", "t35tcl1Ent5ECr3T", "123666", "$$getAccessToken");
});
});
@@ -1,97 +0,0 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`<EmailAddresses /> should handle no email addresses 1`] = `
<div>
<div
class="mx_SettingsSubsection"
>
<div
class="mx_SettingsSubsectionHeading"
>
<h3
class="mx_Heading_h4 mx_SettingsSubsectionHeading_heading"
>
Email addresses
</h3>
</div>
<div
class="mx_SettingsSubsection_description"
>
<div
class="mx_SettingsSubsection_text"
>
Discovery options will appear once you have added an email.
</div>
</div>
</div>
</div>
`;
exports[`<EmailAddresses /> should render a loader while loading 1`] = `
<div>
<div
class="mx_SettingsSubsection"
>
<div
class="mx_SettingsSubsectionHeading"
>
<h3
class="mx_Heading_h4 mx_SettingsSubsectionHeading_heading"
>
Email addresses
</h3>
</div>
<div
class="mx_SettingsSubsection_content mx_SettingsSubsection_contentStretch"
>
<div
class="mx_InlineSpinner"
>
<div
aria-label="Loading…"
class="mx_InlineSpinner_icon mx_Spinner_icon"
style="width: 16px; height: 16px;"
/>
</div>
</div>
</div>
</div>
`;
exports[`<EmailAddresses /> should render email addresses 1`] = `
<div>
<div
class="mx_SettingsSubsection"
>
<div
class="mx_SettingsSubsectionHeading"
>
<h3
class="mx_Heading_h4 mx_SettingsSubsectionHeading_heading"
>
Email addresses
</h3>
</div>
<div
class="mx_SettingsSubsection_content mx_SettingsSubsection_contentStretch"
>
<div
class="mx_EmailAddressesPhoneNumbers_discovery_existing"
>
<span
class="mx_EmailAddressesPhoneNumbers_discovery_existing_address"
>
foo@bar.com
</span>
<div
class="mx_AccessibleButton mx_EmailAddressesPhoneNumbers_discovery_existing_button mx_AccessibleButton_hasKind mx_AccessibleButton_kind_primary_sm"
role="button"
tabindex="0"
>
Share
</div>
</div>
</div>
</div>
</div>
`;
@@ -1,163 +0,0 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`<PhoneNumbers /> should allow binding msisdn 1`] = `
<DocumentFragment>
<div
class="mx_SettingsSubsection"
data-testid="mx_DiscoveryPhoneNumbers"
>
<div
class="mx_SettingsSubsectionHeading"
>
<h3
class="mx_Heading_h4 mx_SettingsSubsectionHeading_heading"
>
Phone numbers
</h3>
</div>
<div
class="mx_SettingsSubsection_content mx_SettingsSubsection_contentStretch"
>
<div
class="mx_EmailAddressesPhoneNumbers_discovery_existing"
>
<span
class="mx_EmailAddressesPhoneNumbers_discovery_existing_address"
>
+441111111111
</span>
<span
class="mx_EmailAddressesPhoneNumbers_discovery_existing_verification"
>
<span>
Please enter verification code sent via text.
<br />
</span>
<form
autocomplete="off"
novalidate=""
>
<div
class="mx_Field mx_Field_input"
>
<input
autocomplete="off"
id="mx_Field_1"
label="Verification code"
placeholder="Verification code"
type="text"
value=""
/>
<label
for="mx_Field_1"
>
Verification code
</label>
</div>
</form>
</span>
</div>
</div>
</div>
</DocumentFragment>
`;
exports[`<PhoneNumbers /> should handle no numbers 1`] = `
<div>
<div
class="mx_SettingsSubsection"
data-testid="mx_DiscoveryPhoneNumbers"
>
<div
class="mx_SettingsSubsectionHeading"
>
<h3
class="mx_Heading_h4 mx_SettingsSubsectionHeading_heading"
>
Phone numbers
</h3>
</div>
<div
class="mx_SettingsSubsection_description"
>
<div
class="mx_SettingsSubsection_text"
>
Discovery options will appear once you have added a phone number.
</div>
</div>
</div>
</div>
`;
exports[`<PhoneNumbers /> should render a loader while loading 1`] = `
<div>
<div
class="mx_SettingsSubsection"
data-testid="mx_DiscoveryPhoneNumbers"
>
<div
class="mx_SettingsSubsectionHeading"
>
<h3
class="mx_Heading_h4 mx_SettingsSubsectionHeading_heading"
>
Phone numbers
</h3>
</div>
<div
class="mx_SettingsSubsection_content mx_SettingsSubsection_contentStretch"
>
<div
class="mx_InlineSpinner"
>
<div
aria-label="Loading…"
class="mx_InlineSpinner_icon mx_Spinner_icon"
style="width: 16px; height: 16px;"
/>
</div>
</div>
</div>
</div>
`;
exports[`<PhoneNumbers /> should render phone numbers 1`] = `
<div>
<div
class="mx_SettingsSubsection"
data-testid="mx_DiscoveryPhoneNumbers"
>
<div
class="mx_SettingsSubsectionHeading"
>
<h3
class="mx_Heading_h4 mx_SettingsSubsectionHeading_heading"
>
Phone numbers
</h3>
</div>
<div
class="mx_SettingsSubsection_content mx_SettingsSubsection_contentStretch"
>
<div
class="mx_EmailAddressesPhoneNumbers_discovery_existing"
>
<span
class="mx_EmailAddressesPhoneNumbers_discovery_existing_address"
>
+
441111111111
</span>
<div
class="mx_AccessibleButton mx_EmailAddressesPhoneNumbers_discovery_existing_button mx_AccessibleButton_hasKind mx_AccessibleButton_kind_primary_sm"
role="button"
tabindex="0"
>
Share
</div>
</div>
</div>
</div>
</div>
`;