import React, { FC } from 'react';
import { fireEvent, render, waitFor } from '@testing-library/react';
import {
    CurrentValidationProvider,
    useCurrentValidationContext,
} from '../currentValidationProvider';

const TestComponent: FC = () => {
    const { state, dispatch } = useCurrentValidationContext();
    return (
        <p>
            Current state is:
            <span data-testid="testComponentState">
                {state.currentValidation || 'NONE'}
            </span>
            <button
                data-testid="testComponentStateButton"
                onClick={() =>
                    dispatch({
                        currentValidation: 'foo',
                        triggerScroll: false,
                    })
                }
                type="button"
            >
                Click Me
            </button>
        </p>
    );
};

describe('<CurrentValidationProvider>', () => {
    test('handles context updates', async () => {
        const { getByTestId } = render(
            <CurrentValidationProvider>
                <TestComponent />
            </CurrentValidationProvider>
        );
        const renderedSpan = getByTestId('testComponentState');
        const renderedButton = getByTestId('testComponentStateButton');

        expect(renderedSpan.textContent).toBe('NONE');

        fireEvent.click(renderedButton);

        await waitFor(() => {
            expect(renderedSpan.textContent).toBe('foo');
        });
    });
});
