diff --git a/openmetadata-ui/src/main/resources/ui/src/components/DataQuality/TestCases/useTestCaseList.ts b/openmetadata-ui/src/main/resources/ui/src/components/DataQuality/TestCases/useTestCaseList.ts index 6de19978b4e5..25a4dd4dee78 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/DataQuality/TestCases/useTestCaseList.ts +++ b/openmetadata-ui/src/main/resources/ui/src/components/DataQuality/TestCases/useTestCaseList.ts @@ -21,7 +21,10 @@ import { useRef, useState, } from 'react'; -import { INITIAL_PAGING_VALUE } from '../../../constants/constants'; +import { + INITIAL_PAGING_VALUE, + PAGING_URL_PARAMS, +} from '../../../constants/constants'; import { DEFAULT_SORT_ORDER } from '../../../constants/profiler.constant'; import { OperationPermission } from '../../../context/PermissionProvider/PermissionProvider.interface'; import { DataQualityPageTabs } from '../../../enums/DataQuality.enum'; @@ -59,16 +62,6 @@ export interface UseTestCaseListProps { showPagination: boolean; } -// usePaging keeps these in the query string that `params` is parsed from. A paging action sets -// the page in state first and in the URL in a later (transition) render, so the fetch reads the -// page from `currentPage` and `pageSize` and must not refetch again when the URL catches up. -const PAGING_URL_PARAMS = [ - 'currentPage', - 'pageSize', - 'cursorType', - 'cursorValue', -]; - /** * Owns the DATA concern: the test-case rows, their loading flag, the sort * options and the fetch pipeline. The driving fetch effect stays co-located diff --git a/openmetadata-ui/src/main/resources/ui/src/components/IncidentManager/IncidentManager.test.tsx b/openmetadata-ui/src/main/resources/ui/src/components/IncidentManager/IncidentManager.test.tsx index 9bc67b65d02e..6372fcad5ce2 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/IncidentManager/IncidentManager.test.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/IncidentManager/IncidentManager.test.tsx @@ -945,27 +945,31 @@ describe('IncidentManagerPage', () => { mockHandlePageSizeChange.mockClear(); }); - it('should fetch next page when Next is clicked', async () => { - const { mockHandlePageChange } = require('../../hooks/paging/usePaging'); + // usePaging is mocked, so a click cannot move `currentPage`; the click must + // only hand the page to usePaging, whose change drives the single fetch + // (covered with the real usePaging in useIncidentManagerListPage.integration.test). + const clickAndCountListRequests = async (testId: string) => { + const listMock = getListTestCaseIncidentStatusFromSearch as jest.Mock; + const button = await screen.findByTestId(testId); + const callsBefore = listMock.mock.calls.length; await act(async () => { - render(); + fireEvent.click(button); }); - const nextButton = await screen.findByTestId('pagination-next'); + return listMock.mock.calls.length - callsBefore; + }; + + it('should move to the next page when Next is clicked', async () => { + const { mockHandlePageChange } = require('../../hooks/paging/usePaging'); await act(async () => { - fireEvent.click(nextButton); + render(); }); - expect(getListTestCaseIncidentStatusFromSearch).toHaveBeenLastCalledWith( - expect.objectContaining({ - limit: 10, - offset: 10, - }) - ); + expect(await clickAndCountListRequests('pagination-next')).toBe(0); expect(mockHandlePageChange).toHaveBeenCalledWith(2); }); - it('should fetch previous page when Previous is clicked', async () => { + it('should move to the previous page when Previous is clicked', async () => { const usePagingModule = require('../../hooks/paging/usePaging'); const { usePaging, mockHandlePageChange } = usePagingModule; usePaging.mockReturnValue({ @@ -982,50 +986,23 @@ describe('IncidentManagerPage', () => { render(); }); - const previousButton = await screen.findByTestId('pagination-previous'); - await act(async () => { - fireEvent.click(previousButton); - }); - expect(getListTestCaseIncidentStatusFromSearch).toHaveBeenLastCalledWith( - expect.objectContaining({ - limit: 10, - offset: 0, - }) + expect.objectContaining({ limit: 10, offset: 10 }) ); + expect(await clickAndCountListRequests('pagination-previous')).toBe(0); expect(mockHandlePageChange).toHaveBeenCalledWith(1); }); - it('should fetch correct page when page number is clicked', async () => { + it('should move to the clicked page number', async () => { const { mockHandlePageChange } = require('../../hooks/paging/usePaging'); await act(async () => { render(); }); - const page2Button = await screen.findByTestId('pagination-page-2'); - await act(async () => { - fireEvent.click(page2Button); - }); - - expect(getListTestCaseIncidentStatusFromSearch).toHaveBeenLastCalledWith( - expect.objectContaining({ - limit: 10, - offset: 10, - }) - ); + expect(await clickAndCountListRequests('pagination-page-2')).toBe(0); expect(mockHandlePageChange).toHaveBeenCalledWith(2); - const page3Button = await screen.findByTestId('pagination-page-3'); - await act(async () => { - fireEvent.click(page3Button); - }); - - expect(getListTestCaseIncidentStatusFromSearch).toHaveBeenLastCalledWith( - expect.objectContaining({ - limit: 10, - offset: 20, - }) - ); + expect(await clickAndCountListRequests('pagination-page-3')).toBe(0); expect(mockHandlePageChange).toHaveBeenCalledWith(3); }); diff --git a/openmetadata-ui/src/main/resources/ui/src/components/IncidentManager/useIncidentFilters.test.ts b/openmetadata-ui/src/main/resources/ui/src/components/IncidentManager/useIncidentFilters.test.ts index 672d94e5ed4b..6e0406e5ff86 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/IncidentManager/useIncidentFilters.test.ts +++ b/openmetadata-ui/src/main/resources/ui/src/components/IncidentManager/useIncidentFilters.test.ts @@ -14,6 +14,7 @@ import { renderHook } from '@testing-library/react'; import { isString, omit, parseInt } from 'lodash'; import QueryString, { ParsedQs } from 'qs'; import { act } from 'react'; +import { PAGING_URL_PARAMS } from '../../constants/constants'; import { TestCaseIncidentStatusParams } from '../../rest/incidentManagerAPI'; import { useIncidentFilters, @@ -37,14 +38,18 @@ const renderFiltersHook = (overrides: Partial = {}) => ); // Models the production wiring in `useIncidentManagerListPage`: `filters` is -// derived from `omit(allParams, ['key', 'title'])`, so it carries `currentPage` -// /`pageSize`/cursor params verbatim (with `startTs`/`endTs` coerced to numbers). -// Tests that inject `filters` and `allParams` independently mask the stale-page -// bug; this helper keeps them in sync to exercise the real relationship. +// `allParams` without `key`/`title` and usePaging's params (with +// `startTs`/`endTs` coerced to numbers), while `allParams` keeps the paging +// params. Tests that inject the two independently mask the stale-page bug; +// this helper keeps them in sync to exercise the real relationship. const deriveProductionFilters = ( allParams: ParsedQs ): TestCaseIncidentStatusParams => { - const base = omit(allParams, ['key', 'title']) as Record; + const base = omit(allParams, [ + 'key', + 'title', + ...PAGING_URL_PARAMS, + ]) as Record; if (isString(base.startTs)) { base.startTs = parseInt(base.startTs, 10); @@ -142,6 +147,25 @@ describe('useIncidentFilters', () => { expect(firstCallArg.search).not.toContain('existing=y'); }); + it('should keep the page size and reset to page 1 when the date range changes', () => { + const { result } = renderFiltersHook({ + allParams: { currentPage: '3', pageSize: '25' }, + }); + + act(() => { + result.current.updateFilters( + { startTs: 1, endTs: 2 }, + { key: 'k', title: 't' } + ); + }); + + const [firstCallArg] = mockNavigate.mock.calls[0]; + + expect(firstCallArg.search).toContain('pageSize=25'); + expect(firstCallArg.search).toContain('currentPage=1'); + expect(firstCallArg.search).not.toContain('currentPage=3'); + }); + it('should navigate on a changed date range via handleDateRangeChange', () => { const { result } = renderFiltersHook(); diff --git a/openmetadata-ui/src/main/resources/ui/src/components/IncidentManager/useIncidentFilters.ts b/openmetadata-ui/src/main/resources/ui/src/components/IncidentManager/useIncidentFilters.ts index eece02126da8..a4b93cb35cc2 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/IncidentManager/useIncidentFilters.ts +++ b/openmetadata-ui/src/main/resources/ui/src/components/IncidentManager/useIncidentFilters.ts @@ -16,7 +16,10 @@ import QueryString, { ParsedQs } from 'qs'; import { useCallback, useMemo, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { useNavigate } from 'react-router-dom'; -import { INITIAL_PAGING_VALUE } from '../../constants/constants'; +import { + INITIAL_PAGING_VALUE, + PAGING_URL_PARAMS, +} from '../../constants/constants'; import { Option } from '../../pages/TasksPage/TasksPage.interface'; import { TestCaseIncidentStatusParams } from '../../rest/incidentManagerAPI'; @@ -74,10 +77,9 @@ export const useIncidentFilters = ({ dateRangeParams?: { key: string; title: string } ) => { const updatedFilters = { ...filters, ...newFilters }; - // `filters` mirrors the whole query string, so it also carries usePaging's - // `currentPage`/cursor params. A changed value yields a different result - // set, and keeping the old page would request an offset past its end. An - // unchanged value (e.g. re-selecting the same option) keeps the page. + // A changed value yields a different result set, and keeping the old page + // would request an offset past its end. An unchanged value (e.g. + // re-selecting the same option) keeps the page. const filterChanged = Object.keys(newFilters).some( (key) => !isEqual( @@ -92,8 +94,15 @@ export const useIncidentFilters = ({ cursorValue: undefined, } : {}; + // `filters` leaves out usePaging's params, so a date-range update, which + // rebuilds the query from `filters`, carries them over from the URL. const allUpdatedParams = dateRangeParams - ? { ...updatedFilters, ...dateRangeParams, ...pagingReset } + ? { + ...pick(allParams, PAGING_URL_PARAMS), + ...updatedFilters, + ...dateRangeParams, + ...pagingReset, + } : { ...allParams, ...updatedFilters, ...pagingReset }; navigate( diff --git a/openmetadata-ui/src/main/resources/ui/src/components/IncidentManager/useIncidentList.test.ts b/openmetadata-ui/src/main/resources/ui/src/components/IncidentManager/useIncidentList.test.ts index 650102789346..5dabfac4a832 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/IncidentManager/useIncidentList.test.ts +++ b/openmetadata-ui/src/main/resources/ui/src/components/IncidentManager/useIncidentList.test.ts @@ -14,6 +14,7 @@ import { act, renderHook, waitFor } from '@testing-library/react'; import { OperationPermission } from '../../context/PermissionProvider/PermissionProvider.interface'; import { Table } from '../../generated/entity/data/table'; import { Include } from '../../generated/type/include'; +import { usePaging } from '../../hooks/paging/usePaging'; import { useDomainStore } from '../../hooks/useDomainStore'; import { getListTestCaseIncidentStatusFromSearch } from '../../rest/incidentManagerAPI'; import { showErrorToast } from '../../utils/ToastUtils'; @@ -158,24 +159,42 @@ describe('useIncidentList', () => { expect(mockGetList).not.toHaveBeenCalled(); }); - it('should refetch with the paged offset and advance the page on handlePagingClick', async () => { - const props = makeProps({ - commonTestCasePermission: undefined, - filters: { testCaseFQN: 'x' }, - }); + it('should move to another page through handlePageChange without fetching it directly', async () => { + const props = makeProps({ filters: { testCaseFQN: 'x' } }); const { result } = renderHook(() => useIncidentList(props)); + await waitFor(() => + expect(result.current.testCaseListData.isLoading).toBe(false) + ); + mockGetList.mockClear(); + act(() => { result.current.handlePagingClick({ currentPage: 3 }); }); - await waitFor(() => expect(mockGetList).toHaveBeenCalled()); - - const callArg = mockGetList.mock.calls[0][0]; - - expect(callArg.offset).toBe(20); - expect(callArg.testCaseFQN).toBe('x'); expect(mockHandlePageChange).toHaveBeenCalledWith(3); + expect(mockGetList).not.toHaveBeenCalled(); + }); + + it('should fetch the offset of the current page', async () => { + const pagingMock = usePaging as jest.Mock; + const defaultPaging = pagingMock.getMockImplementation(); + pagingMock.mockImplementation(() => ({ + ...defaultPaging?.(), + currentPage: 3, + })); + try { + const props = makeProps({ filters: { testCaseFQN: 'x' } }); + renderHook(() => useIncidentList(props)); + + await waitFor(() => expect(mockGetList).toHaveBeenCalled()); + + expect(mockGetList.mock.calls[0][0]).toEqual( + expect.objectContaining({ offset: 20, testCaseFQN: 'x' }) + ); + } finally { + pagingMock.mockImplementation(defaultPaging); + } }); it('should request deleted incidents scoped to the origin table when tableDetails is deleted', async () => { diff --git a/openmetadata-ui/src/main/resources/ui/src/components/IncidentManager/useIncidentList.ts b/openmetadata-ui/src/main/resources/ui/src/components/IncidentManager/useIncidentList.ts index bbb76303dce5..7ce0654a7047 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/IncidentManager/useIncidentList.ts +++ b/openmetadata-ui/src/main/resources/ui/src/components/IncidentManager/useIncidentList.ts @@ -17,6 +17,7 @@ import { useCallback, useEffect, useMemo, + useRef, useState, } from 'react'; import { DEFAULT_DOMAIN_VALUE } from '../../constants/constants'; @@ -75,8 +76,13 @@ export const useIncidentList = ({ handlePageSizeChange, } = usePaging(); + // Only the latest request may write rows and paging: a slower response for a + // page the user already left must not overwrite the page they are on. + const latestRequestId = useRef(0); + const fetchTestCaseIncidents = useCallback( async (params: TestCaseIncidentStatusParams) => { + const requestId = ++latestRequestId.current; setTestCaseListData((prev) => ({ ...prev, isLoading: true })); try { const { data, paging } = await getListTestCaseIncidentStatusFromSearch({ @@ -89,6 +95,9 @@ export const useIncidentList = ({ activeDomain === DEFAULT_DOMAIN_VALUE ? undefined : activeDomain, ...params, }); + if (requestId !== latestRequestId.current) { + return; + } const assigneeOptions = data.reduce((acc, curr) => { const assignee = curr.testCaseResolutionStatusDetails?.assignee; const isExist = acc.some((item) => item.value === assignee?.name); @@ -112,9 +121,13 @@ export const useIncidentList = ({ setTestCaseListData((prev) => ({ ...prev, data: data })); handlePagingChange(paging); } catch (error) { - showErrorToast(error as AxiosError); + if (requestId === latestRequestId.current) { + showErrorToast(error as AxiosError); + } } finally { - setTestCaseListData((prev) => ({ ...prev, isLoading: false })); + if (requestId === latestRequestId.current) { + setTestCaseListData((prev) => ({ ...prev, isLoading: false })); + } } }, [ @@ -126,15 +139,10 @@ export const useIncidentList = ({ ] ); + // A page change reaches the fetch effect through `currentPage`. const handlePagingClick = useCallback( - ({ currentPage }: PagingHandlerParams) => { - fetchTestCaseIncidents({ - ...filters, - offset: (currentPage - 1) * pageSize, - }); - handlePageChange(currentPage); - }, - [fetchTestCaseIncidents, filters, pageSize, handlePageChange] + ({ currentPage: page }: PagingHandlerParams) => handlePageChange(page), + [handlePageChange] ); const pagingData = useMemo( @@ -159,12 +167,16 @@ export const useIncidentList = ({ useEffect(() => { if (hasViewAccess) { - fetchTestCaseIncidents(filters); + fetchTestCaseIncidents({ + ...filters, + offset: (currentPage - 1) * pageSize, + }); } else { setTestCaseListData((prev) => ({ ...prev, isLoading: false })); } }, [ hasViewAccess, + currentPage, pageSize, filters, activeDomain, diff --git a/openmetadata-ui/src/main/resources/ui/src/components/IncidentManager/useIncidentManagerListPage.integration.test.tsx b/openmetadata-ui/src/main/resources/ui/src/components/IncidentManager/useIncidentManagerListPage.integration.test.tsx new file mode 100644 index 000000000000..b557a9f52236 --- /dev/null +++ b/openmetadata-ui/src/main/resources/ui/src/components/IncidentManager/useIncidentManagerListPage.integration.test.tsx @@ -0,0 +1,187 @@ +/* + * 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, renderHook, waitFor } from '@testing-library/react'; +import { ReactNode } from 'react'; +import { MemoryRouter, Route, Routes } from 'react-router-dom'; +import { TestCaseResolutionStatusTypes } from '../../generated/tests/testCaseResolutionStatus'; +import { usePersistentStorage } from '../../hooks/currentUserStore/useCurrentUserStore'; +import { getListTestCaseIncidentStatusFromSearch } from '../../rest/incidentManagerAPI'; +import { useIncidentManagerListPage } from './useIncidentManagerListPage'; + +// The router, usePaging and the URL-backed filters are REAL here: together they decide how many +// list requests one paging action sends, since the page lands in component state first and in the +// URL in a later render. Only REST calls, providers and the filter-option lookups are mocked. +const mockCurrentUser = { name: 'incident-paging-user' }; +const mockPermissionProvider = { + permissions: { testCase: { ViewAll: true, ViewBasic: true } }, + getEntityPermissionByFqn: jest.fn().mockResolvedValue({}), +}; +const mockFilterOptions = { + assigneeOptionsWithSelected: [], + selectedAssignees: [], + setUsers: jest.fn(), + fetchUserFilterOptions: jest.fn(), + searchTestCases: jest.fn(), +}; + +jest.mock('../../hooks/useApplicationStore', () => ({ + useApplicationStore: jest.fn((selector) => + selector({ currentUser: mockCurrentUser }) + ), +})); + +jest.mock('../../context/PermissionProvider/PermissionProvider', () => ({ + usePermissionProvider: jest.fn(() => mockPermissionProvider), +})); + +jest.mock('./useIncidentFilterOptions', () => ({ + useIncidentFilterOptions: jest.fn(() => mockFilterOptions), +})); + +jest.mock('../../rest/incidentManagerAPI', () => ({ + ...jest.requireActual('../../rest/incidentManagerAPI'), + getListTestCaseIncidentStatusFromSearch: jest.fn(), +})); + +const mockGetList = getListTestCaseIncidentStatusFromSearch as jest.Mock; + +const rowsAt = (offset: number) => ({ + data: [{ id: `row-${offset}` }], + paging: { total: 100 }, +}); + +const makeWrapper = + (search = '') => + ({ children }: { children: ReactNode }) => + ( + + + + + + ); + +const renderLoadedPage = async (search = '') => { + const rendered = renderHook(() => useIncidentManagerListPage({}), { + wrapper: makeWrapper(search), + }); + + await waitFor(() => + expect(rendered.result.current.testCaseListData.isLoading).toBe(false) + ); + + return rendered; +}; + +describe('useIncidentManagerListPage (integration)', () => { + beforeEach(() => { + usePersistentStorage.getState().clearUserPreference('incident-paging-user'); + mockGetList + .mockReset() + .mockImplementation(({ offset }) => Promise.resolve(rowsAt(offset))); + }); + + it('sends one list request for the selected page', async () => { + const { result } = await renderLoadedPage(); + const { pageSize } = result.current.pagingData; + mockGetList.mockClear(); + + await act(async () => { + result.current.pagingData.pagingHandler({ currentPage: 3 }); + }); + await waitFor(() => + expect(result.current.testCaseListData.isLoading).toBe(false) + ); + + expect(result.current.pagingData.currentPage).toBe(3); + expect(mockGetList).toHaveBeenCalledTimes(1); + expect(mockGetList.mock.calls[0][0]).toEqual( + expect.objectContaining({ offset: 2 * pageSize }) + ); + expect(result.current.testCaseListData.data[0].id).toBe( + `row-${2 * pageSize}` + ); + }); + + it('fetches the page named in the URL on first load', async () => { + const { result } = await renderLoadedPage('?currentPage=3'); + const { pageSize } = result.current.pagingData; + + expect(result.current.pagingData.currentPage).toBe(3); + expect(mockGetList).toHaveBeenCalledTimes(1); + expect(mockGetList.mock.calls[0][0]).toEqual( + expect.objectContaining({ offset: 2 * pageSize }) + ); + }); + + it('shows the last page asked for when an earlier response arrives later', async () => { + const { result } = await renderLoadedPage(); + const { pageSize } = result.current.pagingData; + let resolveSecondPage: () => void = jest.fn(); + mockGetList.mockImplementation(({ offset }) => + offset === pageSize + ? new Promise((resolve) => { + resolveSecondPage = () => resolve(rowsAt(offset)); + }) + : Promise.resolve(rowsAt(offset)) + ); + + await act(async () => { + result.current.pagingData.pagingHandler({ currentPage: 2 }); + }); + await act(async () => { + result.current.pagingData.pagingHandler({ currentPage: 3 }); + }); + await waitFor(() => + expect(result.current.testCaseListData.isLoading).toBe(false) + ); + await act(async () => { + resolveSecondPage(); + }); + + expect(result.current.pagingData.currentPage).toBe(3); + expect(result.current.testCaseListData.data[0].id).toBe( + `row-${2 * pageSize}` + ); + }); + + it('refetches the first page once when a filter changes on a later page', async () => { + const { result } = await renderLoadedPage(); + + await act(async () => { + result.current.pagingData.pagingHandler({ currentPage: 3 }); + }); + await waitFor(() => + expect(result.current.testCaseListData.isLoading).toBe(false) + ); + mockGetList.mockClear(); + + await act(async () => { + result.current.updateFilters({ + testCaseResolutionStatusType: TestCaseResolutionStatusTypes.ACK, + }); + }); + await waitFor(() => + expect(result.current.testCaseListData.isLoading).toBe(false) + ); + + expect(result.current.pagingData.currentPage).toBe(1); + expect(mockGetList).toHaveBeenCalledTimes(1); + expect(mockGetList.mock.calls[0][0]).toEqual( + expect.objectContaining({ + offset: 0, + testCaseResolutionStatusType: TestCaseResolutionStatusTypes.ACK, + }) + ); + }); +}); diff --git a/openmetadata-ui/src/main/resources/ui/src/components/IncidentManager/useIncidentManagerListPage.ts b/openmetadata-ui/src/main/resources/ui/src/components/IncidentManager/useIncidentManagerListPage.ts index 6bd8fb5399b4..8512a1bd1892 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/IncidentManager/useIncidentManagerListPage.ts +++ b/openmetadata-ui/src/main/resources/ui/src/components/IncidentManager/useIncidentManagerListPage.ts @@ -13,6 +13,7 @@ import { isString, isUndefined, omit, parseInt } from 'lodash'; import QueryString from 'qs'; import { useMemo } from 'react'; +import { PAGING_URL_PARAMS } from '../../constants/constants'; import { usePermissionProvider } from '../../context/PermissionProvider/PermissionProvider'; import { Table } from '../../generated/entity/data/table'; import useCustomLocation from '../../hooks/useCustomLocation/useCustomLocation'; @@ -42,7 +43,9 @@ export const useIncidentManagerListPage = ({ return isUndefined(searchData) ? {} : searchData; }, [location.search]); - const filterSearch = QueryString.stringify(omit(allParams, ['key', 'title'])); + const filterSearch = QueryString.stringify( + omit(allParams, ['key', 'title', ...PAGING_URL_PARAMS]) + ); const filters = useMemo(() => { const urlParams = QueryString.parse(filterSearch); diff --git a/openmetadata-ui/src/main/resources/ui/src/constants/constants.ts b/openmetadata-ui/src/main/resources/ui/src/constants/constants.ts index a46983b8ea4e..fe73e9ea7179 100644 --- a/openmetadata-ui/src/main/resources/ui/src/constants/constants.ts +++ b/openmetadata-ui/src/main/resources/ui/src/constants/constants.ts @@ -55,6 +55,15 @@ export const REFRESH_TOKEN_KEY = 'refreshToken'; export const USER_DATA_SIZE = 5; export const INITIAL_PAGING_VALUE = 1; +// usePaging keeps these in the query string. A paging action sets the page in state first and in +// the URL in a later (transition) render, so a list that parses its filters from the query string +// must leave these out, or the URL catching up refetches with the filters alone. +export const PAGING_URL_PARAMS = [ + 'currentPage', + 'pageSize', + 'cursorType', + 'cursorValue', +]; export const JSON_TAB_SIZE = 2; export const KNOWLEDGE_LIST_LENGTH = 8; export const PAGE_SIZE = 10; diff --git a/openmetadata-ui/src/main/resources/ui/src/pages/IncidentManager/IncidentManagerPage.browser.test.tsx b/openmetadata-ui/src/main/resources/ui/src/pages/IncidentManager/IncidentManagerPage.browser.test.tsx new file mode 100644 index 000000000000..9960133a8522 --- /dev/null +++ b/openmetadata-ui/src/main/resources/ui/src/pages/IncidentManager/IncidentManagerPage.browser.test.tsx @@ -0,0 +1,149 @@ +/* + * 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. + */ +/** + * Incident list paging is offset based (testCaseIncidentStatus/search/list), + * so it does not use the shared cursor contract. A page change must send one + * request, and the rows must stay those of the page the pager shows even when + * an earlier request answers last (issue 38927). + */ +import { delay, http, HttpResponse } from 'msw'; +import { describe, expect, test } from 'vitest'; +import { page, userEvent } from 'vitest/browser'; +import { PAGE_SIZE_BASE } from '../../constants/constants'; +import { + Severities, + TestCaseResolutionStatus, + TestCaseResolutionStatusTypes, +} from '../../generated/tests/testCaseResolutionStatus'; +import { many, named } from '../../test/browser/fixtures/entities'; +import { worker } from '../../test/browser/msw'; +import { networkIdle } from '../../test/browser/network'; +import { renderApp } from '../../test/browser/renderWithApp'; +import { scaled } from '../../test/browser/timeouts'; + +const TOTAL = 35; +const TABLE_FQN = 'pw_service.pw_db.pw_schema.pw_table'; +const SLOW_RESPONSE_MS = 1_000; + +const incidents: TestCaseResolutionStatus[] = many(TOTAL, (i) => { + const testCase = named('incident', i, TABLE_FQN); + + return { + id: testCase.id, + stateId: testCase.id, + timestamp: 1_700_000_000_000 - i, + updatedAt: 1_700_000_000_000 - i, + severity: Severities.Severity1, + testCaseResolutionStatusType: TestCaseResolutionStatusTypes.New, + testCaseReference: { ...testCase, type: 'testCase' }, + }; +}); + +const rowLabel = (i: number) => named('incident', i).displayName; + +/** + * Serves the incident list by offset and records the offset of every list + * request. While `slowFirstPage` is set, page 1 answers after the others, the + * order that left page-1 rows under a "Page 3 of 3" pager. + */ +const serveIncidents = () => { + const offsets: number[] = []; + const control = { offsets, slowFirstPage: false }; + worker.use( + http.get( + '/api/v1/dataQuality/testCases/testCaseIncidentStatus/search/list', + async ({ request }) => { + const url = new URL(request.url); + const offset = Number(url.searchParams.get('offset') ?? 0); + const limit = Number(url.searchParams.get('limit') ?? PAGE_SIZE_BASE); + offsets.push(offset); + if (control.slowFirstPage && offset === 0) { + await delay(SLOW_RESPONSE_MS); + } + + return HttpResponse.json({ + data: incidents.slice(offset, offset + limit), + paging: { offset, limit, total: TOTAL }, + }); + } + ) + ); + + return control; +}; + +const expectPage = async (first: number, pageNumber: number) => { + await expect + .element(page.getByText(rowLabel(first), { exact: true })) + .toBeVisible(); + await expect + .element(page.getByTestId('page-indicator')) + .toHaveTextContent(new RegExp(`${pageNumber}\\s*of\\s*3`)); +}; + +describe('Incident Manager pagination', () => { + test( + 'Next sends one request per page and keeps that page when page 1 answers late', + async () => { + const list = serveIncidents(); + await renderApp('/incident-manager'); + + await expect + .element(page.getByText(rowLabel(1), { exact: true }), { + timeout: scaled(60_000), + }) + .toBeVisible(); + + await networkIdle(); + list.offsets.length = 0; + list.slowFirstPage = true; + + await userEvent.click(page.getByTestId('next')); + await expectPage(PAGE_SIZE_BASE + 1, 2); + await userEvent.click(page.getByTestId('next')); + await expectPage(2 * PAGE_SIZE_BASE + 1, 3); + // networkIdle waits for every request in flight, so a page-1 request, + // if one was sent, has answered before the rows are checked again. + await networkIdle(); + + expect(list.offsets).toEqual([PAGE_SIZE_BASE, 2 * PAGE_SIZE_BASE]); + + await expectPage(2 * PAGE_SIZE_BASE + 1, 3); + + expect(page.getByText(rowLabel(1), { exact: true }).query()).toBeNull(); + expect(new URL(location.href).searchParams.get('currentPage')).toBe('3'); + }, + scaled(90_000) + ); + + test( + 'a reload on page 3 fetches page 3, and Previous fetches page 2 once', + async () => { + const list = serveIncidents(); + await renderApp('/incident-manager?currentPage=3'); + + await expectPage(2 * PAGE_SIZE_BASE + 1, 3); + await networkIdle(); + + expect(list.offsets).toEqual([2 * PAGE_SIZE_BASE]); + + list.offsets.length = 0; + await userEvent.click(page.getByTestId('previous')); + await expectPage(PAGE_SIZE_BASE + 1, 2); + await networkIdle(); + + expect(list.offsets).toEqual([PAGE_SIZE_BASE]); + }, + scaled(90_000) + ); +});