import {PageProvider} from '@components';
import {usePage, createPageContext} from '.';
import {fireEvent, render, renderHook} from '@testing-library/react';
import {PAGE_SIZE_LIST} from '@utils';
import {FC} from 'react';

describe('usePageContext', function() {
  it('usePage, createContext 类型正确', function() {
    expect(usePage).toBeDefined();
    expect(createPageContext).toBeDefined();

    expect(usePage).toBeInstanceOf(Function);
    expect(createPageContext).toBeInstanceOf(Function);
  });

  it('usePage 返回值正确', function() {
    const {result} = renderHook(function() {
      const context = createPageContext();

      return usePage(context);
    });

    expect(result.current[0]).toEqual({page: 1, pageSize: Number(PAGE_SIZE_LIST[0])});
    expect(result.current[1].onCurrentPageChange).toBeInstanceOf(Function);
    expect(result.current[1].onPageChange).toBeInstanceOf(Function);
  });

  it('修改值', function() {
    const context = createPageContext();

    const Child: FC = function() {
      const [{page, pageSize}] = usePage(context);

      return (
        <>
          <p data-testid='page'>{page}</p>
          <p data-testid='page_size'>{pageSize}</p>
        </>
      );
    };

    const Button: FC = function() {
      const [,{onCurrentPageChange, onPageChange}] = usePage(context);

      function onCurrent() {
        onCurrentPageChange(2);
      }
      function onPage() {
        onPageChange(3, 20);
      }

      return (
        <>
          <button onClick={onCurrent} data-testid='current_btn' />
          <button onClick={onPage} data-testid='page_btn' />
        </>
      );
    };

    const App: FC = function() {
      return (
        <PageProvider context={context}>
          <Child />
          <Button />
        </PageProvider>
      );
    };

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

    expect(getByTestId('page').innerHTML).toBe('1');
    expect(getByTestId('page_size').innerHTML).toBe('10');

    fireEvent.click(getByTestId('current_btn'));

    expect(getByTestId('page').innerHTML).toBe('2');
    expect(getByTestId('page_size').innerHTML).toBe('10');

    fireEvent.click(getByTestId('page_btn'));

    expect(getByTestId('page').innerHTML).toBe('3');
    expect(getByTestId('page_size').innerHTML).toBe('20');
  });
});
