import React from 'react';
import userEvent from '@testing-library/user-event';
import { render, screen } from '@testing-library/react';

import TextInput from './TextInput';

let clearErrorsCallback, setDataCallback;

beforeEach(() => {
  clearErrorsCallback = jest.fn();

  setDataCallback = jest.fn();
});

describe('TextInput component', () => {
  /** @test */
  test('renders a text input element', () => {
    render(
      <TextInput
        clearErrors={clearErrorsCallback}
        id="text_input_test"
        setData={setDataCallback}
        value="sample text"
      />,
    );

    const textInputElement = screen.getByTestId('text-input-element');

    expect(textInputElement).toHaveAttribute('type', 'text');
  });

  /** @test */
  test('will trigger clearErrors and setData methods on input change event', () => {
    render(
      <TextInput
        clearErrors={clearErrorsCallback}
        id="text_input_test"
        setData={setDataCallback}
        value=""
      />,
    );

    const textInputElement = screen.getByTestId('text-input-element');

    userEvent.type(textInputElement, 'hi');
    const calls = setDataCallback.mock.calls;

    expect(clearErrorsCallback).toHaveBeenCalledTimes(2);
    expect(setDataCallback).toHaveBeenCalledTimes(2);

    expect(calls[0]).toEqual(['text_input_test', 'h']);
    expect(calls[1]).toEqual(['text_input_test', 'i']);
  });
});