import React from 'react';
import { act } from 'react-dom/test-utils';
import '../../../../__mocks__/matchMedia';
import LoadConfiguration from './LoadConfiguration';
import { createStoreProvider } from 'Utils/Test/createStoreProvider';
import { mount } from 'enzyme';
import ServiceLocator from '../../../ServiceLocator';

describe('Shared/Containers/LoadConfiguration', () => {
    test(
        'the error message thrown by loadConfiguration is passed down to the wrapped component,' +
            'entering a code removes it',
        async () => {
            class ConfiguratorService {
                static serviceName = 'ConfiguratorService';
                validateConfiguration = jest.fn();
            }
            ServiceLocator.provide(new ConfiguratorService());

            // use a dummy component, this test focuses on the container
            const LoadConfigurationComponent = () => <div />;

            const { StoreProvider } = createStoreProvider();

            const wrapper = mount(
                <StoreProvider>
                    <LoadConfiguration
                        {...{
                            LoadConfigurationComponent,
                            loadConfiguration: () => {
                                throw new Error('the error message');
                            },
                        }}
                    />
                </StoreProvider>
            );

            const getComponent = () => wrapper.find(LoadConfigurationComponent);

            await act(() =>
                getComponent()
                    .props()
                    .onLoadClick()
            );
            wrapper.update();
            expect(getComponent().props().errorMessage).toBe('the error message');

            getComponent()
                .props()
                .onCodeChange('CODE123');
            wrapper.setProps({}); // force re-render
            expect(getComponent().props().errorMessage).toBe(''); // the error message is gone
            expect(getComponent().props().loadCode).toBe('CODE123');
        }
    );
});
