// Libs
// -----------------------------------------------------------------------------
import React, { FC, Suspense } from 'react';
import { render } from '@testing-library/react';
import type { RenderOptions } from '@testing-library/react';
import { BrowserRouter } from 'react-router-dom';
import { Spin } from 'antd';

// App
// -----------------------------------------------------------------------------
import { StoreProvider } from 'stores/StoreProvider';
import { RootStore } from 'stores/RootStore';

interface ExtendedRenderOptions extends Omit<RenderOptions, 'queries'> {
  store?: RootStore;
}

// Расширенная функция тестового рендеринга компонента из React Testing Library.
// Добавляет контексты React Router и MobX.
// Позаимствовано с изменениями из документации Redux:
// https://redux.js.org/usage/writing-tests
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
export function testRenderWithProviders(
  ui: React.ReactElement,
  { store = new RootStore(), ...renderOptions }: ExtendedRenderOptions = {},
) {
  const Wrapper: FC = ({ children }) => {
    return (
      <BrowserRouter>
        <Suspense fallback={<Spin size="large" className="spinnerGlobal" />}>
          <StoreProvider value={store}>{children}</StoreProvider>
        </Suspense>
      </BrowserRouter>
    );
  };

  return { store, ...render(ui, { wrapper: Wrapper, ...renderOptions }) };
}
