import {render, waitFor} from '@testing-library/react';
import {useExportFile} from '.';
import {QueryClient, QueryClientProvider} from '@tanstack/react-query';
import {FC} from 'react';
import {act} from 'react-dom/test-utils';

const fn = jest.fn();
function mockAsync() {
  return new Promise(function(res) {
    setTimeout(function() {
      fn();
      res(1);
    }, 200);
  });
}

describe('useExportFile', function() {
  Object.assign(global, {
    URL: {
      createObjectURL(val: string) {
        return val;
      },
    },
    open() {
      /** mock fn */
    },
  });

  beforeEach(function() {
    fn.mockClear();
    jest.useFakeTimers();
  });

  it('定义正确', function() {
    expect(useExportFile).toBeDefined();

    expect(useExportFile).toBeInstanceOf(Function);
  });

  it('测试组件操作', async function() {
    const client = new QueryClient();

    const App: FC = function() {
      const [isExporting, mutate] = useExportFile(mockAsync);

      return (
        <>
          <p data-testid='state'>{isExporting.toString()}</p>
          <button onClick={mutate} data-testid='btn' />
        </>
      );
    };

    const {getByTestId} = render(<QueryClientProvider client={client}>
      <App />
    </QueryClientProvider>);

    expect(getByTestId('state').innerHTML).toBe('false');

    act(function() {
      getByTestId('btn').click();
    });

    await waitFor(function() {
      expect(getByTestId('state').innerHTML).toBe('true');
    });

    await waitFor(function() {
      expect(getByTestId('state').innerHTML).toBe('false');
    });

    expect(fn).toBeCalled();
  });
});
