Skip to content

Commit

Permalink
add unit test
Browse files Browse the repository at this point in the history
  • Loading branch information
pgayvallet committed Oct 5, 2020
1 parent 0689613 commit 70fb894
Showing 1 changed file with 96 additions and 36 deletions.
132 changes: 96 additions & 36 deletions x-pack/plugins/global_search_bar/public/components/search_bar.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,19 @@
*/

import React from 'react';
import { wait } from '@testing-library/react';
import { of } from 'rxjs';
import { waitFor, act } from '@testing-library/react';
import { ReactWrapper } from 'enzyme';
import { of, BehaviorSubject } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { mountWithIntl } from 'test_utils/enzyme_helpers';
import { httpServiceMock, uiSettingsServiceMock } from '../../../../../src/core/public/mocks';
import {
GlobalSearchBatchedResults,
GlobalSearchPluginStart,
GlobalSearchResult,
} from '../../../global_search/public';
import { applicationServiceMock } from '../../../../../src/core/public/mocks';
import { GlobalSearchBatchedResults, GlobalSearchResult } from '../../../global_search/public';
import { globalSearchPluginMock } from '../../../global_search/public/mocks';
import { SearchBar } from '../components/search_bar';
import { SearchBar } from './search_bar';

jest.mock('@elastic/eui/lib/services/accessibility/html_id_generator', () => ({
htmlIdGenerator: () => () => 'mockId',
}));

type Result = { id: string; type: string } | string;

Expand All @@ -38,30 +40,46 @@ const createBatch = (...results: Result[]): GlobalSearchBatchedResults => ({
results: results.map(createResult),
});

jest.mock('@elastic/eui/lib/services/accessibility/html_id_generator', () => ({
htmlIdGenerator: () => () => 'mockId',
}));

const getSelectableProps: any = (component: any) => component.find('EuiSelectable').props();
const getSearchProps: any = (component: any) => component.find('EuiFieldSearch').props();

describe('SearchBar', () => {
let searchService: GlobalSearchPluginStart;
let findSpy: jest.SpyInstance;
const http = httpServiceMock.createSetupContract({ basePath: '/test' });
const basePathUrl = http.basePath.prepend('/plugins/globalSearchBar/assets/');
const uiSettings = uiSettingsServiceMock.createStartContract();
const darkMode = uiSettings.get('theme:darkMode');
let searchService: ReturnType<typeof globalSearchPluginMock.createStartContract>;
let applications: ReturnType<typeof applicationServiceMock.createStartContract>;
const basePathUrl = '/plugins/globalSearchBar/assets/';
const darkMode = false;

let component: ReactWrapper<any>;

beforeEach(() => {
applications = applicationServiceMock.createStartContract();
searchService = globalSearchPluginMock.createStartContract();
findSpy = jest.spyOn(searchService, 'find');
jest.useFakeTimers();
});

const triggerFocus = () => {
component.find('input[data-test-subj="header-search"]').simulate('focus');
};

const update = () => {
act(() => {
jest.runAllTimers();
});
component.update();
};

const simulateTypeChar = async (text: string) => {
await waitFor(() =>
getSearchProps(component).onKeyUpCapture({ currentTarget: { value: text } })
);
};

const getDisplayedOptionsLabel = () => {
return getSelectableProps(component).options.map((option: any) => option.label);
};

it('correctly filters and sorts results', async () => {
const navigate = jest.fn();
findSpy
searchService.find
.mockReturnValueOnce(
of(
createBatch('Discover', 'Canvas'),
Expand All @@ -70,35 +88,37 @@ describe('SearchBar', () => {
)
.mockReturnValueOnce(of(createBatch('Discover', { id: 'My Dashboard', type: 'test' })));

const component = mountWithIntl(
component = mountWithIntl(
<SearchBar
globalSearch={searchService.find}
navigateToUrl={navigate}
navigateToUrl={applications.navigateToUrl}
basePathUrl={basePathUrl}
darkMode={darkMode}
/>
);

expect(findSpy).toHaveBeenCalledTimes(0);
component.find('input[data-test-subj="header-search"]').simulate('focus');
jest.runAllTimers();
component.update();
expect(findSpy).toHaveBeenCalledTimes(1);
expect(findSpy).toHaveBeenCalledWith('', {});
expect(searchService.find).toHaveBeenCalledTimes(0);

triggerFocus();
update();

expect(searchService.find).toHaveBeenCalledTimes(1);
expect(searchService.find).toHaveBeenCalledWith('', {});
expect(getSelectableProps(component).options).toMatchSnapshot();
await wait(() => getSearchProps(component).onKeyUpCapture({ currentTarget: { value: 'd' } }));
jest.runAllTimers();
component.update();

await simulateTypeChar('d');
update();

expect(getSelectableProps(component).options).toMatchSnapshot();
expect(findSpy).toHaveBeenCalledTimes(2);
expect(findSpy).toHaveBeenCalledWith('d', {});
expect(searchService.find).toHaveBeenCalledTimes(2);
expect(searchService.find).toHaveBeenCalledWith('d', {});
});

it('supports keyboard shortcuts', () => {
mountWithIntl(
<SearchBar
globalSearch={searchService.find}
navigateToUrl={jest.fn()}
navigateToUrl={applications.navigateToUrl}
basePathUrl={basePathUrl}
darkMode={darkMode}
/>
Expand All @@ -113,4 +133,44 @@ describe('SearchBar', () => {

expect(document.activeElement).toMatchSnapshot();
});

it('only display results from the last search', async () => {
const firstSearchTrigger = new BehaviorSubject<boolean>(false);
const firstSearch = firstSearchTrigger.pipe(
filter((event) => event),
map(() => {
return createBatch('Discover', 'Canvas');
})
);
const secondSearch = of(createBatch('Visualize', 'Map'));

searchService.find.mockReturnValueOnce(firstSearch).mockReturnValueOnce(secondSearch);

component = mountWithIntl(
<SearchBar
globalSearch={searchService.find}
navigateToUrl={applications.navigateToUrl}
basePathUrl={basePathUrl}
darkMode={darkMode}
/>
);

triggerFocus();
update();

expect(searchService.find).toHaveBeenCalledTimes(1);

await simulateTypeChar('d');
update();

expect(getDisplayedOptionsLabel().length).toBe(2);
expect(getDisplayedOptionsLabel()).toEqual(expect.arrayContaining(['Visualize', 'Map']));

firstSearchTrigger.next(true);

update();

expect(getDisplayedOptionsLabel().length).toBe(2);
expect(getDisplayedOptionsLabel()).toEqual(expect.arrayContaining(['Visualize', 'Map']));
});
});

0 comments on commit 70fb894

Please sign in to comment.