Загрузка данных


import { act, render } from '@testing-library/react';

import { MoexChart, Timeframes } from 'moex-chart';
import React from 'react';

import { useChangeProperties, useSelectProperties } from '@modules/widgetProperties';
import { ChartIndicativeData } from '@widgets/Chart/types';

import { useMoexChart } from '../components/MoexChart/hooks';

// Mock the dependencies
jest.mock('@modules/widgetProperties');

jest.mock('../components/MoexChart/dataSourceProvide', () => ({
  DataSourceProvider: jest.fn(),
}));

jest.mock('moex-chart', () => ({
  MoexChart: jest.fn(),
  Timeframes: {
    '10s': '10s',
    '1m': '1m',
    '5m': '5m',
  },
  DateFormat: {
    DD_MM_YYYY_HH_mm_ss: 'DD_MM_YYYY_HH_mm_ss',
  },
  IndicatorsIds: {
    Volume: 'Volume',
  },
  Locale: {
    rus: 'ru-RU',
    eng: 'en-US',
  },
}));

jest.mock('@api/index', () => ({
  updateMenuLocked: jest.fn(),
  widgetsController: {
    delete: jest.fn(),
  },
  widgetPropertiesController: {
    update: jest.fn(),
  },
  workspaceController: {
    update: jest.fn(),
  },
}));

jest.mock('@api/controllers/workspace', () => ({
  workspaceController: {
    update: jest.fn(),
  },
}));

const mockedDataSourceProvide = jest.requireMock('../components/MoexChart/dataSourceProvide') as {
  DataSourceProvider: jest.Mock;
};

type TimeframeValue = (typeof Timeframes)[keyof typeof Timeframes];

interface MockPaneSnapshot {
  indicators: unknown[];
}

interface MockChartSnapshot {
  charts: {
    symbol: string;
    timeframe: TimeframeValue;
    chartSeriesType: string;
    panes: MockPaneSnapshot[];
  }[];
}

interface MockMoexChartConfig {
  container: HTMLElement;
  snapshot: MockChartSnapshot;
  chartCollectionPreset: {
    openCompareModal: () => void;
    openSymbolSearchModal: () => void;
    getDataSource: jest.Mock;
    startRealtime: (
      getSymbols: () => string[],
      getTimeframe: () => TimeframeValue,
      update: jest.Mock,
    ) => (() => void) | undefined;
  };
}

interface MockMoexChartState {
  tf?: TimeframeValue;
  initialInterval?: string;
  savedData?: string;
}

interface MockPropertiesState {
  moexChartState?: MockMoexChartState;
}

type UpdatePropertiesCallback = (state: MockPropertiesState) => void;

type TimeframeChangeCallback = (timeframe: TimeframeValue) => void;

interface TestComponentProps {
  symbol?: string;
}

describe('useMoexChart', () => {
  const mockUseSelectProperties = useSelectProperties as jest.Mock;
  const mockUseChangeProperties = useChangeProperties as jest.Mock;
  const mockMoexChart = MoexChart as jest.Mock;
  const mockDataSourceProvider = mockedDataSourceProvide.DataSourceProvider;

  const mockUpdateProperties = jest.fn();

  const mockDestroy = jest.fn();
  const mockGetSnapshot = jest.fn();
  const mockSetSnapshot = jest.fn();
  const mockSetSymbol = jest.fn();
  const mockGetCompareManager = jest.fn();
  const mockSetSettings = jest.fn();

  const mockDataSource = jest.fn();
  const mockStartRealtime = jest.fn();
  const mockGetDataSource = jest.fn();
  const mockRealtimeUnsubscribe = jest.fn();

  const mockCompareManager = {
    id: 'compare-manager',
  };

  const mockSnapshot: MockChartSnapshot = {
    charts: [
      {
        symbol: 'OLD:SYMBOL',
        timeframe: Timeframes['5m'],
        chartSeriesType: 'Candlestick',
        panes: [
          {
            indicators: [],
          },
        ],
      },
    ],
  };

  let hookResult: ReturnType<typeof useMoexChart> | null = null;
  let lastMoexChartConfig: MockMoexChartConfig | null = null;
  let mockMoexChartState: MockMoexChartState | undefined;

  const TestComponent = ({ symbol = 'MOEX:SBER' }: TestComponentProps): React.ReactElement => {
    hookResult = useMoexChart({
      symbol,
      indicativeData: undefined,
    });

    return <div ref={hookResult.containerRef} />;
  };

  beforeEach(() => {
    jest.clearAllMocks();

    hookResult = null;
    lastMoexChartConfig = null;

    mockMoexChartState = {
      tf: Timeframes['1m'],
      savedData: undefined,
    };

    mockUseSelectProperties.mockImplementation((selector: (state: MockPropertiesState) => unknown) =>
      selector({
        moexChartState: mockMoexChartState,
      }),
    );

    mockUseChangeProperties.mockReturnValue({
      updateProperties: mockUpdateProperties,
    });

    mockGetDataSource.mockImplementation(
      (_indicativeData?: ChartIndicativeData, callback?: (timeframe: Timeframes) => void) =>
        (timeframe: Timeframes) => {
          callback?.(timeframe);

          return mockDataSource();
        },
    );

    mockStartRealtime.mockReturnValue(mockRealtimeUnsubscribe);

    mockDataSourceProvider.mockImplementation(() => ({
      getDataSource: mockGetDataSource,
      startRealtime: mockStartRealtime,
    }));

    mockGetSnapshot.mockReturnValue(mockSnapshot);
    mockGetCompareManager.mockReturnValue(mockCompareManager);

    mockMoexChart.mockImplementation((config: MockMoexChartConfig) => {
      lastMoexChartConfig = config;

      return {
        destroy: mockDestroy,
        getSnapshot: mockGetSnapshot,
        setSnapshot: mockSetSnapshot,
        setSymbol: mockSetSymbol,
        getCompareManager: mockGetCompareManager,
        setSettings: mockSetSettings,
      };
    });
  });

  it('should create moex chart with current symbol and timeframe', () => {
    // Arrange & Act
    render(<TestComponent symbol="MOEX:SBER" />);

    // Assert
    expect(mockMoexChart).toHaveBeenCalledTimes(1);
    expect(mockDataSourceProvider).toHaveBeenCalledTimes(1);

    expect(lastMoexChartConfig?.container).toBeInstanceOf(HTMLDivElement);
    expect(lastMoexChartConfig?.snapshot.charts[0]?.symbol).toBe('MOEX:SBER');
    expect(lastMoexChartConfig?.snapshot.charts[0]?.timeframe).toBe(Timeframes['1m']);

    expect(hookResult?.compareManagerRef.current).toBe(mockCompareManager);
  });

  it('should create chart with saved snapshot when saved data exists', () => {
    // Arrange
    mockMoexChartState = {
      tf: Timeframes['5m'],
      savedData: JSON.stringify(mockSnapshot),
    };

    // Act
    render(<TestComponent symbol="MOEX:GAZP" />);

    // Assert
    expect(lastMoexChartConfig?.snapshot.charts[0]?.symbol).toBe('MOEX:GAZP');
    expect(lastMoexChartConfig?.snapshot.charts[0]?.timeframe).toBe(Timeframes['5m']);

    expect(hookResult?.hasSavedSnapshot).toBe(true);
  });

  it('should save chart snapshot to widget properties', () => {
    // Arrange
    render(<TestComponent symbol="MOEX:SBER" />);

    // Act
    act(() => {
      hookResult?.saveSnapshot();
    });

    // Assert
    expect(mockGetSnapshot).toHaveBeenCalledTimes(1);
    expect(mockUpdateProperties).toHaveBeenCalledTimes(1);

    const updateCallback = mockUpdateProperties.mock.calls[0]?.[0] as UpdatePropertiesCallback;

    const mockState: MockPropertiesState = {
      moexChartState: {
        tf: Timeframes['1m'],
      },
    };

    updateCallback(mockState);

    expect(mockState.moexChartState).toEqual({
      tf: Timeframes['1m'],
      savedData: JSON.stringify(mockSnapshot),
    });
  });

  it('should not save snapshot when chart does not return snapshot', () => {
    // Arrange
    mockGetSnapshot.mockReturnValue(undefined);

    render(<TestComponent symbol="MOEX:SBER" />);

    // Act
    act(() => {
      hookResult?.saveSnapshot();
    });

    // Assert
    expect(mockGetSnapshot).toHaveBeenCalledTimes(1);
    expect(mockUpdateProperties).not.toHaveBeenCalled();
  });

  it('should apply saved snapshot with current symbol and timeframe', () => {
    // Arrange
    mockMoexChartState = {
      tf: Timeframes['5m'],
      savedData: JSON.stringify(mockSnapshot),
    };

    render(<TestComponent symbol="MOEX:SBER" />);

    // Act
    act(() => {
      hookResult?.applySnapshot();
    });

    // Assert
    expect(mockSetSnapshot).toHaveBeenCalledWith({
      ...mockSnapshot,
      charts: [
        {
          ...mockSnapshot.charts[0],
          symbol: 'MOEX:SBER',
          timeframe: Timeframes['5m'],
        },
      ],
    });

    expect(hookResult?.compareManagerRef.current).toBe(mockCompareManager);
  });

  it('should update compare modal state', () => {
    // Arrange
    render(<TestComponent symbol="MOEX:SBER" />);

    // Act
    act(() => {
      hookResult?.setIsCompareOpen(true);
    });

    // Assert
    expect(hookResult?.isCompareOpen).toBe(true);
  });

  it('should open compare modal from chart preset callback', () => {
    // Arrange
    render(<TestComponent symbol="MOEX:SBER" />);

    // Act
    act(() => {
      lastMoexChartConfig?.chartCollectionPreset.openCompareModal();
    });

    // Assert
    expect(hookResult?.isCompareOpen).toBe(true);
  });

  it('should update symbol search modal state', () => {
    // Arrange
    render(<TestComponent symbol="MOEX:SBER" />);

    // Act
    act(() => {
      hookResult?.setIsSymbolSearchOpen(true);
    });

    // Assert
    expect(hookResult?.isSymbolSearchOpen).toBe(true);
  });

  it('should open symbol search modal from chart preset callback', () => {
    // Arrange
    render(<TestComponent symbol="MOEX:SBER" />);

    // Act
    act(() => {
      lastMoexChartConfig?.chartCollectionPreset.openSymbolSearchModal();
    });

    // Assert
    expect(hookResult?.isSymbolSearchOpen).toBe(true);
  });

  it('should normalize and change main symbol', () => {
    // Arrange
    render(<TestComponent symbol="MOEX:SBER" />);

    // Act
    act(() => {
      hookResult?.setMainSymbol('  MOEX:GAZP  ');
    });

    // Assert
    expect(mockSetSymbol).toHaveBeenCalledTimes(1);
    expect(mockSetSymbol).toHaveBeenCalledWith('MOEX:GAZP');
  });

  it('should not change main symbol when value is empty', () => {
    // Arrange
    render(<TestComponent symbol="MOEX:SBER" />);

    // Act
    act(() => {
      hookResult?.setMainSymbol('');
      hookResult?.setMainSymbol('   ');
    });

    // Assert
    expect(mockSetSymbol).not.toHaveBeenCalled();
  });

  it('should not change main symbol when it is already selected', () => {
    // Arrange
    render(<TestComponent symbol="MOEX:SBER" />);

    // Act
    act(() => {
      hookResult?.setMainSymbol('MOEX:SBER');
    });

    // Assert
    expect(mockSetSymbol).not.toHaveBeenCalled();
  });

  it('should update chart when external symbol changes', () => {
    // Arrange
    const { rerender } = render(<TestComponent symbol="MOEX:SBER" />);

    // Act
    rerender(<TestComponent symbol="MOEX:GAZP" />);

    // Assert
    expect(mockSetSymbol).toHaveBeenCalledTimes(1);
    expect(mockSetSymbol).toHaveBeenCalledWith('MOEX:GAZP');
  });

  it('should not recreate chart when external symbol changes', () => {
    // Arrange
    const { rerender } = render(<TestComponent symbol="MOEX:SBER" />);

    // Act
    rerender(<TestComponent symbol="MOEX:GAZP" />);

    // Assert
    expect(mockMoexChart).toHaveBeenCalledTimes(1);
  });

  it('should apply saved snapshot with symbol selected from search modal', () => {
    // Arrange
    mockMoexChartState = {
      tf: Timeframes['5m'],
      savedData: JSON.stringify(mockSnapshot),
    };

    render(<TestComponent symbol="MOEX:SBER" />);

    act(() => {
      hookResult?.setMainSymbol('MOEX:GAZP');
    });

    // Act
    act(() => {
      hookResult?.applySnapshot();
    });

    // Assert
    expect(mockSetSnapshot).toHaveBeenCalledWith({
      ...mockSnapshot,
      charts: [
        {
          ...mockSnapshot.charts[0],
          symbol: 'MOEX:GAZP',
          timeframe: Timeframes['5m'],
        },
      ],
    });
  });

  it('should pass realtime params to data source provider', () => {
    // Arrange
    render(<TestComponent symbol="MOEX:SBER" />);

    const getSymbols = jest.fn(() => ['MOEX:SBER']);
    const getTimeframe = jest.fn(() => Timeframes['1m']);
    const update = jest.fn();

    // Act
    const unsubscribe = lastMoexChartConfig?.chartCollectionPreset.startRealtime(getSymbols, getTimeframe, update);

    // Assert
    expect(mockStartRealtime).toHaveBeenCalledWith({
      getSymbols,
      getTimeframe,
      update,
    });

    expect(unsubscribe).toBe(mockRealtimeUnsubscribe);
  });

  it('should update timeframe from data source callback', () => {
    // Arrange
    render(<TestComponent symbol="MOEX:SBER" />);

    const timeframeChangeCallback = mockGetDataSource.mock.calls[0]?.[1] as TimeframeChangeCallback;

    // Act
    act(() => {
      timeframeChangeCallback(Timeframes['5m']);
    });

    // Assert
    expect(mockUpdateProperties).toHaveBeenCalledTimes(1);

    const updateCallback = mockUpdateProperties.mock.calls[0]?.[0] as UpdatePropertiesCallback;

    const mockState: MockPropertiesState = {
      moexChartState: {
        tf: Timeframes['1m'],
      },
    };

    updateCallback(mockState);

    expect(mockState.moexChartState?.tf).toBe(Timeframes['5m']);
  });

  it('should not update timeframe when it is the same as current timeframe', () => {
    // Arrange
    render(<TestComponent symbol="MOEX:SBER" />);

    const timeframeChangeCallback = mockGetDataSource.mock.calls[0]?.[1] as TimeframeChangeCallback;

    // Act
    act(() => {
      timeframeChangeCallback(Timeframes['1m']);
    });

    // Assert
    expect(mockUpdateProperties).not.toHaveBeenCalled();
  });

  it('should destroy chart on unmount', () => {
    // Arrange
    const { unmount } = render(<TestComponent symbol="MOEX:SBER" />);

    // Act
    unmount();

    // Assert
    expect(mockDestroy).toHaveBeenCalledTimes(1);
  });
  it('should apply initial interval on chart creation', () => {
    // Arrange
    mockMoexChartState = {
      tf: Timeframes['1m'],
      savedData: undefined,
      initialInterval: '1Y',
    };
    // Act
    render(<TestComponent symbol="MOEX:SBER" />);
    // Assert
    expect(mockSetSettings).toHaveBeenCalledWith({ interval: '1Y' });
  });
  it('should apply initial interval even when saved data exists', () => {
    // Arrange
    mockMoexChartState = {
      tf: Timeframes['5m'],
      savedData: JSON.stringify(mockSnapshot),
      initialInterval: '1Y',
    };
    // Act
    render(<TestComponent symbol="MOEX:SBER" />);
    // Assert
    expect(mockSetSettings).toHaveBeenCalledWith({ interval: '1Y' });
  });
  it('should clear initial interval in widget properties after applying', () => {
    // Arrange
    mockMoexChartState = {
      tf: Timeframes['1m'],
      savedData: undefined,
      initialInterval: '1Y',
    };
    // Act
    render(<TestComponent symbol="MOEX:SBER" />);
    // Assert
    expect(mockUpdateProperties).toHaveBeenCalledTimes(1);
    const updateCallback = mockUpdateProperties.mock.calls[0]?.[0] as UpdatePropertiesCallback;
    const mockState: MockPropertiesState = {
      moexChartState: {
        tf: Timeframes['1m'],
        initialInterval: '1Y',
      },
    };
    updateCallback(mockState);
    expect(mockState.moexChartState?.initialInterval).toBeUndefined();
  });
  it('should not apply interval when initial interval is not set', () => {
    // Arrange
    render(<TestComponent symbol="MOEX:SBER" />);
    // Assert
    expect(mockSetSettings).not.toHaveBeenCalled();
  });
});