import { createComponentFactory, Spectator } from '@ngneat/spectator/jest';
import { RangeDatepickerComponent } from './range-datepicker.component';

describe('RangeDatepickerComponent', () => {
  let spectator: Spectator<RangeDatepickerComponent>;
  const createComponent = createComponentFactory(RangeDatepickerComponent);

  beforeEach(() => {
    spectator = createComponent();
  });

  it('should create the component', () => {
    expect(spectator.component).toBeTruthy();
  });

  it('should set the default displayed date from provided value', () => {
    const testDate = new Date(2021, 0, 1);
    // Provide input value
    spectator.setInput('value', [testDate]);
    const spySet = jest.spyOn(
      spectator.component.viewState.displayedDate,
      'set',
    );

    // Trigger lifecycle hook
    spectator.component.ngAfterViewInit();

    expect(spySet).toHaveBeenCalledWith(testDate);
  });

  it('should default the displayed date to current date when value is undefined', () => {
    // Provide undefined value
    spectator.setInput('value', undefined);
    const spySet = jest.spyOn(
      spectator.component.viewState.displayedDate,
      'set',
    );

    // Trigger lifecycle hook
    spectator.component.ngAfterViewInit();

    const result = spectator.component.setDefaultDisplayedMonthYear();
    const now = Date.now();

    // Check that the resulting date is close to the current date (within one second).
    expect(Math.abs(result.getTime() - now)).toBeLessThan(1000);
    expect(spySet).toHaveBeenCalled();
    const calledWith: Date = spySet.mock.calls[0][0];
    expect(Math.abs(calledWith.getTime() - now)).toBeLessThan(1000);
  });
});
