import React from 'react';
import ReactTestRenderer from 'react-test-renderer';
import Adapter from 'enzyme-adapter-react-16/build/index';
import Enzyme, { mount } from 'enzyme/build/index';
import { Modal } from 'app/shared/components/modal/modal';
import { ConsoleMock } from 'app/testUtils/consoleMock';

describe('Modal tests', () => {
  Enzyme.configure({ adapter: new Adapter() });

  const content = 'content';
  const openedSelector = '.c-modal--opened';
  const closeButtonSelector = '.c-modal__close';

  let consoleMock;

  beforeEach(() => {
    consoleMock = new ConsoleMock();
  });

  afterEach(() => {
    consoleMock.destroy();
  });


  it('renders correctly', () => {
    const tree = ReactTestRenderer
      .create(<Modal/>)
      .toJSON();
    expect(tree).toMatchSnapshot();
    expect(console.error).not.toBeCalled();
  });

  it('renders correctly with content', () => {
    const tree = ReactTestRenderer
      .create(<Modal>
        {content}
      </Modal>)
      .toJSON();
    expect(tree).toMatchSnapshot();
    expect(console.error).not.toBeCalled();
  });

  it('renders correctly centered', () => {
    const tree = ReactTestRenderer
      .create(<Modal centered>
        {content}
      </Modal>)
      .toJSON();
    expect(tree).toMatchSnapshot();
    expect(console.error).not.toBeCalled();
  });

  it('is closed by default', () => {
    const component = mount(<Modal>
      {content}
    </Modal>);
    expect(component.find(openedSelector).exists()).toEqual(false);
    expect(console.error).not.toBeCalled();
  });

  it('fires onClose when close button is clicked', () => {
    const onClose = jest.fn();

    const component = mount(<Modal onClose={onClose}>
      {content}
    </Modal>);

    component.find(closeButtonSelector).simulate('click');
    expect(onClose).toBeCalled();
    expect(console.error).not.toBeCalled();
  });

  it('fires onOverlay when overlay is clicked', () => {
    const onOverlay = jest.fn();

    const component = mount(<Modal onOverlay={onOverlay}>
      {content}
    </Modal>);

    component.find('.js-overlay-hit-area').simulate('click');
    expect(onOverlay).toBeCalled();
    expect(console.error).not.toBeCalled();
  });
});
