Skip to content

chore: add navigation test for workspace details page #14629

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

Merged
merged 5 commits into from
Sep 16, 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
22 changes: 19 additions & 3 deletions site/src/contexts/auth/RequireAuth.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,30 @@
import { API } from "api/api";
import { isApiError } from "api/errors";
import { Loader } from "components/Loader/Loader";
import { ProxyProvider } from "contexts/ProxyContext";
import { DashboardProvider } from "modules/dashboard/DashboardProvider";
import { ProxyProvider as ProductionProxyProvider } from "contexts/ProxyContext";
import { DashboardProvider as ProductionDashboardProvider } from "modules/dashboard/DashboardProvider";
import { type FC, useEffect } from "react";
import { Navigate, Outlet, useLocation } from "react-router-dom";
import { embedRedirect } from "utils/redirect";
import { type AuthContextValue, useAuthContext } from "./AuthProvider";

export const RequireAuth: FC = () => {
type RequireAuthProps = Readonly<{
ProxyProvider?: typeof ProductionProxyProvider;
DashboardProvider?: typeof ProductionDashboardProvider;
}>;

/**
* Wraps any component and ensures that the user has been authenticated before
* they can access the component's contents.
*
* In production, it is assumed that this component will not be called with any
* props at all. But to make testing easier, you can call this component with
* specific providers to mock them out.
*/
export const RequireAuth: FC<RequireAuthProps> = ({
DashboardProvider = ProductionDashboardProvider,
ProxyProvider = ProductionProxyProvider,
}) => {
const location = useLocation();
const { signOut, isSigningOut, isSignedOut, isSignedIn, isLoading } =
useAuthContext();
Expand Down
87 changes: 85 additions & 2 deletions site/src/pages/WorkspacePage/WorkspacePage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,19 @@ import userEvent from "@testing-library/user-event";
import * as apiModule from "api/api";
import type { TemplateVersionParameter, Workspace } from "api/typesGenerated";
import EventSourceMock from "eventsourcemock";
import {
DashboardContext,
type DashboardProvider,
} from "modules/dashboard/DashboardProvider";
import { http, HttpResponse } from "msw";
import type { FC } from "react";
import { type Location, useLocation } from "react-router-dom";
import {
MockAppearanceConfig,
MockDeploymentConfig,
MockEntitlements,
MockFailedWorkspace,
MockOrganization,
MockOutdatedWorkspace,
MockStartingWorkspace,
MockStoppedWorkspace,
Expand All @@ -18,14 +27,22 @@ import {
MockWorkspaceBuild,
MockWorkspaceBuildDelete,
} from "testHelpers/entities";
import { renderWithAuth } from "testHelpers/renderHelpers";
import {
type RenderWithAuthOptions,
renderWithAuth,
} from "testHelpers/renderHelpers";
import { server } from "testHelpers/server";
import { WorkspacePage } from "./WorkspacePage";

const { API, MissingBuildParameters } = apiModule;

type RenderWorkspacePageOptions = Omit<RenderWithAuthOptions, "route" | "path">;

// Renders the workspace page and waits for it be loaded
const renderWorkspacePage = async (workspace: Workspace) => {
const renderWorkspacePage = async (
workspace: Workspace,
options: RenderWorkspacePageOptions = {},
) => {
jest.spyOn(API, "getWorkspaceByOwnerAndName").mockResolvedValue(workspace);
jest.spyOn(API, "getTemplate").mockResolvedValueOnce(MockTemplate);
jest.spyOn(API, "getTemplateVersionRichParameters").mockResolvedValueOnce([]);
Expand All @@ -40,6 +57,7 @@ const renderWorkspacePage = async (workspace: Workspace) => {
});

renderWithAuth(<WorkspacePage />, {
...options,
route: `/@${workspace.owner_name}/${workspace.name}`,
path: "/:username/:workspace",
});
Expand Down Expand Up @@ -527,4 +545,69 @@ describe("WorkspacePage", () => {
);
});
});

describe("Navigation to other pages", () => {
it("Shows a quota link when quota budget is greater than 0. Link navigates user to /workspaces route with the URL params populated with the corresponding organization", async () => {
jest.spyOn(API, "getWorkspaceQuota").mockResolvedValueOnce({
budget: 25,
credits_consumed: 2,
});

const MockDashboardProvider: typeof DashboardProvider = ({
children,
}) => (
<DashboardContext.Provider
value={{
appearance: MockAppearanceConfig,
entitlements: MockEntitlements,
experiments: [],
organizations: [MockOrganization],
showOrganizations: true,
}}
>
{children}
</DashboardContext.Provider>
);

let destinationLocation!: Location;
const MockWorkspacesPage: FC = () => {
destinationLocation = useLocation();
return null;
};

const workspace: Workspace = {
...MockWorkspace,
organization_name: MockOrganization.name,
};

await renderWorkspacePage(workspace, {
mockAuthProviders: {
DashboardProvider: MockDashboardProvider,
},
extraRoutes: [
{
path: "/workspaces",
element: <MockWorkspacesPage />,
},
],
});

const quotaLink = await screen.findByRole<HTMLAnchorElement>("link", {
name: /\d+ credits of \d+/i,
});

const orgName = encodeURIComponent(MockOrganization.name);
expect(
quotaLink.href.endsWith(`/workspaces?filter=organization:${orgName}`),
).toBe(true);

const user = userEvent.setup();
await user.click(quotaLink);

expect(destinationLocation.pathname).toBe("/workspaces");
expect(destinationLocation.search).toBe(
`?filter=organization:${orgName}`,
);
});
});
});
6 changes: 1 addition & 5 deletions site/src/pages/WorkspacePage/WorkspaceTopbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -147,11 +147,7 @@ export const WorkspaceTopbar: FC<WorkspaceProps> = ({
<OrganizationBreadcrumb
orgName={orgDisplayName}
orgIconUrl={activeOrg?.icon}
orgPageUrl={
showOrganizations
? `/organizations/${encodeURIComponent(workspace.organization_name)}`
: undefined
}
orgPageUrl={`/organizations/${encodeURIComponent(workspace.organization_name)}`}
/>
</>
)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ const defaultFilterProps = getDefaultFilterProps<FilterProps>({
user: MockMenu,
template: MockMenu,
status: MockMenu,
organizations: MockMenu,
},
values: {
owner: MockUser.username,
Expand Down
12 changes: 10 additions & 2 deletions site/src/testHelpers/renderHelpers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@ import {
waitFor,
} from "@testing-library/react";
import { AppProviders } from "App";
import type { ProxyProvider } from "contexts/ProxyContext";
import { ThemeProvider } from "contexts/ThemeProvider";
import { RequireAuth } from "contexts/auth/RequireAuth";
import { DashboardLayout } from "modules/dashboard/DashboardLayout";
import type { DashboardProvider } from "modules/dashboard/DashboardProvider";
import { ManagementSettingsLayout } from "pages/ManagementSettingsPage/ManagementSettingsLayout";
import { TemplateSettingsLayout } from "pages/TemplateSettingsPage/TemplateSettingsLayout";
import { WorkspaceSettingsLayout } from "pages/WorkspaceSettingsPage/WorkspaceSettingsLayout";
Expand Down Expand Up @@ -83,6 +85,11 @@ export type RenderWithAuthOptions = {
nonAuthenticatedRoutes?: RouteObject[];
// In case you want to render a layout inside of it
children?: RouteObject["children"];

mockAuthProviders?: Readonly<{
DashboardProvider?: typeof DashboardProvider;
ProxyProvider?: typeof ProxyProvider;
}>;
};

export function renderWithAuth(
Expand All @@ -92,12 +99,13 @@ export function renderWithAuth(
route = "/",
extraRoutes = [],
nonAuthenticatedRoutes = [],
mockAuthProviders = {},
children,
}: RenderWithAuthOptions = {},
) {
const routes: RouteObject[] = [
{
element: <RequireAuth />,
element: <RequireAuth {...mockAuthProviders} />,
children: [{ path, element, children }, ...extraRoutes],
},
...nonAuthenticatedRoutes,
Expand All @@ -108,8 +116,8 @@ export function renderWithAuth(
);

return {
user: MockUser,
...renderResult,
user: MockUser,
};
}

Expand Down
Loading