import React from 'react';
import { render, cleanup, waitFor, fireEvent } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';

import { registerScroll, getScroll, debounce } from './scroll';

export default function ScrollTest() {
  registerScroll();

  return (
    <>
      <div className="containerScroll" style={{ height: '10000px' }}>
        <h1>testing scroll</h1>
      </div>
    </>
  );
}
jest.useFakeTimers();
describe('Scroll test', () => {
  test('registerScroll test', async () => {
    const { baseElement } = render(<ScrollTest />);
    fireEvent.scroll(window, { target: { scrollY: 500 } });
    await waitFor(() => {
      expect(baseElement).toHaveAttribute('data-scroll', '500');
    }, 0);
  });

  test('getScroll test', async () => {
    render(<ScrollTest />);
    fireEvent.scroll(window, { target: { scrollY: 500 } });
    await waitFor(() => {
      expect(getScroll()).toEqual('500');
    }, 0);
  });

  let func = jest.Mock;
  let debouncedFunc = Function;

  beforeEach(() => {
    func = jest.fn();
    debouncedFunc = debounce(func, 1000);
  });

  test('debounce test', async () => {
    for (let i = 0; i < 100; i += 1) {
      debouncedFunc();
    }

    // fast-forward time
    jest.runAllTimers();

    expect(func).toBeCalledTimes(1);
  });
});
afterEach(() => {
  cleanup();
});
