import React from 'react';
import { combineReducers } from 'redux';
import { renderConnectedComponent, sleep } from '../../../test-utils/dist/js';
import {
  reduxAjaxMiddleware,
  reduxAjaxReducer,
  reduxAjaxReducerKey,
  submitFailure,
  submitPending,
  submitSuccess
} from '../index';
import { useReduxAjax } from '../redux-ajax.hook';

const requestId = 'test';

const Example: React.FC = () => {
  const { Success, Loading, Failure } = useReduxAjax(requestId);
  return (
    <>
      <div>Always visible</div>
      <Success>success</Success>
      <Loading>loading</Loading>
      <Failure>failure</Failure>
    </>
  );
};

const setupTest = () =>
  renderConnectedComponent({
    rootReducer: combineReducers({ [reduxAjaxReducerKey]: reduxAjaxReducer }),
    middlewareList: [reduxAjaxMiddleware({ fetchFn: jest.fn() })]
  })(<Example />);

describe('react-redux-ajax components', () => {
  it('renders only the loader component when the request is pending', async () => {
    const { store, asFragment } = setupTest();
    store.dispatch(submitPending({ requestId }));
    await sleep();

    expect(asFragment()).toMatchSnapshot();
  });

  it('renders only the success component when the request is successful', async () => {
    const { store, asFragment } = setupTest();
    store.dispatch(submitSuccess({ requestId }));
    await sleep();

    expect(asFragment()).toMatchSnapshot();
  });

  it('renders only the resiliency component when the request has failed', async () => {
    const { store, asFragment } = setupTest();
    store.dispatch(submitFailure({ requestId, error: {} }));
    await sleep();

    expect(asFragment()).toMatchSnapshot();
  });
});
