---
# System prepended metadata

title: WorkspaceSelect.test.jsx

---

import React from 'react';
import { mount } from 'enzyme';
import Immutable from 'immutable';
import { act } from 'react-dom/test-utils';
import WorkspaceSelect from '../WorkspaceSelect.jsx';
import EventMessageHandler from '../../handlers/EventMessageHandler.js';
import { WORKSPACE_MESSAGE_TIMEOUT, WORKSPACE_SELECT_CONTEXT_VALUES } from '../../Constants.js';
import GoodDataResource from '../../resources/GoodDataResource.js';
import SettingsResource from '../../resources/SettingsResource.js';

jest.mock('../../resources/SettingsResource.js', () => ({
    getConfigurationsCompiled: jest.fn().mockResolvedValue(
        {
            "enabled": true,
            "domainUrl": "https://crm.on.gooddata.com",
            "workspaceId": "pllqbm9e4mls3njwbkv935nzbg1f6uft",
            "homeScreen": {
                "enabled": true,
                "dashboardId": "aaEmOzfow3UT"
            },
            "dashboards": {
                "dashboardId": "aabIUFprDzam"
            },
            "customerSummary": {
                "enabled": true,
                "dashboardId": "aabIUFprDzam",
                "customerIdTargetVariable": "label.conta.iddoclientedaconta"
            },
            "integratedLogin": {
                "enabled": false
            }
        }
    ),
}));
jest.mock('../../resources/GoodDataResource.js', () => ({
    getDefaultWorkspaceTitle: jest.fn().mockResolvedValue('[CRM] WORKSPACE TITLE'),
    getCurrentUserId: jest.fn().mockResolvedValue('/gdc/account/profile/c6b3a174815cecb895f38636c073b21f'),
    getCurrentUserWorkspaces: jest.fn().mockResolvedValue({}),
}));
jest.useFakeTimers();

const MOCKED_EVENT = {
    origin: 'https://analytics.gooddata.com',
    data: {
        type: 'ready',
    },
};
const MOCKED_VALUE = {
    id: '89e3becb-5c51-4e9a-8620-69eac007afbe',
};

// it finds the message's event handler in the addEventListenerSpy
function findHandleEvent(addEventListenerSpy) {
    return addEventListenerSpy.mock.calls.find((call) => {
        if (call[0] === 'message') {
            return call[1];
        }
    })[1];
}

describe('WorkspaceSelect', () => {
    let clearTimeOutSpy;
    let wrapper;
    const onSelectionChange = jest.fn();
    const events = {};

    beforeAll(() => {
        clearTimeOutSpy = jest.spyOn(window, 'clearTimeout').mockImplementation(() => {});
    });

    beforeEach(() => {
        jest.clearAllMocks();
        jest.resetAllMocks();
        jest.restoreAllMocks();

        GoodDataResource.getCurrentUserWorkspaces.mockResolvedValue(Immutable.List([
            {
                id: 'ci30ltrj8y4p8cvemz9a0eszqupg9uzo',
                title: '[CRM] WORKSPACE TITLE 1',
            },
            {
                id: 'swxzva7lp9jy8e9i1sb7a8zjfx5zpdcz',
                title: '[CRM] WORKSPACE TITLE 2',
            }
        ]));
    });

    describe('GoodData events', () => {
        it('should call EventMessageHandler.handleEvent when availableCommands event is triggered', async () => {
            const settingsResourceSpy = jest
                .spyOn(SettingsResource, 'getConfigurationsCompiled')
                .mockResolvedValue({});
            const addEventListenerSpy = jest
                .spyOn(window, 'addEventListener')
                .mockImplementation((event, handle) => {
                    events[event] = handle;
                });
            const eventMessageHandlerSpy = jest
                .spyOn(EventMessageHandler, 'handleEvent')
                .mockReturnValue(WORKSPACE_SELECT_CONTEXT_VALUES.loading);

            await act(async () => {
                wrapper = await mount(<WorkspaceSelect onSelectionChange={onSelectionChange} />);
            });
            await act(async () => {
                const handle = findHandleEvent(addEventListenerSpy);
                await handle(MOCKED_EVENT);
            });

            jestExpect(wrapper.find('WorkspaceSelect').exists()).toBe(true);
            jestExpect(addEventListenerSpy).toBeCalled();
            jestExpect(eventMessageHandlerSpy).toBeCalledWith(MOCKED_EVENT, {});
            jestExpect(settingsResourceSpy).toBeCalledWith();
        });

        it('should call EventMessageHandler.handleEvent when the loaded event is triggered', async () => {
            const settingsResourceSpy = jest
                .spyOn(SettingsResource, 'getConfigurationsCompiled')
                .mockResolvedValue({});
            const addEventListenerSpy = jest
                .spyOn(window, 'addEventListener')
                .mockImplementation((event, handle) => {
                    events[event] = handle;
                });
            const eventMessageHandlerSpy = jest
                .spyOn(EventMessageHandler, 'handleEvent')
                .mockReturnValue(WORKSPACE_SELECT_CONTEXT_VALUES.ready);
            MOCKED_EVENT.data.type = 'loaded';

            await act(async () => {
                wrapper = await mount(<WorkspaceSelect onSelectionChange={onSelectionChange} />);
            });
            await act(async () => {
                const handle = findHandleEvent(addEventListenerSpy);
                await handle(MOCKED_EVENT);
            });

            jestExpect(wrapper.find('WorkspaceSelect').exists()).toBe(true);
            jestExpect(addEventListenerSpy).toBeCalled();
            jestExpect(eventMessageHandlerSpy).toBeCalledWith(MOCKED_EVENT, {});
            jestExpect(settingsResourceSpy).toBeCalledWith();
            jestExpect(clearTimeOutSpy).toBeCalled();
        });

        it('should call clearTimeout event and set contextState to timedOut when 15 seconds pass without receiving the loaded event', async () => {
            jest.useFakeTimers();
            const setTimeoutSpy = jest.spyOn(global, 'setTimeout');
            const settingsResourceSpy = jest
                .spyOn(SettingsResource, 'getConfigurationsCompiled')
                .mockResolvedValue({});
            const addEventListenerSpy = jest
                .spyOn(window, 'addEventListener')
                .mockImplementation((event, handle) => {
                    events[event] = handle;
                });
            const eventMessageHandlerSpy = jest.spyOn(EventMessageHandler, 'handleEvent');

            await act(async () => {
                wrapper = await mount(<WorkspaceSelect onSelectionChange={onSelectionChange} />);
            });
            await act(async () => {
                jest.runAllTimers();
                await wrapper.update();
            });

            jestExpect(setTimeoutSpy).toBeCalledWith(
                jestExpect.any(Function),
                WORKSPACE_MESSAGE_TIMEOUT,
            );
            jestExpect(wrapper.find('WorkspaceSelect').exists()).toBe(true);
            jestExpect(addEventListenerSpy).toBeCalled();
            jestExpect(eventMessageHandlerSpy).not.toBeCalled();
            jestExpect(settingsResourceSpy).toBeCalledWith();
        });
    });

    describe('handleSelectionChange', () => {
        describe('should call onSelectionChange when the handleSelectionChange is triggered', () => {
            it('when the informed value is a string', () => {
                act(() => {
                    wrapper
                        .find('Select')
                        .props()
                        .onChange(MOCKED_VALUE);
                });
                wrapper.update();

                jestExpect(onSelectionChange).toBeCalledWith(MOCKED_VALUE);
                jestExpect(
                    wrapper
                        .find('#workspace-select-component')
                        .first()
                        .prop('value'),
                ).toBe(MOCKED_VALUE);
            });

            it('when the informed value is a null', () => {
                act(() => {
                    wrapper
                        .find('Select')
                        .props()
                        .onChange(null);
                });
                wrapper.update();

                jestExpect(onSelectionChange).toBeCalledWith(null);
                jestExpect(
                    wrapper
                        .find('#workspace-select-component')
                        .first()
                        .prop('value'),
                ).toBe(null);
            });

            it('when the informed value is an empty object', () => {
                act(() => {
                    wrapper
                        .find('Select')
                        .props()
                        .onChange({});
                });
                wrapper.update();

                jestExpect(onSelectionChange).toBeCalledWith({});
                jestExpect(
                    wrapper
                        .find('#workspace-select-component')
                        .first()
                        .prop('value'),
                ).toStrictEqual({});
            });
        });
    });
});
