Compare commits

..

1 Commits

Author SHA1 Message Date
Bikram Choudhury
98b19b9e32 Refactor: Extract root components architecture with comprehensive tests 2025-12-25 02:34:07 +05:30
25 changed files with 915 additions and 457 deletions

View File

@@ -17,38 +17,6 @@
position: fixed;
top: -200px;
}
body.isDarkMode .ms-Layer {
.ms-Callout-main {
background-color: @BaseHigh !important;
}
.ms-Callout-beak {
background-color: @BaseHigh !important;
}
.ms-ContextualMenu {
background-color: @BaseHigh !important;
}
.ms-Dropdown-items {
background-color: @BaseHigh !important;
}
.ms-Dropdown-item {
background-color: @BaseHigh !important;
color: @BaseLight !important;
&:hover {
background-color: @BaseMediumHigh !important;
color: @BaseLight !important;
}
&.is-selected {
background-color: @BaseMediumHigh !important;
color: @BaseLight !important;
}
}
}
html {
font-family: wf_segoe-ui_normal, "Segoe UI", "Segoe WP", Tahoma, Arial, sans-serif;
@@ -161,65 +129,6 @@ body {
}
}
&.isDarkMode .accountSwitchContextualMenu {
background-color: @BaseHigh;
.ms-Callout-main {
background-color: @BaseHigh;
}
.ms-ContextualMenu-item {
background-color: @BaseHigh;
}
.ms-Dropdown {
.ms-Dropdown-title {
background-color: @BaseDark;
color: @BaseLight;
border-color: @BaseMediumHigh;
}
.ms-Dropdown-caretDownWrapper {
color: @BaseLight;
}
&:hover .ms-Dropdown-title {
background-color: @BaseHigh;
color: @BaseLight;
border-color: @BaseMedium;
}
}
.ms-Label {
color: @BaseLight;
}
}
&.isDarkMode .ms-Dropdown-callout {
.ms-Callout-main {
background-color: @BaseHigh;
}
.ms-Dropdown-items {
background-color: @BaseHigh;
}
.ms-Dropdown-item {
background-color: @BaseHigh;
color: @BaseLight;
&:hover {
background-color: @BaseMediumHigh;
color: @BaseLight;
}
&.is-selected {
background-color: @BaseMediumHigh;
color: @BaseLight;
}
}
}
.fixedleftpane {
background: @BaseLow;
height: 100vh;

View File

@@ -1,4 +1,5 @@
import React, { useEffect } from "react";
import { SidePanel } from "../../Explorer/Panes/PanelContainerComponent";
import CopyJobCommandBar from "./CommandBar/CopyJobCommandBar";
import "./containerCopyStyles.less";
import { MonitorCopyJobsRefState } from "./MonitorCopyJobs/MonitorCopyJobRefState";
@@ -16,6 +17,7 @@ const ContainerCopyPanel: React.FC<ContainerCopyProps> = ({ explorer }) => {
<div id="containerCopyWrapper" className="flexContainer hideOverflows">
<CopyJobCommandBar explorer={explorer} />
<MonitorCopyJobs ref={monitorCopyJobsRef} explorer={explorer} />
<SidePanel />
</div>
);
};

View File

@@ -187,7 +187,7 @@ export const PartitionKeyComponent: React.FC<PartitionKeyComponentProps> = ({
<Text styles={textSubHeadingStyle}>Current {partitionKeyName.toLowerCase()}</Text>
<Text styles={textSubHeadingStyle}>Partitioning</Text>
</Stack>
<Stack tokens={{ childrenGap: 5 }} data-test="partition-key-values">
<Stack tokens={{ childrenGap: 5 }}>
<Text styles={textSubHeadingStyle1}>{partitionKeyValue}</Text>
<Text styles={textSubHeadingStyle1}>
{isHierarchicalPartitionedContainer() ? "Hierarchical" : "Non-hierarchical"}
@@ -199,7 +199,6 @@ export const PartitionKeyComponent: React.FC<PartitionKeyComponentProps> = ({
{!isReadOnly && (
<>
<MessageBar
data-test="partition-key-warning"
messageBarType={MessageBarType.warning}
messageBarIconProps={{ iconName: "WarningSolid", className: "messageBarWarningIcon" }}
styles={darkThemeMessageBarStyles}
@@ -221,7 +220,6 @@ export const PartitionKeyComponent: React.FC<PartitionKeyComponentProps> = ({
</Text>
{configContext.platform !== Platform.Emulator && (
<PrimaryButton
data-test="change-partition-key-button"
styles={{ root: { width: "fit-content" } }}
text="Change"
onClick={startPartitionkeyChangeWorkflow}

View File

@@ -78,7 +78,6 @@ exports[`PartitionKeyComponent renders default component and matches snapshot 1`
</Text>
</Stack>
<Stack
data-test="partition-key-values"
tokens={
{
"childrenGap": 5,
@@ -109,7 +108,6 @@ exports[`PartitionKeyComponent renders default component and matches snapshot 1`
</Stack>
</Stack>
<StyledMessageBar
data-test="partition-key-warning"
messageBarIconProps={
{
"className": "messageBarWarningIcon",
@@ -162,7 +160,6 @@ exports[`PartitionKeyComponent renders default component and matches snapshot 1`
To change the partition key, a new destination container must be created or an existing destination container selected. Data will then be copied to the destination container.
</Text>
<CustomizedPrimaryButton
data-test="change-partition-key-button"
onClick={[Function]}
styles={
{
@@ -240,7 +237,6 @@ exports[`PartitionKeyComponent renders read-only component and matches snapshot
</Text>
</Stack>
<Stack
data-test="partition-key-values"
tokens={
{
"childrenGap": 5,

View File

@@ -208,7 +208,7 @@ export const ChangePartitionKeyPane: React.FC<ChangePartitionKeyPaneProps> = ({
</div>
</Stack>
{createNewContainer ? (
<Stack data-test="create-new-container-form">
<Stack>
<MessageBar>All configurations except for unique keys will be copied from the source container</MessageBar>
<Stack className="panelGroupSpacing">
<Stack horizontal>
@@ -230,7 +230,6 @@ export const ChangePartitionKeyPane: React.FC<ChangePartitionKeyPaneProps> = ({
</TooltipHost>
</Stack>
<input
data-test="new-container-id-input"
name="collectionId"
id="collectionId"
type="text"
@@ -272,7 +271,6 @@ export const ChangePartitionKeyPane: React.FC<ChangePartitionKeyPaneProps> = ({
<input
type="text"
data-test="new-container-partition-key-input"
id="addCollection-partitionKeyValue"
aria-required
required
@@ -306,7 +304,6 @@ export const ChangePartitionKeyPane: React.FC<ChangePartitionKeyPaneProps> = ({
type="text"
id="addCollection-partitionKeyValue"
key={`addCollection-partitionKeyValue_${index}`}
data-test={`new-container-sub-partition-key-input-${index}`}
aria-required
required
size={40}
@@ -330,8 +327,6 @@ export const ChangePartitionKeyPane: React.FC<ChangePartitionKeyPaneProps> = ({
}}
/>
<IconButton
data-test={`remove-sub-partition-key-button-${index}`}
ariaLabel="Remove hierarchical partition key"
iconProps={{ iconName: "Delete" }}
style={{ height: 27 }}
onClick={() => {
@@ -344,7 +339,6 @@ export const ChangePartitionKeyPane: React.FC<ChangePartitionKeyPaneProps> = ({
})}
<Stack className="panelGroupSpacing">
<DefaultButton
data-test="add-sub-partition-key-button"
styles={{ root: { padding: 0, width: 200, height: 30 }, label: { fontSize: 12 } }}
disabled={subPartitionKeys.length >= Constants.BackendDefaults.maxNumMultiHashPartition}
onClick={() => setSubPartitionKeys([...subPartitionKeys, ""])}
@@ -352,11 +346,7 @@ export const ChangePartitionKeyPane: React.FC<ChangePartitionKeyPaneProps> = ({
Add hierarchical partition key
</DefaultButton>
{subPartitionKeys.length > 0 && (
<Text
data-test="hierarchical-partitioning-info-text"
variant="small"
style={{ color: "var(--colorNeutralForeground1)" }}
>
<Text variant="small" style={{ color: "var(--colorNeutralForeground1)" }}>
<Icon iconName="InfoSolid" className="removeIcon" tabIndex={0} /> This feature allows you to
partition your data with up to three levels of keys for better data distribution. Requires .NET V3,
Java V4 SDK, or preview JavaScript V3 SDK.{" "}
@@ -369,7 +359,7 @@ export const ChangePartitionKeyPane: React.FC<ChangePartitionKeyPaneProps> = ({
</Stack>
</Stack>
) : (
<Stack data-test="use-existing-container-form">
<Stack>
<Stack horizontal>
<span className="mandatoryStar">*&nbsp;</span>
<Text className="panelTextBold" variant="small">
@@ -400,7 +390,6 @@ export const ChangePartitionKeyPane: React.FC<ChangePartitionKeyPaneProps> = ({
}}
defaultSelectedKey={targetCollectionId}
responsiveMode={999}
ariaLabel="Existing Containers"
/>
</Stack>
)}

View File

@@ -1,6 +1,5 @@
import { initializeIcons } from "@fluentui/react";
import { useBoolean } from "@fluentui/react-hooks";
import { MessageTypes } from "Contracts/MessageTypes";
import { AadAuthorizationFailure } from "Platform/Hosted/Components/AadAuthorizationFailure";
import * as React from "react";
import { render } from "react-dom";
@@ -22,33 +21,9 @@ import "./Shared/appInsights";
import { useAADAuth } from "./hooks/useAADAuth";
import { useConfig } from "./hooks/useConfig";
import { useTokenMetadata } from "./hooks/usePortalAccessToken";
import { THEME_MODE_DARK, useThemeStore } from "./hooks/useTheme";
initializeIcons();
if (typeof window !== "undefined") {
window.addEventListener("message", (event) => {
const messageData = event.data?.data || event.data;
const messageType = messageData?.type;
if (messageType === MessageTypes.UpdateTheme) {
const themeData = messageData?.params?.theme || messageData?.theme;
if (themeData && themeData.mode !== undefined) {
const isDark = themeData.mode === THEME_MODE_DARK;
useThemeStore.setState({
isDarkMode: isDark,
themeMode: themeData.mode,
});
if (isDark) {
document.body.classList.add("isDarkMode");
} else {
document.body.classList.remove("isDarkMode");
}
}
}
});
}
const App: React.FunctionComponent = () => {
// For handling encrypted portal tokens sent via query paramter
const params = new URLSearchParams(window.location.search);

View File

@@ -2,18 +2,9 @@
import "./ReactDevTools";
// CSS Dependencies
import { initializeIcons, loadTheme, useTheme } from "@fluentui/react";
import { FluentProvider, makeStyles, webDarkTheme, webLightTheme } from "@fluentui/react-components";
import { Platform } from "ConfigContext";
import ContainerCopyPanel from "Explorer/ContainerCopy/ContainerCopyPanel";
import Explorer from "Explorer/Explorer";
import { QuickstartCarousel } from "Explorer/Quickstart/QuickstartCarousel";
import { MongoQuickstartTutorial } from "Explorer/Quickstart/Tutorials/MongoQuickstartTutorial";
import { SQLQuickstartTutorial } from "Explorer/Quickstart/Tutorials/SQLQuickstartTutorial";
import { userContext } from "UserContext";
import { initializeIcons } from "@fluentui/react";
import "allotment/dist/style.css";
import "bootstrap/dist/css/bootstrap.css";
import { useCarousel } from "hooks/useCarousel";
import React from "react";
import ReactDOM from "react-dom";
import "../externals/jquery-ui.min.css";
@@ -24,13 +15,8 @@ import "../externals/jquery.dataTables.min.css";
import "../externals/jquery.typeahead.min.css";
import "../externals/jquery.typeahead.min.js";
// Image Dependencies
import { SidePanel } from "Explorer/Panes/PanelContainerComponent";
import { QueryCopilotCarousel } from "Explorer/QueryCopilot/CopilotCarousel";
import { SidebarContainer } from "Explorer/Sidebar";
import { KeyboardShortcutRoot } from "KeyboardShortcuts";
import "allotment/dist/style.css";
import "../images/CosmosDB_rgb_ui_lighttheme.ico";
import hdeConnectImage from "../images/HdeConnectCosmosDB.svg";
import "../images/favicon.ico";
import "../less/TableStyles/CustomizeColumns.less";
import "../less/TableStyles/EntityEditor.less";
@@ -42,178 +28,29 @@ import "../less/infobox.less";
import "../less/menus.less";
import "../less/messagebox.less";
import "../less/resourceTree.less";
import * as StyleConstants from "./Common/StyleConstants";
import "./Explorer/Controls/Accordion/AccordionComponent.less";
import "./Explorer/Controls/CollapsiblePanel/CollapsiblePanelComponent.less";
import { Dialog } from "./Explorer/Controls/Dialog";
import "./Explorer/Controls/ErrorDisplayComponent/ErrorDisplayComponent.less";
import "./Explorer/Controls/JsonEditor/JsonEditorComponent.less";
import "./Explorer/Controls/Notebook/NotebookTerminalComponent.less";
import "./Explorer/Controls/TreeComponent/treeComponent.less";
import { ErrorBoundary } from "./Explorer/ErrorBoundary";
import "./Explorer/Graph/GraphExplorerComponent/graphExplorer.less";
import "./Explorer/Menus/CommandBar/CommandBarComponent.less";
import { CommandBar } from "./Explorer/Menus/CommandBar/CommandBarComponentAdapter";
import "./Explorer/Menus/CommandBar/ConnectionStatusComponent.less";
import "./Explorer/Menus/CommandBar/MemoryTrackerComponent.less";
import "./Explorer/Menus/NotificationConsole/NotificationConsole.less";
import { NotificationConsole } from "./Explorer/Menus/NotificationConsole/NotificationConsoleComponent";
import "./Explorer/Panes/PanelComponent.less";
import "./Explorer/SplashScreen/SplashScreen.less";
import "./Libs/jquery";
import MetricScenario from "./Metrics/MetricEvents";
import { MetricScenarioProvider, useMetricScenario } from "./Metrics/MetricScenarioProvider";
import { ApplicationMetricPhase } from "./Metrics/ScenarioConfig";
import { useInteractive } from "./Metrics/useMetricPhases";
import { appThemeFabric } from "./Platform/Fabric/FabricTheme";
import { MetricScenarioProvider } from "./Metrics/MetricScenarioProvider";
import Root from "./RootComponents/Root";
import "./Shared/appInsights";
import { useConfig } from "./hooks/useConfig";
import { useKnockoutExplorer } from "./hooks/useKnockoutExplorer";
import { useThemeStore } from "./hooks/useTheme";
import "./less/DarkModeMenus.less";
import "./less/ThemeSystem.less";
// Initialize icons before React is loaded
initializeIcons(undefined, { disableWarnings: true });
const useStyles = makeStyles({
root: {
height: "100vh",
width: "100vw",
backgroundColor: "var(--colorNeutralBackground1)",
color: "var(--colorNeutralForeground1)",
},
});
const App = (): JSX.Element => {
const config = useConfig();
const styles = useStyles();
// theme is used for application-wide styling
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const theme = useTheme();
// Load Fabric theme and styles only once when platform is Fabric
React.useEffect(() => {
if (config?.platform === Platform.Fabric) {
loadTheme(appThemeFabric);
import("../less/documentDBFabric.less");
}
StyleConstants.updateStyles();
}, [config?.platform]);
const explorer = useKnockoutExplorer(config?.platform);
// Scenario-based health tracking: start ApplicationLoad and complete phases.
const { startScenario, completePhase } = useMetricScenario();
React.useEffect(() => {
startScenario(MetricScenario.ApplicationLoad);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
React.useEffect(() => {
if (explorer) {
completePhase(MetricScenario.ApplicationLoad, ApplicationMetricPhase.ExplorerInitialized);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [explorer]);
if (!explorer) {
return <LoadingExplorer />;
}
return (
<div id="Main" className={styles.root}>
<KeyboardShortcutRoot>
<div className="flexContainer" aria-hidden="false">
{userContext.features.enableContainerCopy && userContext.apiType === "SQL" ? (
<>
<ContainerCopyPanel explorer={explorer} />
<SidePanel />
</>
) : (
<DivExplorer explorer={explorer} />
)}
</div>
</KeyboardShortcutRoot>
</div>
);
};
const DivExplorer: React.FC<{ explorer: Explorer }> = ({ explorer }) => {
const isCarouselOpen = useCarousel((state) => state.shouldOpen);
const isCopilotCarouselOpen = useCarousel((state) => state.showCopilotCarousel);
useInteractive(MetricScenario.ApplicationLoad);
return (
<div
className="flexContainer"
style={{
flex: 1,
display: "flex",
flexDirection: "column",
backgroundColor: "var(--colorNeutralBackground1)",
color: "var(--colorNeutralForeground1)",
}}
aria-hidden="false"
data-test="DataExplorerRoot"
>
<div
id="divExplorer"
className="flexContainer hideOverflows"
style={{
flex: 1,
display: "flex",
flexDirection: "column",
backgroundColor: "var(--colorNeutralBackground1)",
color: "var(--colorNeutralForeground1)",
}}
>
<div id="freeTierTeachingBubble"> </div>
<CommandBar container={explorer} />
<SidebarContainer explorer={explorer} />
<div
className="dataExplorerErrorConsoleContainer"
role="contentinfo"
aria-label="Notification console"
id="explorerNotificationConsole"
style={{
backgroundColor: "var(--colorNeutralBackground1)",
color: "var(--colorNeutralForeground1)",
}}
>
<NotificationConsole />
</div>
</div>
<SidePanel />
<Dialog />
{<QuickstartCarousel isOpen={isCarouselOpen} />}
{<SQLQuickstartTutorial />}
{<MongoQuickstartTutorial />}
{<QueryCopilotCarousel isOpen={isCopilotCarouselOpen} explorer={explorer} />}
</div>
);
};
const Root: React.FC = () => {
// Use React state to track isDarkMode and subscribe to changes
const [isDarkMode, setIsDarkMode] = React.useState(useThemeStore.getState().isDarkMode);
const currentTheme = isDarkMode ? webDarkTheme : webLightTheme;
// Subscribe to theme changes
React.useEffect(() => {
return useThemeStore.subscribe((state) => {
setIsDarkMode(state.isDarkMode);
});
}, []);
return (
<ErrorBoundary>
<FluentProvider theme={currentTheme}>
<App />
</FluentProvider>
</ErrorBoundary>
);
};
const mainElement = document.getElementById("Main");
if (mainElement) {
ReactDOM.render(
@@ -223,24 +60,3 @@ if (mainElement) {
mainElement,
);
}
function LoadingExplorer(): JSX.Element {
const styles = useStyles();
return (
<div className={styles.root}>
<div className="splashLoaderContainer">
<div className="splashLoaderContentContainer">
<p className="connectExplorerContent">
<img src={hdeConnectImage} alt="Azure Cosmos DB" />
</p>
<p className="splashLoaderTitle" id="explorerLoadingStatusTitle">
Welcome to Azure Cosmos DB
</p>
<p className="splashLoaderText" id="explorerLoadingStatusText" role="alert">
Connecting...
</p>
</div>
</div>
</div>
);
}

View File

@@ -3,7 +3,7 @@ import MetricScenario from "./MetricEvents";
import { MetricPhase } from "./ScenarioConfig";
import { scenarioMonitor } from "./ScenarioMonitor";
interface MetricScenarioContextValue {
export interface MetricScenarioContextValue {
startScenario: (scenario: MetricScenario) => void;
startPhase: (scenario: MetricScenario, phase: MetricPhase) => void;
completePhase: (scenario: MetricScenario, phase: MetricPhase) => void;

View File

@@ -1,7 +1,7 @@
// TODO: Renable this rule for the file or turn it off everywhere
/* eslint-disable react/display-name */
import { DefaultButton, IButtonStyles, IContextualMenuItem, IContextualMenuProps } from "@fluentui/react";
import { DefaultButton, IButtonStyles, IContextualMenuItem } from "@fluentui/react";
import * as React from "react";
import { FunctionComponent, useEffect, useState } from "react";
import { StyleConstants } from "../../../Common/StyleConstants";
@@ -92,16 +92,14 @@ export const AccountSwitcher: FunctionComponent<Props> = ({ armToken, setDatabas
},
];
const menuProps: IContextualMenuProps = {
directionalHintFixed: true,
className: "accountSwitchContextualMenu",
items,
};
return (
<DefaultButton
text={buttonText}
menuProps={menuProps}
menuProps={{
directionalHintFixed: true,
className: "accountSwitchContextualMenu",
items,
}}
styles={buttonStyles}
className="accountSwitchButton"
id="accountSwitchButton"

View File

@@ -31,6 +31,9 @@ export const SwitchAccount: FunctionComponent<Props> = ({
}}
defaultSelectedKey={selectedAccount?.name}
placeholder={accounts && accounts.length === 0 ? "No Accounts Found" : "Select an Account"}
styles={{
callout: "accountSwitchAccountDropdownMenu",
}}
/>
);
};

View File

@@ -30,6 +30,9 @@ export const SwitchSubscription: FunctionComponent<Props> = ({
}}
defaultSelectedKey={selectedSubscription?.subscriptionId}
placeholder={subscriptions && subscriptions.length === 0 ? "No Subscriptions Found" : "Select a Subscription"}
styles={{
callout: "accountSwitchSubscriptionDropdownMenu",
}}
/>
);
};

View File

@@ -0,0 +1,317 @@
import { loadTheme } from "@fluentui/react";
import "@testing-library/jest-dom";
import { render, screen, waitFor } from "@testing-library/react";
import React from "react";
import { updateStyles } from "../Common/StyleConstants";
import { Platform } from "../ConfigContext";
import { useConfig } from "../hooks/useConfig";
import { useKnockoutExplorer } from "../hooks/useKnockoutExplorer";
import { MetricScenarioContextValue, useMetricScenario } from "../Metrics/MetricScenarioProvider";
import App from "./App";
const mockUserContext = {
features: { enableContainerCopy: false },
apiType: "SQL",
};
jest.mock("@fluentui/react", () => ({
loadTheme: jest.fn(),
makeStyles: jest.fn(() => () => ({
root: "mock-app-root-class",
})),
MessageBarType: {
error: "error",
warning: "warning",
info: "info",
success: "success",
},
SpinnerSize: {
xSmall: "xSmall",
small: "small",
medium: "medium",
large: "large",
},
}));
jest.mock("../Common/StyleConstants", () => ({
StyleConstants: {
BaseMedium: "#000000",
AccentMediumHigh: "#0078d4",
AccentMedium: "#106ebe",
AccentLight: "#deecf9",
AccentAccentExtra: "#0078d4",
FabricAccentMediumHigh: "#0078d4",
FabricAccentMedium: "#106ebe",
FabricAccentLight: "#deecf9",
PortalAccentMediumHigh: "#0078d4",
PortalAccentMedium: "#106ebe",
PortalAccentLight: "#deecf9",
},
updateStyles: jest.fn(),
}));
jest.mock("./LoadingExplorer", () => {
const MockLoadingExplorer = () => {
return <div data-testid="mock-loading-explorer">Loading Explorer</div>;
};
MockLoadingExplorer.displayName = "MockLoadingExplorer";
return MockLoadingExplorer;
});
jest.mock("./ExplorerContainer", () => {
const MockExplorerContainer = ({ explorer }: { explorer: unknown }) => {
return (
<div data-testid="mock-explorer-container">Explorer Container - {explorer ? "with explorer" : "no explorer"}</div>
);
};
MockExplorerContainer.displayName = "MockExplorerContainer";
return MockExplorerContainer;
});
jest.mock("../Explorer/ContainerCopy/ContainerCopyPanel", () => {
const MockContainerCopyPanel = ({ explorer }: { explorer: unknown }) => {
return (
<div data-testid="mock-container-copy-panel">
Container Copy Panel - {explorer ? "with explorer" : "no explorer"}
</div>
);
};
MockContainerCopyPanel.displayName = "MockContainerCopyPanel";
return MockContainerCopyPanel;
});
jest.mock("../KeyboardShortcuts", () => ({
KeyboardShortcutRoot: ({ children }: { children: React.ReactNode }) => (
<div data-testid="mock-keyboard-shortcut-root">{children}</div>
),
}));
jest.mock("../UserContext", () => ({
get userContext() {
return mockUserContext;
},
}));
const mockConfig = {
platform: Platform.Portal,
};
const mockExplorer = {
id: "test-explorer",
name: "Test Explorer",
};
jest.mock("../hooks/useConfig", () => ({
useConfig: jest.fn(() => mockConfig),
}));
jest.mock("../hooks/useKnockoutExplorer", () => ({
useKnockoutExplorer: jest.fn(),
}));
jest.mock("../Metrics/MetricScenarioProvider", () => ({
useMetricScenario: jest.fn(() => ({
startScenario: jest.fn(),
completePhase: jest.fn(),
})),
}));
jest.mock("../Metrics/MetricEvents", () => ({
__esModule: true,
default: {
ApplicationLoad: "ApplicationLoad",
},
}));
jest.mock("../Metrics/ScenarioConfig", () => ({
ApplicationMetricPhase: {
ExplorerInitialized: "ExplorerInitialized",
},
CommonMetricPhase: {
Interactive: "Interactive",
},
}));
jest.mock("../Platform/Fabric/FabricTheme", () => ({
appThemeFabric: { name: "fabric-theme" },
}));
describe("App", () => {
afterEach(() => {
jest.clearAllMocks();
mockUserContext.features = { enableContainerCopy: false };
mockUserContext.apiType = "SQL";
});
let mockStartScenario: jest.Mock;
let mockCompletePhase: jest.Mock;
let mockUseKnockoutExplorer: jest.Mock;
let mockUseConfig: jest.Mock;
let mockLoadTheme: jest.Mock;
let mockUpdateStyles: jest.Mock;
beforeEach(() => {
jest.clearAllMocks();
mockStartScenario = jest.fn();
mockCompletePhase = jest.fn();
mockUseKnockoutExplorer = jest.mocked(useKnockoutExplorer);
mockUseConfig = jest.mocked(useConfig);
mockLoadTheme = jest.mocked(loadTheme);
mockUpdateStyles = jest.mocked(updateStyles);
const mockUseMetricScenario = jest.mocked(useMetricScenario);
mockUseMetricScenario.mockReturnValue({
startScenario: mockStartScenario,
completePhase: mockCompletePhase
} as unknown as MetricScenarioContextValue);
mockUseConfig.mockReturnValue(mockConfig);
mockUseKnockoutExplorer.mockReturnValue(null);
});
test("should render loading explorer when explorer is not ready", () => {
mockUseKnockoutExplorer.mockReturnValue(null);
render(<App />);
expect(screen.getByTestId("mock-loading-explorer")).toBeInTheDocument();
expect(screen.queryByTestId("mock-explorer-container")).not.toBeInTheDocument();
});
test("should render explorer container when explorer is ready", () => {
mockUseKnockoutExplorer.mockReturnValue(mockExplorer);
render(<App />);
expect(screen.getByTestId("mock-explorer-container")).toBeInTheDocument();
expect(screen.queryByTestId("mock-loading-explorer")).not.toBeInTheDocument();
});
test("should start metric scenario on mount", () => {
render(<App />);
expect(mockStartScenario).toHaveBeenCalledWith("ApplicationLoad");
expect(mockStartScenario).toHaveBeenCalledTimes(1);
});
test("should complete metric phase when explorer is initialized", async () => {
const { rerender } = render(<App />);
expect(mockCompletePhase).not.toHaveBeenCalled();
mockUseKnockoutExplorer.mockReturnValue(mockExplorer);
rerender(<App />);
await waitFor(() => {
expect(mockCompletePhase).toHaveBeenCalledWith("ApplicationLoad", "ExplorerInitialized");
});
});
test("should load fabric theme when platform is Fabric", () => {
const fabricConfig = { platform: Platform.Fabric };
mockUseConfig.mockReturnValue(fabricConfig);
mockUseKnockoutExplorer.mockReturnValue(mockExplorer);
render(<App />);
expect(mockLoadTheme).toHaveBeenCalledWith({ name: "fabric-theme" });
});
test("should not load fabric theme when platform is not Fabric", () => {
const portalConfig = { platform: Platform.Portal };
mockUseConfig.mockReturnValue(portalConfig);
render(<App />);
expect(mockLoadTheme).not.toHaveBeenCalled();
});
test("should always call updateStyles", () => {
render(<App />);
expect(mockUpdateStyles).toHaveBeenCalled();
});
test("should render container copy panel when container copy is enabled and API is SQL", () => {
mockUserContext.features = { enableContainerCopy: true };
mockUserContext.apiType = "SQL";
mockUseKnockoutExplorer.mockReturnValue(mockExplorer);
render(<App />);
expect(screen.getByTestId("mock-container-copy-panel")).toBeInTheDocument();
expect(screen.queryByTestId("mock-explorer-container")).not.toBeInTheDocument();
});
test("should render explorer container when container copy is disabled", () => {
mockUserContext.features = { enableContainerCopy: false };
mockUserContext.apiType = "SQL";
mockUseKnockoutExplorer.mockReturnValue(mockExplorer);
render(<App />);
expect(screen.getByTestId("mock-explorer-container")).toBeInTheDocument();
expect(screen.queryByTestId("mock-container-copy-panel")).not.toBeInTheDocument();
});
test("should render explorer container when API is not SQL", () => {
mockUserContext.features = { enableContainerCopy: true };
mockUserContext.apiType = "MongoDB";
mockUseKnockoutExplorer.mockReturnValue(mockExplorer);
render(<App />);
expect(screen.getByTestId("mock-explorer-container")).toBeInTheDocument();
expect(screen.queryByTestId("mock-container-copy-panel")).not.toBeInTheDocument();
});
test("should have correct DOM structure", () => {
mockUseKnockoutExplorer.mockReturnValue(mockExplorer);
const { container } = render(<App />);
const mainDiv = container.querySelector("#Main");
expect(mainDiv).toBeInTheDocument();
expect(mainDiv).toHaveClass("mock-app-root-class");
expect(screen.getByTestId("mock-keyboard-shortcut-root")).toBeInTheDocument();
const flexContainer = container.querySelector(".flexContainer");
expect(flexContainer).toBeInTheDocument();
expect(flexContainer).toHaveAttribute("aria-hidden", "false");
});
test("should handle config changes for Fabric platform", () => {
const { rerender } = render(<App />);
const fabricConfig = { platform: Platform.Fabric };
mockUseConfig.mockReturnValue(fabricConfig);
rerender(<App />);
expect(mockLoadTheme).toHaveBeenCalledWith({ name: "fabric-theme" });
});
test("should pass explorer to child components", () => {
mockUseKnockoutExplorer.mockReturnValue(mockExplorer);
render(<App />);
expect(screen.getByText("Explorer Container - with explorer")).toBeInTheDocument();
});
test("should handle null config gracefully", () => {
mockUseConfig.mockReturnValue(null);
mockUseKnockoutExplorer.mockReturnValue(mockExplorer);
expect(() => render(<App />)).not.toThrow();
expect(mockLoadTheme).not.toHaveBeenCalled();
expect(mockUpdateStyles).toHaveBeenCalled();
});
});

View File

@@ -0,0 +1,73 @@
import { loadTheme, makeStyles } from "@fluentui/react";
import React from "react";
import * as StyleConstants from "../Common/StyleConstants";
import { Platform } from "../ConfigContext";
import ContainerCopyPanel from "../Explorer/ContainerCopy/ContainerCopyPanel";
import { useConfig } from "../hooks/useConfig";
import { useKnockoutExplorer } from "../hooks/useKnockoutExplorer";
import { KeyboardShortcutRoot } from "../KeyboardShortcuts";
import MetricScenario from "../Metrics/MetricEvents";
import { useMetricScenario } from "../Metrics/MetricScenarioProvider";
import { ApplicationMetricPhase } from "../Metrics/ScenarioConfig";
import { appThemeFabric } from "../Platform/Fabric/FabricTheme";
import { userContext } from "../UserContext";
import ExplorerContainer from "./ExplorerContainer";
import LoadingExplorer from "./LoadingExplorer";
const useStyles = makeStyles({
root: {
height: "100vh",
width: "100vw",
backgroundColor: "var(--colorNeutralBackground1)",
color: "var(--colorNeutralForeground1)",
},
});
const App = (): JSX.Element => {
const config = useConfig();
const styles = useStyles();
// Load Fabric theme and styles only once when platform is Fabric
React.useEffect(() => {
if (config?.platform === Platform.Fabric) {
loadTheme(appThemeFabric);
import("../../less/documentDBFabric.less");
}
StyleConstants.updateStyles();
}, [config?.platform]);
const explorer = useKnockoutExplorer(config?.platform);
// Scenario-based health tracking: start ApplicationLoad and complete phases.
const { startScenario, completePhase } = useMetricScenario();
React.useEffect(() => {
startScenario(MetricScenario.ApplicationLoad);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
React.useEffect(() => {
if (explorer) {
completePhase(MetricScenario.ApplicationLoad, ApplicationMetricPhase.ExplorerInitialized);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [explorer]);
if (!explorer) {
return <LoadingExplorer />;
}
return (
<div id="Main" className={styles.root}>
<KeyboardShortcutRoot>
<div className="flexContainer" aria-hidden="false">
{userContext.features.enableContainerCopy && userContext.apiType === "SQL" ? (
<ContainerCopyPanel explorer={explorer} />
) : (
<ExplorerContainer explorer={explorer} />
)}
</div>
</KeyboardShortcutRoot>
</div>
);
};
export default App;

View File

@@ -0,0 +1,183 @@
import "@testing-library/jest-dom";
import { render, screen } from "@testing-library/react";
import React from "react";
import Explorer from "../Explorer/Explorer";
import { useCarousel } from "../hooks/useCarousel";
import { useInteractive } from "../Metrics/useMetricPhases";
import ExplorerContainer from "./ExplorerContainer";
jest.mock("../Explorer/Controls/Dialog", () => ({
Dialog: () => <div data-testid="mock-dialog">Dialog</div>,
}));
jest.mock("../Explorer/Menus/CommandBar/CommandBarComponentAdapter", () => ({
CommandBar: ({ container }: { container: Explorer }) => (
<div data-testid="mock-command-bar">CommandBar - {container ? "with explorer" : "no explorer"}</div>
),
}));
jest.mock("../Explorer/Menus/NotificationConsole/NotificationConsoleComponent", () => ({
NotificationConsole: () => <div data-testid="mock-notification-console">NotificationConsole</div>,
}));
jest.mock("../Explorer/Panes/PanelContainerComponent", () => ({
SidePanel: () => <div data-testid="mock-side-panel">SidePanel</div>,
}));
jest.mock("../Explorer/QueryCopilot/CopilotCarousel", () => ({
QueryCopilotCarousel: ({ isOpen, explorer }: { isOpen: boolean; explorer: Explorer }) => (
<div data-testid="mock-copilot-carousel">
CopilotCarousel - {isOpen ? "open" : "closed"} - {explorer ? "with explorer" : "no explorer"}
</div>
),
}));
jest.mock("../Explorer/Quickstart/QuickstartCarousel", () => ({
QuickstartCarousel: ({ isOpen }: { isOpen: boolean }) => (
<div data-testid="mock-quickstart-carousel">QuickstartCarousel - {isOpen ? "open" : "closed"}</div>
),
}));
jest.mock("../Explorer/Quickstart/Tutorials/MongoQuickstartTutorial", () => ({
MongoQuickstartTutorial: () => <div data-testid="mock-mongo-tutorial">MongoQuickstartTutorial</div>,
}));
jest.mock("../Explorer/Quickstart/Tutorials/SQLQuickstartTutorial", () => ({
SQLQuickstartTutorial: () => <div data-testid="mock-sql-tutorial">SQLQuickstartTutorial</div>,
}));
jest.mock("../Explorer/Sidebar", () => ({
SidebarContainer: ({ explorer }: { explorer: Explorer }) => (
<div data-testid="mock-sidebar-container">SidebarContainer - {explorer ? "with explorer" : "no explorer"}</div>
),
}));
jest.mock("../hooks/useCarousel", () => ({
useCarousel: jest.fn((selector) => {
if (selector.toString().includes("shouldOpen")) {
return true;
}
if (selector.toString().includes("showCopilotCarousel")) {
return false;
}
return false;
}),
}));
jest.mock("../Metrics/useMetricPhases", () => ({
useInteractive: jest.fn(),
}));
jest.mock("../Metrics/MetricEvents", () => ({
__esModule: true,
default: {
ApplicationLoad: "ApplicationLoad",
},
}));
describe("ExplorerContainer", () => {
let mockExplorer: Explorer;
beforeEach(() => {
mockExplorer = {
id: "test-explorer",
name: "Test Explorer",
} as unknown as Explorer;
jest.clearAllMocks();
});
test("should render explorer container with all components", () => {
const { container } = render(<ExplorerContainer explorer={mockExplorer} />);
const mainContainer = container.querySelector('[data-test="DataExplorerRoot"]');
expect(mainContainer).toBeInTheDocument();
expect(mainContainer).toHaveClass("flexContainer");
expect(screen.getByTestId("mock-command-bar")).toBeInTheDocument();
expect(screen.getByTestId("mock-sidebar-container")).toBeInTheDocument();
expect(screen.getByTestId("mock-notification-console")).toBeInTheDocument();
expect(screen.getByTestId("mock-side-panel")).toBeInTheDocument();
expect(screen.getByTestId("mock-dialog")).toBeInTheDocument();
expect(screen.getByTestId("mock-quickstart-carousel")).toBeInTheDocument();
expect(screen.getByTestId("mock-sql-tutorial")).toBeInTheDocument();
expect(screen.getByTestId("mock-mongo-tutorial")).toBeInTheDocument();
expect(screen.getByTestId("mock-copilot-carousel")).toBeInTheDocument();
});
test("should pass explorer to components that need it", () => {
render(<ExplorerContainer explorer={mockExplorer} />);
expect(screen.getByText("CommandBar - with explorer")).toBeInTheDocument();
expect(screen.getByText("SidebarContainer - with explorer")).toBeInTheDocument();
expect(screen.getByText("CopilotCarousel - closed - with explorer")).toBeInTheDocument();
});
test("should have correct DOM structure", () => {
const { container } = render(<ExplorerContainer explorer={mockExplorer} />);
const mainContainer = container.querySelector('[data-test="DataExplorerRoot"]');
expect(mainContainer).toBeInTheDocument();
expect(mainContainer).toHaveAttribute("aria-hidden", "false");
const divExplorer = container.querySelector("#divExplorer");
expect(divExplorer).toBeInTheDocument();
expect(divExplorer).toHaveClass("flexContainer", "hideOverflows");
const freeTierBubble = container.querySelector("#freeTierTeachingBubble");
expect(freeTierBubble).toBeInTheDocument();
const notificationContainer = container.querySelector("#explorerNotificationConsole");
expect(notificationContainer).toBeInTheDocument();
expect(notificationContainer).toHaveClass("dataExplorerErrorConsoleContainer");
expect(notificationContainer).toHaveAttribute("role", "contentinfo");
expect(notificationContainer).toHaveAttribute("aria-label", "Notification console");
});
test("should apply correct inline styles", () => {
const { container } = render(<ExplorerContainer explorer={mockExplorer} />);
const mainContainer = container.querySelector('[data-test="DataExplorerRoot"]');
expect(mainContainer).toHaveStyle({
flex: "1",
display: "flex",
flexDirection: "column",
backgroundColor: "var(--colorNeutralBackground1)",
color: "var(--colorNeutralForeground1)",
});
const divExplorer = container.querySelector("#divExplorer");
expect(divExplorer).toHaveStyle({
flex: "1",
display: "flex",
flexDirection: "column",
});
});
test("should handle carousel states correctly", () => {
const mockUseCarousel = jest.mocked(useCarousel);
mockUseCarousel.mockImplementation((selector: { toString: () => string | string[] }) => {
if (selector.toString().includes("shouldOpen")) {
return false;
}
if (selector.toString().includes("showCopilotCarousel")) {
return true;
}
return false;
});
render(<ExplorerContainer explorer={mockExplorer} />);
expect(screen.getByText("QuickstartCarousel - closed")).toBeInTheDocument();
expect(screen.getByText("CopilotCarousel - open - with explorer")).toBeInTheDocument();
});
test("should call useInteractive hook with correct metric", () => {
const mockUseInteractive = jest.mocked(useInteractive);
render(<ExplorerContainer explorer={mockExplorer} />);
expect(mockUseInteractive).toHaveBeenCalledWith("ApplicationLoad");
});
});

View File

@@ -0,0 +1,71 @@
import React from "react";
import { Dialog } from "../Explorer/Controls/Dialog";
import Explorer from "../Explorer/Explorer";
import { CommandBar } from "../Explorer/Menus/CommandBar/CommandBarComponentAdapter";
import { NotificationConsole } from "../Explorer/Menus/NotificationConsole/NotificationConsoleComponent";
import { SidePanel } from "../Explorer/Panes/PanelContainerComponent";
import { QueryCopilotCarousel } from "../Explorer/QueryCopilot/CopilotCarousel";
import { QuickstartCarousel } from "../Explorer/Quickstart/QuickstartCarousel";
import { MongoQuickstartTutorial } from "../Explorer/Quickstart/Tutorials/MongoQuickstartTutorial";
import { SQLQuickstartTutorial } from "../Explorer/Quickstart/Tutorials/SQLQuickstartTutorial";
import { SidebarContainer } from "../Explorer/Sidebar";
import { useCarousel } from "../hooks/useCarousel";
import MetricScenario from "../Metrics/MetricEvents";
import { useInteractive } from "../Metrics/useMetricPhases";
const ExplorerContainer: React.FC<{ explorer: Explorer }> = ({ explorer }) => {
const isCarouselOpen = useCarousel((state) => state.shouldOpen);
const isCopilotCarouselOpen = useCarousel((state) => state.showCopilotCarousel);
useInteractive(MetricScenario.ApplicationLoad);
return (
<div
className="flexContainer"
style={{
flex: 1,
display: "flex",
flexDirection: "column",
backgroundColor: "var(--colorNeutralBackground1)",
color: "var(--colorNeutralForeground1)",
}}
aria-hidden="false"
data-test="DataExplorerRoot"
>
<div
id="divExplorer"
className="flexContainer hideOverflows"
style={{
flex: 1,
display: "flex",
flexDirection: "column",
backgroundColor: "var(--colorNeutralBackground1)",
color: "var(--colorNeutralForeground1)",
}}
>
<div id="freeTierTeachingBubble"> </div>
<CommandBar container={explorer} />
<SidebarContainer explorer={explorer} />
<div
className="dataExplorerErrorConsoleContainer"
role="contentinfo"
aria-label="Notification console"
id="explorerNotificationConsole"
style={{
backgroundColor: "var(--colorNeutralBackground1)",
color: "var(--colorNeutralForeground1)",
}}
>
<NotificationConsole />
</div>
</div>
<SidePanel />
<Dialog />
{<QuickstartCarousel isOpen={isCarouselOpen} />}
{<SQLQuickstartTutorial />}
{<MongoQuickstartTutorial />}
{<QueryCopilotCarousel isOpen={isCopilotCarouselOpen} explorer={explorer} />}
</div>
);
};
export default ExplorerContainer;

View File

@@ -0,0 +1,71 @@
import "@testing-library/jest-dom";
import { render, screen } from "@testing-library/react";
import React from "react";
import LoadingExplorer from "./LoadingExplorer";
jest.mock("../../images/HdeConnectCosmosDB.svg", () => "test-hde-connect-image.svg");
jest.mock("@fluentui/react-components", () => ({
makeStyles: jest.fn(() => () => ({
root: "mock-root-class",
})),
}));
describe("LoadingExplorer", () => {
beforeEach(() => {
jest.clearAllMocks();
});
test("should render loading explorer component", () => {
render(<LoadingExplorer />);
const container = screen.getByRole("alert");
expect(container).toBeInTheDocument();
expect(container).toHaveTextContent("Connecting...");
});
test("should display welcome title", () => {
render(<LoadingExplorer />);
const title = screen.getByText("Welcome to Azure Cosmos DB");
expect(title).toBeInTheDocument();
expect(title).toHaveAttribute("id", "explorerLoadingStatusTitle");
});
test("should display connecting status text", () => {
render(<LoadingExplorer />);
const statusText = screen.getByText("Connecting...");
expect(statusText).toBeInTheDocument();
expect(statusText).toHaveAttribute("id", "explorerLoadingStatusText");
expect(statusText).toHaveAttribute("role", "alert");
});
test("should render Azure Cosmos DB image", () => {
render(<LoadingExplorer />);
const image = screen.getByAltText("Azure Cosmos DB");
expect(image).toBeInTheDocument();
expect(image).toHaveAttribute("src", "test-hde-connect-image.svg");
});
test("should have correct class structure", () => {
render(<LoadingExplorer />);
const splashContainer = document.querySelector(".splashLoaderContainer");
expect(splashContainer).toBeInTheDocument();
const contentContainer = document.querySelector(".splashLoaderContentContainer");
expect(contentContainer).toBeInTheDocument();
const connectContent = document.querySelector(".connectExplorerContent");
expect(connectContent).toBeInTheDocument();
});
test("should apply CSS classes correctly", () => {
const { container } = render(<LoadingExplorer />);
const rootDiv = container.firstChild as HTMLElement;
expect(rootDiv).toHaveClass("mock-root-class");
});
});

View File

@@ -0,0 +1,36 @@
import { makeStyles } from "@fluentui/react-components";
import React from "react";
import hdeConnectImage from "../../images/HdeConnectCosmosDB.svg";
const useStyles = makeStyles({
root: {
height: "100vh",
width: "100vw",
backgroundColor: "var(--colorNeutralBackground1)",
color: "var(--colorNeutralForeground1)",
},
});
function LoadingExplorer(): JSX.Element {
const styles = useStyles();
return (
<div className={styles.root}>
<div className="splashLoaderContainer">
<div className="splashLoaderContentContainer">
<p className="connectExplorerContent">
<img src={hdeConnectImage} alt="Azure Cosmos DB" />
</p>
<p className="splashLoaderTitle" id="explorerLoadingStatusTitle">
Welcome to Azure Cosmos DB
</p>
<p className="splashLoaderText" id="explorerLoadingStatusText" role="alert">
Connecting...
</p>
</div>
</div>
</div>
);
}
export default LoadingExplorer;

View File

@@ -0,0 +1,107 @@
import "@testing-library/jest-dom";
import { render, screen } from "@testing-library/react";
import React from "react";
import Root from "./Root";
jest.mock("../Explorer/ErrorBoundary", () => ({
ErrorBoundary: ({ children }: { children: React.ReactNode }) => (
<div data-testid="mock-error-boundary">{children}</div>
),
}));
jest.mock("@fluentui/react-components", () => ({
FluentProvider: ({ children, theme }: { children: React.ReactNode; theme: { colorNeutralBackground1: string } }) => (
<div
data-testid="mock-fluent-provider"
data-theme={theme.colorNeutralBackground1 === "dark" ? "webDarkTheme" : "webLightTheme"}
>
{children}
</div>
),
webLightTheme: { colorNeutralBackground1: "light" },
webDarkTheme: { colorNeutralBackground1: "dark" },
}));
jest.mock("./App", () => ({
__esModule: true,
default: () => <div data-testid="mock-app">App</div>,
}));
const createMockStore = (isDarkMode: boolean = false) => ({
getState: jest.fn(() => ({ isDarkMode })),
subscribe: jest.fn(() => jest.fn()),
});
const mockThemeStore = createMockStore(false);
jest.mock("../hooks/useTheme", () => ({
get useThemeStore() {
return mockThemeStore;
},
}));
describe("Root", () => {
beforeEach(() => {
jest.clearAllMocks();
});
test("should render Root component with all child components", () => {
render(<Root />);
expect(screen.getByTestId("mock-error-boundary")).toBeInTheDocument();
expect(screen.getByTestId("mock-fluent-provider")).toBeInTheDocument();
expect(screen.getByTestId("mock-app")).toBeInTheDocument();
});
test("should have correct component hierarchy", () => {
render(<Root />);
const errorBoundary = screen.getByTestId("mock-error-boundary");
const fluentProvider = screen.getByTestId("mock-fluent-provider");
const app = screen.getByTestId("mock-app");
expect(errorBoundary).toContainElement(fluentProvider);
expect(fluentProvider).toContainElement(app);
});
test("should subscribe to theme changes on mount", () => {
render(<Root />);
expect(mockThemeStore.subscribe).toHaveBeenCalled();
expect(mockThemeStore.subscribe).toHaveBeenCalledWith(expect.any(Function));
});
test("should get initial theme state", () => {
render(<Root />);
expect(mockThemeStore.getState).toHaveBeenCalled();
});
test("should handle component unmounting", () => {
const mockUnsubscribe = jest.fn();
mockThemeStore.subscribe.mockReturnValue(mockUnsubscribe);
const { unmount } = render(<Root />);
unmount();
expect(mockUnsubscribe).toHaveBeenCalled();
});
test("should call getState to initialize theme", () => {
render(<Root />);
expect(mockThemeStore.getState).toHaveBeenCalledTimes(1);
});
test("should handle theme subscription properly", () => {
render(<Root />);
expect(mockThemeStore.subscribe).toHaveBeenCalledTimes(1);
expect(mockThemeStore.getState).toHaveBeenCalled();
});
test("should render without errors", () => {
expect(() => render(<Root />)).not.toThrow();
});
});

View File

@@ -0,0 +1,28 @@
import { FluentProvider, webDarkTheme, webLightTheme } from "@fluentui/react-components";
import React from "react";
import { ErrorBoundary } from "../Explorer/ErrorBoundary";
import { useThemeStore } from "../hooks/useTheme";
import App from "./App";
const Root: React.FC = () => {
// Use React state to track isDarkMode and subscribe to changes
const [isDarkMode, setIsDarkMode] = React.useState(useThemeStore.getState().isDarkMode);
const currentTheme = isDarkMode ? webDarkTheme : webLightTheme;
// Subscribe to theme changes
React.useEffect(() => {
return useThemeStore.subscribe((state) => {
setIsDarkMode(state.isDarkMode);
});
}, []);
return (
<ErrorBoundary>
<FluentProvider theme={currentTheme}>
<App />
</FluentProvider>
</ErrorBoundary>
);
};
export default Root;

View File

@@ -470,15 +470,6 @@ export class DataExplorer {
return this.frame.getByTestId("notification-console/header-status");
}
async getDropdownItemByName(name: string, ariaLabel?: string): Promise<Locator> {
const dropdownItemsWrapper = this.frame.locator("div.ms-Dropdown-items");
if (ariaLabel) {
expect(await dropdownItemsWrapper.getAttribute("aria-label")).toEqual(ariaLabel);
}
const containerDropdownItems = dropdownItemsWrapper.locator("button.ms-Dropdown-item[role='option']");
return containerDropdownItems.filter({ hasText: name });
}
/** Waits for the Data Explorer app to load */
static async waitForExplorer(page: Page) {
const iframeElement = await page.getByTestId("DataExplorerFrame").elementHandle();

View File

@@ -9,7 +9,7 @@ let queryTab: QueryTab = null!;
let queryEditor: Editor = null!;
test.beforeAll("Create Test Database", async () => {
context = await createTestSQLContainer({ includeTestData: true });
context = await createTestSQLContainer(true);
});
test.beforeEach("Open new query tab", async ({ page }) => {

View File

@@ -1,98 +0,0 @@
import { expect, Page, test } from "@playwright/test";
import { DataExplorer, TestAccount } from "../../fx";
import { createTestSQLContainer, TestContainerContext } from "../../testData";
test.describe("Change Partition Key", () => {
let pageInstance: Page;
let context: TestContainerContext = null!;
let explorer: DataExplorer = null!;
const newPartitionKeyPath = "/newPartitionKey";
const newContainerId = "testcontainer_1";
test.beforeAll("Create Test Database", async () => {
context = await createTestSQLContainer();
});
test.beforeEach("Open container settings", async ({ page }) => {
pageInstance = page;
explorer = await DataExplorer.open(page, TestAccount.SQL);
// Click Scale & Settings and open Partition Key tab
await explorer.openScaleAndSettings(context);
const PartitionKeyTab = explorer.frame.getByTestId("settings-tab-header/PartitionKeyTab");
await PartitionKeyTab.click();
});
test.afterAll("Delete Test Database", async () => {
await context?.dispose();
});
test("Change partition key path", async () => {
await expect(explorer.frame.getByText("/partitionKey")).toBeVisible();
await expect(explorer.frame.getByText("Change partition key")).toBeVisible();
await expect(explorer.frame.getByText(/To safeguard the integrity of/)).toBeVisible();
await expect(explorer.frame.getByText(/To change the partition key/)).toBeVisible();
const changePartitionKeyButton = explorer.frame.getByTestId("change-partition-key-button");
expect(changePartitionKeyButton).toBeVisible();
await changePartitionKeyButton.click();
// Fill out new partition key form in the panel
const changePkPanel = explorer.frame.getByTestId(`Panel:Change partition key`);
await expect(changePkPanel.getByText(context.database.id)).toBeVisible();
await expect(explorer.frame.getByRole("heading", { name: "Change partition key" })).toBeVisible();
await expect(explorer.frame.getByText(/When changing a container/)).toBeVisible();
// Try to switch to new container
await expect(changePkPanel.getByText("New container")).toBeVisible();
await expect(changePkPanel.getByText("Existing container")).toBeVisible();
await expect(changePkPanel.getByTestId("new-container-id-input")).toBeVisible();
changePkPanel.getByTestId("new-container-id-input").fill(newContainerId);
await expect(changePkPanel.getByTestId("new-container-partition-key-input")).toBeVisible();
changePkPanel.getByTestId("new-container-partition-key-input").fill(newPartitionKeyPath);
await expect(changePkPanel.getByTestId("add-sub-partition-key-button")).toBeVisible();
changePkPanel.getByTestId("add-sub-partition-key-button").click();
await expect(changePkPanel.getByTestId("new-container-sub-partition-key-input-0")).toBeVisible();
await expect(changePkPanel.getByTestId("remove-sub-partition-key-button-0")).toBeVisible();
await expect(changePkPanel.getByTestId("hierarchical-partitioning-info-text")).toBeVisible();
changePkPanel.getByTestId("new-container-sub-partition-key-input-0").fill("/customerId");
await changePkPanel.getByTestId("Panel/OkButton").click();
await pageInstance.waitForLoadState("networkidle");
await expect(changePkPanel).not.toBeVisible({ timeout: 60 * 1000 });
// Verify partition key change job
const jobText = explorer.frame.getByText(/Partition key change job/);
await expect(jobText).toBeVisible();
await expect(explorer.frame.locator(".ms-ProgressIndicator-itemName")).toContainText("Portal_testcontainer_1");
const jobRow = explorer.frame.locator(".ms-ProgressIndicator-itemDescription");
await expect(jobRow.getByText("Completed")).toBeVisible({ timeout: 30 * 1000 });
const newContainerNode = await explorer.waitForContainerNode(context.database.id, newContainerId);
expect(newContainerNode).not.toBeNull();
// Now try to switch to existing container
await changePartitionKeyButton.click();
await changePkPanel.getByText("Existing container").click();
await changePkPanel.getByLabel("Use existing container").check();
await changePkPanel.getByText("Choose an existing container").click();
const containerDropdownItem = await explorer.getDropdownItemByName(newContainerId, "Existing Containers");
await containerDropdownItem.click();
await changePkPanel.getByTestId("Panel/OkButton").click();
await explorer.frame.getByRole("button", { name: "Cancel" }).click();
// Dismiss overlay if it appears
const overlayFrame = explorer.frame.locator("#webpack-dev-server-client-overlay").first();
if (await overlayFrame.count()) {
await overlayFrame.contentFrame().getByLabel("Dismiss").click();
}
const cancelledJobRow = explorer.frame.getByTestId("Tab:tab0");
await expect(cancelledJobRow.getByText("Cancelled")).toBeVisible({ timeout: 30 * 1000 });
});
});

View File

@@ -14,7 +14,7 @@ test.describe("Autoscale and Manual throughput", () => {
let explorer: DataExplorer = null!;
test.beforeAll("Create Test Database", async () => {
context = await createTestSQLContainer({ includeTestData: true });
context = await createTestSQLContainer(true);
});
test.beforeEach("Open container settings", async ({ page }) => {

View File

@@ -7,7 +7,7 @@ test.describe("Settings under Scale & Settings", () => {
let explorer: DataExplorer = null!;
test.beforeAll("Create Test Database", async () => {
context = await createTestSQLContainer({ includeTestData: true });
context = await createTestSQLContainer(true);
});
test.beforeEach("Open Settings tab under Scale & Settings", async ({ page }) => {

View File

@@ -74,18 +74,8 @@ export class TestContainerContext {
}
}
type createTestSqlContainerConfig = {
includeTestData?: boolean;
partitionKey?: string;
databaseName?: string;
};
export async function createTestSQLContainer({
includeTestData = false,
partitionKey = "/partitionKey",
databaseName = "",
}: createTestSqlContainerConfig = {}) {
const databaseId = databaseName ? databaseName : generateUniqueName("db");
export async function createTestSQLContainer(includeTestData?: boolean) {
const databaseId = generateUniqueName("db");
const containerId = "testcontainer"; // A unique container name isn't needed because the database is unique
const credentials = getAzureCLICredentials();
const adaptedCredentials = new AzureIdentityCredentialAdapter(credentials);
@@ -114,7 +104,7 @@ export async function createTestSQLContainer({
try {
const { container } = await database.containers.createIfNotExists({
id: containerId,
partitionKey,
partitionKey: "/partitionKey",
});
if (includeTestData) {
const batchCount = TestData.length / 100;