import React from 'react';
import { fireEvent } from '@testing-library/react';
import renderWithTheme from '../../../testUtils/renderWithTheme';

import Checkbox from '../Checkbox';

describe('rendering', () => {
  it('shows text label', () => {
    const { getByText } = renderWithTheme(
      <Checkbox text="Checkbox text" value="checkboxValue" />
    );
    expect(getByText('Checkbox text')).toBeInTheDocument();
  });

  it('allows to customize text', () => {
    const { getByText } = renderWithTheme(
      <Checkbox text={<div>Customised text</div>} value="checkboxValue" />
    );
    expect(getByText('Customised text')).toBeInTheDocument();
  });
});

describe('interaction', () => {
  it('triggers onChange when clicking on', () => {
    const onChange = jest.fn();
    const { getByText } = renderWithTheme(
      <Checkbox
        text="Checkbox text"
        value="checkboxValue"
        onChange={(e): void => onChange(e.target.checked)}
      />
    );
    fireEvent.click(getByText('Checkbox text'));
    expect(onChange).toHaveBeenCalledTimes(1);
    expect(onChange).toHaveBeenCalledWith(true);

    fireEvent.click(getByText('Checkbox text'));
    expect(onChange).toHaveBeenCalledTimes(2);
    expect(onChange).toHaveBeenCalledWith(false);
  });

  it('allows to be controlled', () => {
    const onChange = jest.fn();
    const { getByText } = renderWithTheme(
      <Checkbox
        text="Checkbox text"
        value="checkboxValue"
        checked
        onChange={(e): void => onChange(e.target.checked)}
      />
    );
    fireEvent.click(getByText('Checkbox text'));
    expect(onChange).toHaveBeenCalledTimes(1);
    expect(onChange).toHaveBeenCalledWith(false);

    fireEvent.click(getByText('Checkbox text'));
    expect(onChange).toHaveBeenCalledTimes(2);
    expect(onChange).toHaveBeenCalledWith(false);
  });
});
