Skip to content
Open
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
Expand Up @@ -50,21 +50,6 @@ vi.mock('@/v2/hooks/useAPIData.hook', async (importOriginal) => {
return {
...actual,
useApiData: <T,>(url: string, defaultValue: T, options = {}) => {
// Containers fetches clusterState with initialFetch: true and again via useAutoReload on mount;
// the second call aborts the first, which surfaces as unhandled CanceledError in tests.
if (url === '/api/v1/clusterState') {
return {
data: ClusterState as T,
loading: false,
error: null,
lastUpdated: Date.now(),
success: true,
execute: vi.fn(),
refetch: vi.fn(() => Promise.resolve({ data: ClusterState })),
clearError: vi.fn(),
reset: vi.fn(),
};
}
return actual.useApiData(url, defaultValue, {
...options,
retryAttempts: 0,
Expand Down Expand Up @@ -92,6 +77,7 @@ async function waitForLoadingToFinish(container: HTMLElement) {

describe('Containers Component', () => {
beforeEach(() => {
sessionStorage.removeItem('autoReloadEnabled');
vi.mocked(commonUtils.showDataFetchError).mockClear();
});
beforeAll(() => containersServer.listen());
Expand All @@ -111,6 +97,34 @@ describe('Containers Component', () => {
expect(getEnabledSearchInput()).toBeInTheDocument();
});

test.each([null, 'true', 'false'])('loads each initial endpoint once with auto reload %s', async (enabled) => {
if (enabled !== null) {
sessionStorage.setItem('autoReloadEnabled', enabled);
}
const requests: string[] = [];
const countRequest = ({ request }: { request: Request }) => {
requests.push(new URL(request.url).pathname);
};
containersServer.events.on('request:start', countRequest);
try {
render(<Containers />);
await waitForContainerRows();
await waitFor(() => expect(highlightValue('Total Containers')).toHaveTextContent(
new RegExp(`^${ClusterState.containers}$`)));
await waitFor(() => expect(highlightValue('Quasi Closed')).toHaveTextContent(/^2$/));
for (const endpoint of [
'/api/v1/clusterState',
'/api/v1/containers/unhealthy/MISSING',
'/api/v1/containers/quasiClosed',
]) {
expect(requests.filter(url => url === endpoint)).toHaveLength(1);
}
} finally {
containersServer.events.removeListener('request:start', countRequest);
sessionStorage.removeItem('autoReloadEnabled');
}
});

test('Loads data on mount', async () => {
render(<Containers />);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 React from 'react';
import { act, fireEvent, render, screen } from '@testing-library/react';
import { vi } from 'vitest';
import { useAutoReload } from '@/v2/hooks/useAutoReload.hook';

function TestAutoReload({ refresh }: { refresh: () => void }) {
const autoReload = useAutoReload(refresh, 1000);
return <button onClick={() => autoReload.handleAutoReloadToggle(!autoReload.isPolling)}>
{autoReload.isPolling ? 'Stop' : 'Start'}
</button>;
}

describe('useAutoReload', () => {
beforeEach(() => {
vi.useFakeTimers();
sessionStorage.removeItem('autoReloadEnabled');
});
afterEach(() => {
vi.useRealTimers();
sessionStorage.removeItem('autoReloadEnabled');
});

test.each([null, 'true', 'false'])('loads once on mount with auto reload %s', (enabled) => {
if (enabled !== null) {
sessionStorage.setItem('autoReloadEnabled', enabled);
}
const refresh = vi.fn();
const { unmount } = render(<TestAutoReload refresh={refresh} />);
expect(refresh).toHaveBeenCalledTimes(1);
act(() => { vi.advanceTimersByTime(1000); });
expect(refresh).toHaveBeenCalledTimes(enabled === 'false' ? 1 : 2);
unmount();
act(() => { vi.advanceTimersByTime(2000); });
expect(refresh).toHaveBeenCalledTimes(enabled === 'false' ? 1 : 2);
});

test('stops and resumes polling with the latest refresh callback', () => {
const refresh = vi.fn();
const latestRefresh = vi.fn();
const { rerender, unmount } = render(<TestAutoReload refresh={refresh} />);
fireEvent.click(screen.getByText('Stop'));
act(() => { vi.advanceTimersByTime(1000); });
expect(refresh).toHaveBeenCalledTimes(1);
rerender(<TestAutoReload refresh={latestRefresh} />);
fireEvent.click(screen.getByText('Start'));
expect(latestRefresh).toHaveBeenCalledTimes(1);
act(() => { vi.advanceTimersByTime(1000); });
expect(latestRefresh).toHaveBeenCalledTimes(2);
unmount();
expect(vi.getTimerCount()).toBe(0);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,17 @@ describe('Pipelines Component', () => {
expect(table).toHaveTextContent('CLOSED');
});

test('loads data when auto refresh is disabled', async () => {
sessionStorage.setItem('autoReloadEnabled', 'false');
try {
render(<Pipelines />);
const rows = await waitFor(() => screen.getAllByTestId(pipelineLocators.pipelineRowRegex));
expect(rows).toHaveLength(3);
} finally {
sessionStorage.removeItem('autoReloadEnabled');
}
});

test('Renders table with correct number of rows', async () => {
render(<Pipelines />);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,13 @@ export function useAutoReload(
}
};

// Initialize polling on mount if auto-reload is enabled
// Load on mount and initialize polling if auto-reload is enabled
useEffect(() => {
const autoReloadEnabled = sessionStorage.getItem('autoReloadEnabled') !== 'false';
if (autoReloadEnabled) {
startPolling();
} else {
refreshFunctionRef.current();
}

return () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ const Containers: React.FC<{}> = () => {
CONSTANTS.DEFAULT_CLUSTER_STATE,
{
retryAttempts: 2,
initialFetch: true,
initialFetch: false,
onError: (error) => showDataFetchError(error)
}
);
Expand Down Expand Up @@ -425,11 +425,6 @@ const Containers: React.FC<{}> = () => {
}
};

useEffect(() => {
fetchTabData('1', 0, DEFAULT_PAGE_SIZE);
fetchQuasiClosedCount();
}, []); // eslint-disable-line react-hooks/exhaustive-deps

function handleColumnChange(selected: ValueType<Option, true>) {
setSelectedColumns(selected as Option[]);
}
Expand Down