import { shallow } from 'enzyme';
import React from 'react';
import {
  BranchTimedTracker,
  BranchTimedTrackerProps,
} from './branchTimedTracker';
import { BranchEvent } from './branchUtils';

jest.useFakeTimers();
const DEFAULT_PROPS: BranchTimedTrackerProps = {
  delaySecondsUntilTrack: 1,
  deviceID: '321',
  event: BranchEvent.FiveMinutePlay,
  sessionID: '123',
};

describe('<BranchTimedTracker />', () => {
  it('kicks off a timer on mount', () => {
    const subject = shallow(<BranchTimedTracker {...DEFAULT_PROPS} />, {
      disableLifecycleMethods: true,
    });
    const instance = subject.instance() as BranchTimedTracker;
    const trackEvent = jest.fn();
    instance.trackEvent = trackEvent;

    instance.componentDidMount();
    expect(trackEvent.mock.calls.length).toBe(0);
    jest.runAllTimers();
    expect(trackEvent.mock.calls.length).toBe(1);
  });

  it('closes branch timer on unmount and does not track after unmount', () => {
    const subject = shallow(<BranchTimedTracker {...DEFAULT_PROPS} />, {
      disableLifecycleMethods: true,
    });
    const instance = subject.instance() as BranchTimedTracker;
    const trackEvent = jest.fn();
    instance.trackEvent = trackEvent;

    instance.componentDidMount();
    expect(trackEvent.mock.calls.length).toBe(0);

    instance.componentWillUnmount();
    jest.runAllTimers();
    expect(trackEvent.mock.calls.length).toBe(0);
  });
});
