import {BaseResult} from '@models';
import {usePutData} from '.';
import {render, waitFor} from '@testing-library/react';
import {FC} from 'react';
import {QueryClient, QueryClientProvider} from '@tanstack/react-query';

const fn = jest.fn();

function mockRequest(): BaseResult {
  fn();
  return new Promise(function (res) {
    setTimeout(() => res({msg: '200', data: 123}), 500);
  });
}

describe('usePutData', function () {
  it('声明', function () {
    expect(usePutData).toBeDefined();
    expect(usePutData).toBeInstanceOf(Function);
  });

  it('返回值', async function () {
    jest.useFakeTimers();

    const App: FC = function () {
      const [isLoading, {addMutate, editMutate}] = usePutData({
        addFn: mockRequest,
        editFn: mockRequest,
        onClose: fn,
        onFetch: fn,
      });

      return (
        <>
          <p data-testid='state'>{isLoading.toString()}</p>
          <button data-testid='add_btn' onClick={addMutate} />
          <button data-testid='edit_btn' onClick={editMutate} />
        </>
      );
    };

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

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

    getByTestId('add_btn').click();

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

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

    expect(fn).toBeCalledTimes(3);

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

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

    expect(fn).toBeCalledTimes(6);
  });
});
