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

import CustomSelect from '.';

const items = [
  { key: 'All', value: '0' },
  { key: 'option one', value: '1' },
  { key: 'option two', value: '2' },
  { key: 'option three' },
];
describe('Custom Select Component', () => {
  test('render with props', () => {
    const { container, getByText } = render(
      <CustomSelect
        items={items}
        itemsValue="value"
        itemsLabel="key"
        activeItem={{ key: 'All', value: '0' }}
        onClick={() => {}}
      />
    );
    expect(container.querySelectorAll('li.selectListItem')).toHaveLength(3);
    expect(getByText('option two')).toBeTruthy();
    expect(getByText('option one')).toBeTruthy();
    const btn = container.querySelector('button.select');
    expect(btn.innerHTML).toBe('All');
    expect(container.querySelectorAll('li.selectListItem')[2].getAttribute('data-value')).toEqual(
      'id'
    );
    expect(container.querySelectorAll('li.selectListItem')[2].getAttribute('data-type')).toEqual(
      'type'
    );
  });

  test('open select', () => {
    const { container } = render(
      <CustomSelect
        items={items}
        itemsValue="value"
        itemsLabel="key"
        activeItem={{ key: 'All', value: '0' }}
        onClick={() => {}}
      />
    );
    const btn = container.querySelector('button.select');
    const list = container.querySelector('ol.list');
    fireEvent.click(btn);
    expect(list.classList).toContain('show');
    expect(btn.classList).toContain('flip');
  });

  test('click an item', () => {
    const mockFn = jest.fn();
    const { container, getByText } = render(
      <CustomSelect
        items={items}
        itemsValue="value"
        itemsLabel="key"
        activeItem={{ key: 'All', value: '0' }}
        onClick={mockFn}
      />
    );
    const btn = container.querySelector('button.select');
    fireEvent.click(btn);
    fireEvent.click(getByText('option two'));
    expect(mockFn).toHaveBeenCalled();
  });
});
afterEach(() => {
  cleanup();
});
