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

CRDCDH-1160 Organization dropdown sorting #396

Merged
merged 16 commits into from
Jun 17, 2024
Merged
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
281 changes: 281 additions & 0 deletions src/components/Contexts/OrganizationListContext.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,281 @@
import React, { FC } from "react";
import { render, waitFor } from "@testing-library/react";
import { MockedProvider, MockedResponse } from "@apollo/client/testing";
import { GraphQLError } from "graphql";
import {
OrganizationProvider,
Status as OrgStatus,
useOrganizationListContext,
} from "./OrganizationListContext";
import { LIST_ORGS } from "../../graphql";

type Props = {
mocks?: MockedResponse[];
preload?: boolean;
children?: React.ReactNode;
};

const TestChild: FC = () => {
const { status, data, activeOrganizations } = useOrganizationListContext();

if (status === OrgStatus.LOADING) {
return <div>Loading...</div>;
}

return (
<div>
<div data-testid="status">{status}</div>
<ul data-testid="organization-list">
{data?.map((org, index) => (
// eslint-disable-next-line react/no-array-index-key
<li key={`organization-${index}`} data-testid={`organization-${index}`}>
{org.name}
</li>
))}
</ul>
<ul data-testid="active-organization-list">
{activeOrganizations?.map((org, index) => (
// eslint-disable-next-line react/no-array-index-key
<li key={`active-organization-${index}`} data-testid={`active-organization-${index}`}>
{org.name}
</li>
))}
</ul>
</div>
);
};

const TestParent: FC<Props> = ({ mocks, preload = true, children }: Props) => (
<MockedProvider mocks={mocks} addTypename={false}>
<OrganizationProvider preload={preload}>{children ?? <TestChild />}</OrganizationProvider>
</MockedProvider>
);

describe("OrganizationListContext > useOrganizationListContext Tests", () => {
it("should throw an exception when used outside of the OrganizationProvider", () => {
jest.spyOn(console, "error").mockImplementation(() => {});
expect(() => render(<TestChild />)).toThrow(
"OrganizationListContext cannot be used outside of the OrganizationProvider component"
);
jest.spyOn(console, "error").mockRestore();
});
});

describe("OrganizationListContext > OrganizationProvider Tests", () => {
const emptyMocks = [
{
request: {
query: LIST_ORGS,
},
result: {
data: {
listOrganizations: [],
},
},
},
];

it("should render without crashing", () => {
render(<TestParent mocks={emptyMocks} />);
});

it("should handle loading state correctly", async () => {
const { getByText } = render(<TestParent mocks={emptyMocks} />);
expect(getByText("Loading...")).toBeInTheDocument();
});

it("should load and display organization data", async () => {
const orgData = [
{ name: "Org One", status: "Active" },
{ name: "Org Two", status: "Active" },
];

const mocks = [
{
request: {
query: LIST_ORGS,
},
result: {
data: {
listOrganizations: orgData,
},
},
},
];

const { getByTestId } = render(<TestParent mocks={mocks} />);

await waitFor(() => {
expect(getByTestId("status").textContent).toEqual(OrgStatus.LOADED);
expect(getByTestId("organization-0").textContent).toEqual("Org One");
expect(getByTestId("organization-1").textContent).toEqual("Org Two");
});
});

it("should handle errors when failing to load organizations", async () => {
const mocks = [
{
request: {
query: LIST_ORGS,
},
result: {
errors: [new GraphQLError("Failed to fetch")],
},
},
];

const { getByTestId } = render(<TestParent mocks={mocks} />);

await waitFor(() => {
expect(getByTestId("status").textContent).toEqual(OrgStatus.ERROR);
});
});

it("should only show active organizations in the activeOrganizations list", async () => {
const orgData = [
{ name: "Active Org", status: "Active" },
{ name: "Inactive Org", status: "Inactive" },
];

const mocks = [
{
request: {
query: LIST_ORGS,
},
result: {
data: {
listOrganizations: orgData,
},
},
},
];

const FilteredTestParent: FC = () => (
<MockedProvider mocks={mocks} addTypename={false}>
<OrganizationProvider preload>
<TestChild />
</OrganizationProvider>
</MockedProvider>
);

const { getByTestId } = render(<FilteredTestParent />);

await waitFor(() => {
expect(getByTestId("organization-list").textContent).toContain("Active Org");
expect(getByTestId("organization-list").textContent).toContain("Inactive Org");
expect(getByTestId("active-organization-list").textContent).not.toContain("Inactive Org");
});
});

it("should sort organizations by name in ascending order", async () => {
const orgData = [
{ name: "Organization Zeta", status: "Active" },
{ name: "Organization Alpha", status: "Active" },
{ name: "Organization Delta", status: "Active" },
];

const mocks = [
{
request: {
query: LIST_ORGS,
},
result: {
data: {
listOrganizations: orgData,
},
},
},
];

const { getByTestId } = render(<TestParent mocks={mocks} />);

await waitFor(() => {
expect(getByTestId("organization-0").textContent).toEqual("Organization Alpha");
expect(getByTestId("organization-1").textContent).toEqual("Organization Delta");
expect(getByTestId("organization-2").textContent).toEqual("Organization Zeta");
});
});

it("should not execute query when preload is false", async () => {
const { queryByText } = render(
<TestParent mocks={[]} preload={false}>
<TestChild />
</TestParent>
);
await waitFor(() => {
expect(queryByText("Loading...")).not.toBeInTheDocument();
});
});

it("should handle state changes gracefully", async () => {
const orgData = [{ name: "Org Fast", status: "Active" }];
const loadingMock = {
request: { query: LIST_ORGS },
result: { data: { listOrganizations: [] } },
delay: 100,
};
const loadedMock = {
request: { query: LIST_ORGS },
result: { data: { listOrganizations: orgData } },
};

const { getByText } = render(<TestParent mocks={[loadingMock]} />);

await waitFor(() => {
expect(getByText("Loading...")).toBeInTheDocument();
});

const { getByTestId } = render(<TestParent mocks={[loadedMock]} />);

await waitFor(() => {
expect(getByTestId("status").textContent).toEqual(OrgStatus.LOADED);
expect(getByTestId("organization-0").textContent).toEqual("Org Fast");
});
});

it("should correctly update all consumers when state changes", async () => {
const orgData = [{ name: "Org Multi", status: "Active" }];

const mocks = [
{
request: { query: LIST_ORGS },
result: { data: { listOrganizations: orgData } },
},
];

const DoubleConsumer: FC = () => (
<MockedProvider mocks={mocks} addTypename={false}>
<OrganizationProvider preload>
<TestChild />
<TestChild />
</OrganizationProvider>
</MockedProvider>
);

const { getAllByTestId } = render(<DoubleConsumer />);

await waitFor(() => {
const statuses = getAllByTestId("status");
expect(statuses[0].textContent).toEqual(OrgStatus.LOADED);
expect(statuses[1].textContent).toEqual(OrgStatus.LOADED);
});
});

it("should handle partial data without crashing", async () => {
const partialDataMocks = [
{
request: { query: LIST_ORGS },
result: {
data: { listOrganizations: [{ name: "Org Partial" }] }, // Missing "status"
},
},
];

const { getByTestId } = render(<TestParent mocks={partialDataMocks} />);

await waitFor(() => {
expect(getByTestId("status").textContent).toEqual(OrgStatus.LOADED);
expect(getByTestId("organization-0").textContent).toEqual("Org Partial");
});
});
});
32 changes: 19 additions & 13 deletions src/components/Contexts/OrganizationListContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { LIST_ORGS, ListOrgsResp } from "../../graphql";
export type ContextState = {
status: Status;
data: Partial<Organization>[];
activeOrganizations: Partial<Organization>[];
};

export enum Status {
Expand All @@ -13,7 +14,11 @@ export enum Status {
ERROR = "ERROR",
}

const initialState: ContextState = { status: Status.LOADING, data: null };
const initialState: ContextState = {
status: Status.LOADING,
data: [],
activeOrganizations: [],
};

/**
* Organization List Context
Expand Down Expand Up @@ -51,7 +56,6 @@ export const useOrganizationListContext = (): ContextState => {

type ProviderProps = {
preload: boolean;
filterInactive?: boolean;
children: React.ReactNode;
};

Expand All @@ -62,11 +66,7 @@ type ProviderProps = {
* @param {ProviderProps} props
* @returns {JSX.Element} Context provider
*/
export const OrganizationProvider: FC<ProviderProps> = ({
preload,
filterInactive,
children,
}: ProviderProps) => {
export const OrganizationProvider: FC<ProviderProps> = ({ preload, children }: ProviderProps) => {
const [state, setState] = useState<ContextState>(initialState);

const { data, loading, error } = preload
Expand All @@ -78,20 +78,26 @@ export const OrganizationProvider: FC<ProviderProps> = ({

useEffect(() => {
if (loading) {
setState({ status: Status.LOADING, data: null });
setState({ status: Status.LOADING, data: [], activeOrganizations: [] });
return;
}
if (error) {
setState({ status: Status.ERROR, data: null });
setState({ status: Status.ERROR, data: [], activeOrganizations: [] });
return;
}

const sortedOrganizations = data?.listOrganizations?.sort(
(a, b) => a.name?.localeCompare(b.name)
);

const activeOrganizations = sortedOrganizations?.filter(
(org: Organization) => org.status === "Active"
);

setState({
status: Status.LOADED,
data:
data?.listOrganizations?.filter((org: Organization) =>
filterInactive ? org.status === "Active" : true
) || [],
data: sortedOrganizations || [],
activeOrganizations: activeOrganizations || [],
});
}, [loading, error, data]);

Expand Down
16 changes: 14 additions & 2 deletions src/content/dataSubmissions/Controller.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
import React from "react";
import React, { memo } from "react";
import { useParams } from "react-router-dom";
import DataSubmission from "./DataSubmission";
import ListView from "./DataSubmissionsListView";
import { OrganizationProvider } from "../../components/Contexts/OrganizationListContext";

/**
* A memoized version of OrganizationProvider
*
* @see OrganizationProvider
*/
const MemorizedProvider = memo(OrganizationProvider);

/**
* Render the correct view based on the URL
Expand All @@ -16,7 +24,11 @@ const DataSubmissionController = () => {
return <DataSubmission submissionId={submissionId} tab={tab} />;
}

return <ListView />;
return (
<MemorizedProvider preload>
<ListView />
</MemorizedProvider>
);
};

export default DataSubmissionController;
Loading
Loading