Skip to content
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
/*
* Copyright 2026 Collate.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { act, render, screen } from '@testing-library/react';
import { useState } from 'react';
import { MemoryRouter, NavigateFunction, useNavigate } from 'react-router-dom';
import { resolveAppModuleRoutes } from '../../platform/ai-shell/AppModeRoutes/AppModeRoutes.utils';
import { KeepAliveRoutes } from '../../platform/ai-shell/KeepAliveRoutes/KeepAliveRoutes';
import { TestCaseDetailProps } from '../TestCaseDetail/TestCaseDetail.types';
import { observabilityModule } from './observability.module';

const mockMountedPages: string[] = [];

jest.mock('../TestCaseDetail/TestCaseDetail', () => {
const MockTestCaseDetail = ({
isVersionPage = false,
}: TestCaseDetailProps) => {
const page = isVersionPage ? 'version' : 'details';

// Runs once per mount, so a re-render with new props is not counted.
useState(() => mockMountedPages.push(page));

return <div>{`test-case-${page}`}</div>;
};

return { __esModule: true, default: MockTestCaseDetail };
});

jest.mock('../ObservabilityLayout/ObservabilityLayout', () => ({
__esModule: true,
default: ({ children }: { children: React.ReactNode }) => <>{children}</>,
}));

const TEST_CASE_PATH = '/observability/test-case/svc.db.schema.table.test';

let navigate: NavigateFunction;

const NavigateCapture = () => {
navigate = useNavigate();

return null;
};

const goTo = async (path: string, text: string) => {
await act(async () => {
navigate(path);
});

expect(await screen.findByText(text)).toBeInTheDocument();
};

describe('observabilityModule test case routes', () => {
beforeEach(() => {
mockMountedPages.length = 0;
});

it('should remount the test case page when switching between details and versions', async () => {
render(
<MemoryRouter initialEntries={[TEST_CASE_PATH]}>
<NavigateCapture />
<KeepAliveRoutes
routes={resolveAppModuleRoutes([observabilityModule])}
/>
</MemoryRouter>
);

expect(await screen.findByText('test-case-details')).toBeInTheDocument();

await goTo(`${TEST_CASE_PATH}/versions/0.3`, 'test-case-version');
await goTo(
`${TEST_CASE_PATH}/versions/0.1/test-case-results`,
'test-case-version'
);
await goTo(`${TEST_CASE_PATH}/test-case-results`, 'test-case-details');

expect(mockMountedPages).toEqual(['details', 'version', 'details']);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,12 @@ const AlertDetailsPage = withSuspenseFallback(
React.lazy(() => import('../Alerts/AlertDetailsPage'))
);

// The version routes key their TestCaseDetail apart from the details routes so
// switching between them remounts it, like the classic router's separate
// TestCaseVersionPage. Otherwise the historical snapshot the version page puts
// in useTestCaseStore survives the switch and the details page shows it.
const TEST_CASE_VERSION_INSTANCE_KEY = 'test-case-version';

// NOTE: Pipeline* pages still live in Collate (large plugin-coupled pages).
// Until they are moved to OSS, their routes resolve through the app-mode
// fallback (CollateRouter); the pipeline sub-nav item below navigates to those
Expand Down Expand Up @@ -174,7 +180,7 @@ export const observabilityModule: AppModule = {
path: OBSERVABILITY_ROUTES.OBSERVABILITY_TEST_CASE_VERSION_WITH_TAB,
element: (
<ObservabilityLayout>
<TestCaseDetail isVersionPage />
<TestCaseDetail isVersionPage key={TEST_CASE_VERSION_INSTANCE_KEY} />
</ObservabilityLayout>
),
position: RoutePosition.APP,
Expand All @@ -183,7 +189,7 @@ export const observabilityModule: AppModule = {
path: OBSERVABILITY_ROUTES.OBSERVABILITY_TEST_CASE_VERSION,
element: (
<ObservabilityLayout>
<TestCaseDetail isVersionPage />
<TestCaseDetail isVersionPage key={TEST_CASE_VERSION_INSTANCE_KEY} />
</ObservabilityLayout>
),
position: RoutePosition.APP,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,10 @@ import {
import { getDerivedPermissionFlags } from '../../../utils/PermissionDerivation';
import { showErrorToast, showSuccessToast } from '../../../utils/ToastUtils';
import { TestCasePageTabs } from '../IncidentManager.interface';
import { UseTestCaseStoreInterface } from './useTestCase.store';
import {
useTestCaseStore,
UseTestCaseStoreInterface,
} from './useTestCase.store';
import { useTestCaseDetailPage } from './useTestCaseDetailPage';

const mockTestCaseFqn =
Expand Down Expand Up @@ -610,4 +613,96 @@ describe('useTestCaseDetailPage', () => {
expect.any(Function)
);
});

describe('version responses that resolve after the version page unmounts', () => {
// The store outlives the page, so these run against the real store.
const actualStore = jest.requireActual('./useTestCase.store');
const currentTestCase = {
...MOCK_TEST_CASE_DATA,
displayName: 'Current name',
version: 0.3,
};
const historicalTestCase = {
...MOCK_TEST_CASE_DATA,
displayName: 'Old name',
version: 0.1,
};

const leaveVersionPageForDetails = async () => {
mockParams = { ...mockParams, version: '0.1' };
const versionPage = renderDetailPageHook(true);

await waitFor(() => expect(getTestCaseVersionDetails).toHaveBeenCalled());

versionPage.unmount();
mockParams = { ...mockParams, version: undefined };
const detailsPage = renderDetailPageHook();

await waitFor(() =>
expect(detailsPage.result.current.testCase).toEqual(currentTestCase)
);

return detailsPage;
};

beforeEach(() => {
(useTestCaseStore as unknown as jest.Mock).mockImplementation(
actualStore.useTestCaseStore
);
(getTestCaseByFqn as jest.Mock).mockResolvedValue(currentTestCase);
});

afterEach(() => {
actualStore.useTestCaseStore.getState().reset();
(useTestCaseStore as unknown as jest.Mock).mockImplementation(
() => mockUseTestCase
);
(getTestCaseByFqn as jest.Mock).mockResolvedValue(MOCK_TEST_CASE_DATA);
(getTestCaseVersionDetails as jest.Mock).mockResolvedValue(
MOCK_TEST_CASE_DATA
);
});

it('should keep the current test case when an older version arrives late', async () => {
let resolveVersion!: (testCase: typeof historicalTestCase) => void;
(getTestCaseVersionDetails as jest.Mock).mockReturnValue(
new Promise((resolve) => {
resolveVersion = resolve;
})
);
const detailsPage = await leaveVersionPageForDetails();

await act(async () => {
resolveVersion(historicalTestCase);
});

expect(detailsPage.result.current.testCase).toEqual(currentTestCase);
});

it('should report a version fetch that fails while viewing the version', async () => {
const error = new Error('version fetch failed');
(getTestCaseVersionDetails as jest.Mock).mockRejectedValue(error);
mockParams = { ...mockParams, version: '0.1' };

renderDetailPageHook(true);

await waitFor(() => expect(showErrorToast).toHaveBeenCalledWith(error));
});

it('should not report a version fetch that fails after leaving', async () => {
let rejectVersion!: (error: Error) => void;
(getTestCaseVersionDetails as jest.Mock).mockReturnValue(
new Promise((_resolve, reject) => {
rejectVersion = reject;
})
);
await leaveVersionPageForDetails();

await act(async () => {
rejectVersion(new Error('version fetch failed'));
});

expect(showErrorToast).not.toHaveBeenCalled();
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,7 @@
isVersionPage,
isDimensionalityTabVisible
);
}, [

Check warning on line 282 in openmetadata-ui/src/main/resources/ui/src/pages/IncidentManager/IncidentManagerDetailPage/useTestCaseDetailPage.tsx

View workflow job for this annotation

GitHub Actions / checkstyle

React Hook useMemo has an unnecessary dependency: 'testCaseClassBase.showSqlQueryTab'. Either exclude it or remove the dependency array. Outer scope values like 'testCaseClassBase.showSqlQueryTab' aren't valid dependencies because mutating them doesn't re-render the component
feedCount.openTaskCount,
testCaseClassBase.showSqlQueryTab,
testCase?.dimensionColumns,
Expand Down Expand Up @@ -401,7 +401,7 @@

const getEntityFeedCount = useCallback(() => {
getFeedCounts(EntityType.TEST_CASE, testCaseFQN, handleFeedCount);
}, [testCaseFQN]);

Check warning on line 404 in openmetadata-ui/src/main/resources/ui/src/pages/IncidentManager/IncidentManagerDetailPage/useTestCaseDetailPage.tsx

View workflow job for this annotation

GitHub Actions / checkstyle

React Hook useCallback has a missing dependency: 'handleFeedCount'. Either include it or remove the dependency array

// Only the open-task count is used here (tab badge); skip the
// activity-events fetch that getFeedCounts would bundle in.
Expand Down Expand Up @@ -440,16 +440,25 @@
{ state: location.state }
);
},
[testCaseFQN, urlTab, location.state]

Check warning on line 443 in openmetadata-ui/src/main/resources/ui/src/pages/IncidentManager/IncidentManagerDetailPage/useTestCaseDetailPage.tsx

View workflow job for this annotation

GitHub Actions / checkstyle

React Hook useCallback has missing dependencies: 'navigate' and 'version'. Either include them or remove the dependency array
);
const fetchCurrentVersion = async (id: string) => {
try {
const response = await getTestCaseVersionDetails(id, version);
setTestCase(response);
} catch (error) {
showErrorToast(error as AxiosError);
}
};
// The store outlives this page, so a response that lands after the user left
// this version (signal aborted) would put a snapshot nobody is viewing on screen.
const fetchCurrentVersion = useCallback(
async (id: string, signal: AbortSignal) => {
try {
const response = await getTestCaseVersionDetails(id, version);
if (!signal.aborted) {
setTestCase(response);
}
} catch (error) {
if (!signal.aborted) {
showErrorToast(error as AxiosError);
}
}
},
[version, setTestCase]
);

const displayName = useMemo(() => {
return isVersionPage
Expand All @@ -470,13 +479,17 @@
reset();
testCaseClassBase.setShowSqlQueryTab(false);
};
}, [testCaseFQN, hasViewPermission]);

Check warning on line 482 in openmetadata-ui/src/main/resources/ui/src/pages/IncidentManager/IncidentManagerDetailPage/useTestCaseDetailPage.tsx

View workflow job for this annotation

GitHub Actions / checkstyle

React Hook useEffect has missing dependencies: 'fetchTaskCounts' and 'reset'. Either include them or remove the dependency array

useEffect(() => {
const controller = new AbortController();

if (testCase?.id && isVersionPage) {
fetchCurrentVersion(testCase.id);
fetchCurrentVersion(testCase.id, controller.signal);
}
}, [version, testCase?.id, isVersionPage]);

return () => controller.abort();
}, [testCase?.id, isVersionPage, fetchCurrentVersion]);

const extraDropdownContent = useMemo(() => {
const isColumn = testCase?.entityLink.includes('::columns::');
Expand Down
Loading