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

import ModuleTitle from '.';

describe('Module Title Component', () => {
  test('render with props', () => {
    const { container, getByText } = render(
      <ModuleTitle
        module={{
          module_title: 'New Section',
          module_title_tag: 'h2',
          see_more_link: {
            path: '/all',
            title: 'View More',
            value: 999,
            type: 'page',
          },
        }}
        viewMoreIcon={<i className="arrow-left" />}
      />
    );
    expect(container.querySelector('.moduleTitle')).toBeTruthy();
    expect(container.querySelector('h2').innerHTML).toEqual('New Section');
    expect(getByText('View More')).toBeTruthy();
    expect(container.querySelector('a.viewMore').getAttribute('href')).toEqual('/all');
    expect(container.querySelector('i.arrow-left')).toBeTruthy();
  });

  test('all H elements', () => {
    const arr = ['h2', 'h3', 'h4', 'h5', 'h6'];

    const madeObj = (current) => {
      const obj = {
        module_title_tag: current,
        module_title: `Title with current + ${current} `,
      };
      return obj;
    };

    const arrWithObj = arr.reduce((acc, current) => {
      acc.push(madeObj(current));
      return acc;
    }, []);

    arrWithObj.forEach((element) => {
      const { container } = render(
        <ModuleTitle
          module={{
            name: 'content',
            module_title: element.module_title,
            module_title_tag: element.module_title_tag,
            link_label: 'View More',
            link_value: '/all',
          }}
        />
      );

      expect(container.querySelector(element.module_title_tag)).toBeTruthy();
      // expect(container.querySelector(element.module_title_tag)).toHaveLength(1)
    });
  });

  test('with pageContext', () => {
    const { container, getByText } = render(
      <ModuleTitle
        module={{
          name: 'content',
          module_title: 'Test Title',
          module_title_tag: 'h2',
          see_more_link: {
            path: '/all',
            title: 'View More',
            value: 999,
            type: 'page',
          },
          style: 'Style test',
        }}
        pageContext={{
          page: {
            template: true,
          },
        }}
      />
    );

    expect(getByText('Test Title')).toBeTruthy();
    expect(container.querySelector('a')).toHaveAttribute('href', '/all');
    expect(container.querySelectorAll('a')).toHaveLength(1);
    expect(getByText('View More')).toBeTruthy();
    expect(container.querySelectorAll('svg')).toHaveLength(1);
  });
});
afterEach(() => {
  cleanup();
});
