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

import { getExtraField, imagePrettyUrl } from 'gatsby-core-theme/src/helpers/getters';
import MainProvider from '~context/MainProvider';
import getPageData from '../../../../../../../tests/factories/pages/default.factory';
import TemplateOne from '.';

const translations = {
  online_casino: 'Online Casino',
};

function renderComponent(pageData) {
  return render(
    <MainProvider
      value={{
        bannerIsActive: false,
        cookieAccepted: true,
        translations,
      }}
    >
      <TemplateOne
        title={pageData.title}
        description={pageData.description}
        extraFields={pageData.extra_fields}
        imageObj={pageData.featured_image_object}
      />
    </MainProvider>
  );
}

let data;

beforeEach(() => {
  data = getPageData();
});
describe('Show template one', () => {
  test('render with props', () => {
    const { container } = renderComponent(data);
    expect(container.querySelector('.templateOne')).toBeTruthy();
  });
  test('show correct title', () => {
    const { container } = renderComponent(data);
    expect(container.querySelector('.headerContainer').querySelector('h1')).toBeTruthy();
    expect(container.querySelector('.headerContainer').querySelector('h1').innerHTML).toEqual(
      data.title
    );
  });
  test('show correct description', () => {
    const { container } = renderComponent(data);
    expect(container.querySelector('.headerContainer').querySelector('div').innerHTML).toEqual(
      data.description
    );
  });
  test('show correct url', () => {
    const { container } = renderComponent(data);
    expect(
      container.querySelector('.headerContainer').querySelector('a').innerHTML.split('<svg')[0]
    ).toEqual(getExtraField(data?.extra_fields, 'link'));
  });
  test('show correct image', () => {
    const imgObj = data.featured_image_object;

    // eslint-disable-next-line global-require
    const func = require('gatsby-core-theme/src/helpers/device-detect');
    func.isNativeImageLazyLoadingSupported = jest.fn(() => true);
    const { container } = renderComponent(data);

    expect(container.querySelector('img')).toBeTruthy();
    expect(container.querySelector('img')).toHaveAttribute(
      'src',
      imagePrettyUrl(imgObj.filename, 356, 343)
    );
    expect(container.querySelector('img')).toHaveAttribute('loading', 'eager');
  });
});
afterEach(() => {
  cleanup();
});
