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-17056 - chore(tests): add tests for client add/edit #502

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
132 changes: 132 additions & 0 deletions ui/src/pages/clients/ClientCreate/ClientCreate.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
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 ClientCreate from "./ClientCreate";
import { ClientFormLabel } from "../ClientForm";
import { Label } from "./types";
import { initialValues } from "./ClientCreate";
import {
NotificationProvider,
NotificationConsumer,
} from "@canonical/react-components";
import { queryKeys } from "util/queryKeys";

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

const mock = new MockAdapter(axiosInstance);

beforeEach(() => {
mock.reset();
vi.spyOn(reactQuery, "useQueryClient").mockReturnValue({
invalidateQueries: vi.fn(),
} as unknown as reactQuery.QueryClient);
mock.onPost("/clients").reply(200);
});

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

test("calls the API on submit", async () => {
const values = {
client_name: faker.word.sample(),
};
renderComponent(<ClientCreate />);
const input = screen.getByRole("textbox", { name: ClientFormLabel.NAME });
await userEvent.click(input);
await userEvent.clear(input);
await userEvent.type(input, values.client_name);
await userEvent.click(screen.getByRole("button", { name: Label.SUBMIT }));
expect(mock.history.post[0].url).toBe("/clients");
expect(mock.history.post[0].data).toBe(
JSON.stringify({
...initialValues,
...values,
}),
);
});

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("/clients").reply(200, {
data: { client_id: "client1", client_secret: "secret1" },
});
const values = {
client_name: faker.word.sample(),
};
renderComponent(
<NotificationProvider>
<ClientCreate />
<NotificationConsumer />
</NotificationProvider>,
{
url: "/",
setLocation: (newLocation) => {
location = newLocation;
},
},
);
await userEvent.type(
screen.getByRole("textbox", { name: ClientFormLabel.NAME }),
values.client_name,
);
await userEvent.click(screen.getByRole("button", { name: Label.SUBMIT }));
await waitFor(() =>
expect(invalidateQueries).toHaveBeenCalledWith({
queryKey: [queryKeys.clients],
}),
);
expect(document.querySelector(".p-notification--positive")).toHaveTextContent(
"Client created. Id: client1 Secret: secret1",
),
expect((location as Location | null)?.pathname).toBe(urls.clients.index);
});

test("handles API failure", async () => {
mock.onPost("/clients").reply(400, {
message: "oops",
});
const values = {
client_name: faker.word.sample(),
};
renderComponent(
<NotificationProvider>
<ClientCreate />
<NotificationConsumer />
</NotificationProvider>,
);
await userEvent.type(
screen.getByRole("textbox", { name: ClientFormLabel.NAME }),
values.client_name,
);
await userEvent.click(screen.getByRole("button", { name: Label.SUBMIT }));
expect(document.querySelector(".p-notification--negative")).toHaveTextContent(
`${Label.ERROR}oops`,
);
});
33 changes: 20 additions & 13 deletions ui/src/pages/clients/ClientCreate/ClientCreate.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,17 @@ import SidePanel from "components/SidePanel";
import ScrollableContainer from "components/ScrollableContainer";
import { TestId } from "./test-types";
import { testId } from "test/utils";
import { Label } from "./types";

export const initialValues = {
client_uri: "",
client_name: "grafana",
grant_types: ["authorization_code", "refresh_token"],
response_types: ["code", "id_token"],
scope: "openid offline_access email",
redirect_uris: ["http://localhost:2345/login/generic_oauth"],
request_object_signing_alg: "RS256",
};

const ClientCreate: FC = () => {
const navigate = useNavigate();
Expand All @@ -28,15 +39,7 @@ const ClientCreate: FC = () => {
});

const formik = useFormik<ClientFormTypes>({
initialValues: {
client_uri: "",
client_name: "grafana",
grant_types: ["authorization_code", "refresh_token"],
response_types: ["code", "id_token"],
scope: "openid offline_access email",
redirect_uris: ["http://localhost:2345/login/generic_oauth"],
request_object_signing_alg: "RS256",
},
initialValues,
validationSchema: ClientCreateSchema,
onSubmit: (values) => {
createClient(JSON.stringify(values))
Expand All @@ -47,9 +50,13 @@ const ClientCreate: FC = () => {
const msg = `Client created. Id: ${result.client_id} Secret: ${result.client_secret}`;
navigate("/client", notify.queue(notify.success(msg)));
})
.catch((e) => {
.catch((error: unknown) => {
formik.setSubmitting(false);
notify.failure("Client creation failed", e);
notify.failure(
Label.ERROR,
error instanceof Error ? error : null,
typeof error === "string" ? error : null,
);
});
},
});
Expand Down Expand Up @@ -80,15 +87,15 @@ const ClientCreate: FC = () => {
<Row className="u-align-text--right">
<Col size={12}>
<Button appearance="base" onClick={() => navigate("/client")}>
Cancel
{Label.CANCEL}
</Button>
<ActionButton
appearance="positive"
loading={formik.isSubmitting}
disabled={!formik.isValid}
onClick={submitForm}
>
Save
{Label.SUBMIT}
</ActionButton>
</Col>
</Row>
Expand Down
5 changes: 5 additions & 0 deletions ui/src/pages/clients/ClientCreate/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export enum Label {
CANCEL = "Cancel",
ERROR = "Client creation failed",
SUBMIT = "Save",
}
143 changes: 143 additions & 0 deletions ui/src/pages/clients/ClientEdit/ClientEdit.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
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 ClientEdit from "./ClientEdit";
import { ClientFormLabel } from "../ClientForm";
import { Label } from "./types";
import {
NotificationProvider,
NotificationConsumer,
} from "@canonical/react-components";
import { queryKeys } from "util/queryKeys";
import { mockClient } from "test/mocks/clients";
import { Client } from "types/client";

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

const mock = new MockAdapter(axiosInstance);

let client: Client;

beforeEach(() => {
vi.spyOn(reactQuery, "useQueryClient").mockReturnValue({
invalidateQueries: vi.fn(),
} as unknown as reactQuery.QueryClient);
mock.reset();
client = mockClient();
mock.onGet(`/clients/${client.client_id}`).reply(200, { data: client });
mock.onPut(`/clients/${client.client_id}`).reply(200);
});

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

test("calls the API on submit", async () => {
const values = {
client_name: faker.word.sample(),
};
renderComponent(<ClientEdit />, {
url: `/?id=${client.client_id}`,
});
const input = screen.getByRole("textbox", { name: ClientFormLabel.NAME });
await userEvent.click(input);
await userEvent.clear(input);
await userEvent.type(input, values.client_name);
await userEvent.click(screen.getByRole("button", { name: Label.SUBMIT }));
expect(mock.history.put[0].url).toBe(`/clients/${client.client_id}`);
expect(JSON.parse(mock.history.put[0].data as string)).toMatchObject({
client_uri: client.client_uri,
grant_types: client.grant_types,
response_types: client.response_types,
scope: client.scope,
redirect_uris: client.redirect_uris,
request_object_signing_alg: client.request_object_signing_alg,
...values,
});
});

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.onPut(`/clients/${client.client_id}`).reply(200, {
data: { client_id: "client1", client_secret: "secret1" },
});
const values = {
client_name: faker.word.sample(),
};
renderComponent(
<NotificationProvider>
<ClientEdit />
<NotificationConsumer />
</NotificationProvider>,
{
url: `/?id=${client.client_id}`,
setLocation: (newLocation) => {
location = newLocation;
},
},
);
await userEvent.type(
screen.getByRole("textbox", { name: ClientFormLabel.NAME }),
values.client_name,
);
await userEvent.click(screen.getByRole("button", { name: Label.SUBMIT }));
await waitFor(() =>
expect(invalidateQueries).toHaveBeenCalledWith({
queryKey: [queryKeys.clients],
}),
);
expect(document.querySelector(".p-notification--positive")).toHaveTextContent(
Label.SUCCESS,
),
expect((location as Location | null)?.pathname).toBe(urls.clients.index);
});

test("handles API failure", async () => {
mock.onPut(`/clients/${client.client_id}`).reply(400, {
message: "oops",
});
const values = {
client_name: faker.word.sample(),
};
renderComponent(
<NotificationProvider>
<ClientEdit />
<NotificationConsumer />
</NotificationProvider>,
{ url: `/?id=${client.client_id}` },
);
await userEvent.type(
screen.getByRole("textbox", { name: ClientFormLabel.NAME }),
values.client_name,
);
await userEvent.click(screen.getByRole("button", { name: Label.SUBMIT }));
expect(document.querySelector(".p-notification--negative")).toHaveTextContent(
`${Label.ERROR}oops`,
);
});
Loading
Loading