import { cleanup } from '@testing-library/react';
import { render } from '../../../utils/theme-render-wrapper';
import { BrowserRouter } from 'react-router-dom';
import { Link } from './link';

afterEach(cleanup);

const href = 'helloworld';
const linkText = 'hello world';
const onClick = jest.fn();
describe('<Link />', () => {
  it(`Should render table link`, () => {
    const { baseElement } = render(
      <BrowserRouter>
        <Link table href={href}>
          {linkText}
        </Link>
      </BrowserRouter>
    );
    expect(baseElement).toBeTruthy();
  });

  it(`Should render valid HTML link`, () => {
    const { container } = render(
      <BrowserRouter>
        <Link href={href}>{linkText}</Link>
      </BrowserRouter>
    );
    const aTag = container.getElementsByTagName('a');
    const res = aTag[0].href;
    expect(res).toBe(`http://localhost/${href}`);
  });

  it(`Should render link and call onClick handler`, () => {
    const { queryByText } = render(
      <BrowserRouter>
        <Link href={href} onClick={onClick}>
          {linkText}
        </Link>
      </BrowserRouter>
    );
    const aElement = queryByText(linkText);
    aElement?.click();
    expect(onClick).toHaveBeenCalled();
  });

  it(`Should render link without href and "a" tag`, () => {
    const { container } = render(
      <BrowserRouter>
        <Link>{linkText}</Link>
      </BrowserRouter>
    );
    const aElement = container.querySelector('a');
    expect(aElement).toBeFalsy();
  });

  it(`Should render link with external link`, () => {
    const href = 'https://www.example.com';
    const { container } = render(
      <BrowserRouter>
        <Link href={href}>{linkText}</Link>
      </BrowserRouter>
    );
    const aElement = container.querySelector('a');
    expect(aElement?.getAttribute('href')).toBe(href);
  });
});
