Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WD-17063 - chore(tests): add tests for create identity form #503

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
149 changes: 149 additions & 0 deletions ui/src/pages/identities/IdentityCreate/IdentityCreate.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
import { screen, waitFor } from "@testing-library/dom";
import { faker } from "@faker-js/faker";
import userEvent from "@testing-library/user-event";
import { Location } from "react-router-dom";
import MockAdapter from "axios-mock-adapter";
import * as reactQuery from "@tanstack/react-query";

import { renderComponent } from "test/utils";
import { urls } from "urls";
import { axiosInstance } from "api/axios";

import IdentityCreate from "./IdentityCreate";
import { IdentityFormLabel } from "../IdentityForm";
import { Label } from "./types";
import {
NotificationProvider,
NotificationConsumer,
} from "@canonical/react-components";
import { queryKeys } from "util/queryKeys";
import { mockSchema } from "test/mocks/schemas";
import { Schema } from "types/schema";

vi.mock("@tanstack/react-query", async () => {
const actual = await vi.importActual("@tanstack/react-query");
return {
...actual,
useQueryIdentity: vi.fn(),
};
});

const mock = new MockAdapter(axiosInstance);

let schema: Schema;
beforeEach(() => {
mock.reset();
vi.spyOn(reactQuery, "useQueryClient").mockReturnValue({
invalidateQueries: vi.fn(),
} as unknown as reactQuery.QueryClient);
mock.onPost("/identities").reply(200);
schema = mockSchema();
mock
.onGet("/schemas?page_token=&page_size=50")
.reply(200, { data: [schema] });
});

test("can cancel", async () => {
let location: Location | null = null;
renderComponent(<IdentityCreate />, {
url: "/",
setLocation: (newLocation) => {
location = newLocation;
},
});
await userEvent.click(screen.getByRole("button", { name: Label.CANCEL }));
expect((location as Location | null)?.pathname).toBe(urls.identities.index);
});

test("calls the API on submit", async () => {
const values = {
email: faker.word.sample(),
schemaId: schema.id,
};
renderComponent(<IdentityCreate />);
const emailInput = screen.getByRole("textbox", {
name: IdentityFormLabel.EMAIL,
});
await userEvent.click(emailInput);
await userEvent.clear(emailInput);
await userEvent.type(emailInput, values.email);
await userEvent.selectOptions(
screen.getByRole("combobox", { name: IdentityFormLabel.SCHEMA }),
values.schemaId,
);
await userEvent.click(screen.getByRole("button", { name: Label.SUBMIT }));
expect(mock.history.post[0].url).toBe("/identities");
expect(JSON.parse(mock.history.post[0].data as string)).toMatchObject({
schema_id: values.schemaId,
traits: {
email: values.email,
},
});
});

test("handles API success", async () => {
let location: Location | null = null;
const invalidateQueries = vi.fn();
vi.spyOn(reactQuery, "useQueryClient").mockReturnValue({
invalidateQueries,
} as unknown as reactQuery.QueryClient);
mock.onPost("/identities").reply(200);
renderComponent(
<NotificationProvider>
<IdentityCreate />
<NotificationConsumer />
</NotificationProvider>,
{
url: "/",
setLocation: (newLocation) => {
location = newLocation;
},
},
);
await userEvent.type(
screen.getByRole("textbox", {
name: IdentityFormLabel.EMAIL,
}),
faker.word.sample(),
);
await userEvent.selectOptions(
screen.getByRole("combobox", { name: IdentityFormLabel.SCHEMA }),
schema.id,
);
await userEvent.click(screen.getByRole("button", { name: Label.SUBMIT }));
await waitFor(() =>
expect(invalidateQueries).toHaveBeenCalledWith({
queryKey: [queryKeys.identities],
}),
);
expect(document.querySelector(".p-notification--positive")).toHaveTextContent(
Label.SUCCESS,
),
expect((location as Location | null)?.pathname).toBe(urls.identities.index);
});

test("handles API failure", async () => {
mock.onPost("/identities").reply(400, {
message: "oops",
});
renderComponent(
<NotificationProvider>
<IdentityCreate />
<NotificationConsumer />
</NotificationProvider>,
);
await userEvent.type(
screen.getByRole("textbox", {
name: IdentityFormLabel.EMAIL,
}),
faker.word.sample(),
);
await userEvent.selectOptions(
screen.getByRole("combobox", { name: IdentityFormLabel.SCHEMA }),
schema.id,
);
await userEvent.click(screen.getByRole("button", { name: Label.SUBMIT }));
expect(document.querySelector(".p-notification--negative")).toHaveTextContent(
`${Label.ERROR}oops`,
);
});
16 changes: 10 additions & 6 deletions ui/src/pages/identities/IdentityCreate/IdentityCreate.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import SidePanel from "components/SidePanel";
import ScrollableContainer from "components/ScrollableContainer";
import { TestId } from "./test-types";
import { testId } from "test/utils";
import { Label } from "./types";

const IdentityCreate: FC = () => {
const navigate = useNavigate();
Expand Down Expand Up @@ -45,12 +46,15 @@ const IdentityCreate: FC = () => {
void queryClient.invalidateQueries({
queryKey: [queryKeys.identities],
});
const msg = `Identity created.`;
navigate("/identity", notify.queue(notify.success(msg)));
navigate("/identity", notify.queue(notify.success(Label.SUCCESS)));
})
.catch((e) => {
.catch((error: unknown) => {
formik.setSubmitting(false);
notify.failure("Identity creation failed", e);
notify.failure(
Label.ERROR,
error instanceof Error ? error : null,
typeof error === "string" ? error : null,
);
});
},
});
Expand Down Expand Up @@ -81,15 +85,15 @@ const IdentityCreate: FC = () => {
<Row className="u-align-text--right">
<Col size={12}>
<Button appearance="base" onClick={() => navigate("/identity")}>
Cancel
{Label.CANCEL}
</Button>
<ActionButton
appearance="positive"
loading={formik.isSubmitting}
disabled={!formik.isValid}
onClick={submitForm}
>
Save
{Label.SUBMIT}
</ActionButton>
</Col>
</Row>
Expand Down
6 changes: 6 additions & 0 deletions ui/src/pages/identities/IdentityCreate/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export enum Label {
CANCEL = "Cancel",
ERROR = "Identity creation failed",
SUBMIT = "Save",
SUCCESS = "Identity created.",
}
1 change: 1 addition & 0 deletions ui/src/pages/identities/IdentityForm/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export { default, type IdentityFormTypes } from "./IdentityForm";
export { Label as IdentityFormLabel } from "./types";
Loading