Skip to content

Commit

Permalink
Fixed use_search_bar unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Machi3mfl committed Dec 12, 2023
1 parent 37f7681 commit 80d1c09
Show file tree
Hide file tree
Showing 2 changed files with 96 additions and 101 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ mockedGetDataPlugin.mockImplementation(
},
},
},
} as Start),
} as Start)
);
///////////////////////////////////////////////////////////

Expand Down Expand Up @@ -77,12 +77,8 @@ describe('[hook] useSearchBarConfiguration', () => {
jest
.spyOn(mockDataPlugin.indexPatterns, 'getDefault')
.mockResolvedValue(mockedDefaultIndexPatternData);
jest
.spyOn(mockDataPlugin.query.filterManager, 'getFilters')
.mockReturnValue([]);
const { result, waitForNextUpdate } = renderHook(() => useSearchBar({
defaultIndexPatternID: 'default-index-pattern',
}));
jest.spyOn(mockDataPlugin.query.filterManager, 'getFilters').mockReturnValue([]);
const { result, waitForNextUpdate } = renderHook(() => useSearchBar({}));
await waitForNextUpdate();
expect(mockDataPlugin.indexPatterns.getDefault).toBeCalled();
expect(result.current.searchBarProps.indexPatterns).toMatchObject([
Expand All @@ -97,21 +93,15 @@ describe('[hook] useSearchBarConfiguration', () => {
id: exampleIndexPatternId,
title: '',
};
jest
.spyOn(mockDataPlugin.indexPatterns, 'get')
.mockResolvedValue(mockedIndexPatternData);
jest.spyOn(mockDataPlugin.indexPatterns, 'get').mockResolvedValue(mockedIndexPatternData);
const { result, waitForNextUpdate } = renderHook(() =>
useSearchBar({
defaultIndexPatternID: 'wazuh-index-pattern',
}),
})
);
await waitForNextUpdate();
expect(mockDataPlugin.indexPatterns.get).toBeCalledWith(
exampleIndexPatternId,
);
expect(result.current.searchBarProps.indexPatterns).toMatchObject([
mockedIndexPatternData,
]);
expect(mockDataPlugin.indexPatterns.get).toBeCalledWith(exampleIndexPatternId);
expect(result.current.searchBarProps.indexPatterns).toMatchObject([mockedIndexPatternData]);
});

it('should show an ERROR message and get the default app index pattern when not found the index pattern data by the ID received', async () => {
Expand All @@ -122,25 +112,19 @@ describe('[hook] useSearchBarConfiguration', () => {
jest
.spyOn(mockDataPlugin.indexPatterns, 'getDefault')
.mockResolvedValue(mockedDefaultIndexPatternData);
jest
.spyOn(mockDataPlugin.query.filterManager, 'getFilters')
.mockReturnValue([]);
jest.spyOn(mockDataPlugin.query.filterManager, 'getFilters').mockReturnValue([]);

// mocking console error to avoid logs in test and check if is called
const mockedConsoleError = jest
.spyOn(console, 'error')
.mockImplementationOnce(() => {});
const mockedConsoleError = jest.spyOn(console, 'error').mockImplementationOnce(() => {});
const { result, waitForNextUpdate } = renderHook(() =>
useSearchBar({
defaultIndexPatternID: 'invalid-index-pattern-id',
}),
})
);

await waitForNextUpdate();
expect(mockDataPlugin.indexPatterns.getDefault).toBeCalled();
expect(mockDataPlugin.indexPatterns.get).toBeCalledWith(
'invalid-index-pattern-id',
);
expect(mockDataPlugin.indexPatterns.get).toBeCalledWith('invalid-index-pattern-id');
expect(result.current.searchBarProps.indexPatterns).toMatchObject([
mockedDefaultIndexPatternData,
]);
Expand All @@ -161,25 +145,52 @@ describe('[hook] useSearchBarConfiguration', () => {
jest
.spyOn(mockDataPlugin.indexPatterns, 'getDefault')
.mockResolvedValue(mockedDefaultIndexPatternData);
jest
.spyOn(mockDataPlugin.query.filterManager, 'getFilters')
.mockReturnValue(defaultFilters);
jest.spyOn(mockDataPlugin.query.filterManager, 'getFilters').mockReturnValue(defaultFilters);
const { result, waitForNextUpdate } = renderHook(() =>
useSearchBar({
filters: defaultFilters,
defaultIndexPatternID: 'wazuh-index-pattern',
}),
})
);

await waitForNextUpdate();

expect(result.current.searchBarProps.filters).toMatchObject(defaultFilters);
expect(mockDataPlugin.query.filterManager.setFilters).toBeCalledWith(
defaultFilters,
);
expect(mockDataPlugin.query.filterManager.setFilters).toBeCalledWith(defaultFilters);
expect(mockDataPlugin.query.filterManager.getFilters).toBeCalled();
});

it('should return and preserve filters when the index pattern received is equal to the index pattern already selected in the app', async () => {
const defaultIndexFilters: Filter[] = [
{
query: 'something to filter',
meta: {
alias: 'filter-mocked',
disabled: false,
negate: true,
},
},
];
jest
.spyOn(mockDataPlugin.indexPatterns, 'getDefault')
.mockResolvedValue(mockedDefaultIndexPatternData);
jest
.spyOn(mockDataPlugin.indexPatterns, 'get')
.mockResolvedValue(mockedDefaultIndexPatternData);
jest
.spyOn(mockDataPlugin.query.filterManager, 'getFilters')
.mockReturnValue(defaultIndexFilters);
const { result, waitForNextUpdate } = renderHook(() =>
useSearchBar({
defaultIndexPatternID: mockedDefaultIndexPatternData.id,
})
);
await waitForNextUpdate();
expect(result.current.searchBarProps.indexPatterns).toMatchObject([
mockedDefaultIndexPatternData,
]);
expect(result.current.searchBarProps.filters).toMatchObject(defaultIndexFilters);
});

it('should return empty filters when the index pattern is NOT equal to the default app index pattern', async () => {
const exampleIndexPatternId = 'wazuh-index-pattern';
const mockedExampleIndexPatternData: Partial<IndexPattern> = {
Expand All @@ -193,13 +204,11 @@ describe('[hook] useSearchBarConfiguration', () => {
jest
.spyOn(mockDataPlugin.indexPatterns, 'getDefault')
.mockResolvedValue(mockedDefaultIndexPatternData);
jest
.spyOn(mockDataPlugin.query.filterManager, 'getFilters')
.mockReturnValue([]);
jest.spyOn(mockDataPlugin.query.filterManager, 'getFilters').mockReturnValue([]);
const { result, waitForNextUpdate } = renderHook(() =>
useSearchBar({
defaultIndexPatternID: exampleIndexPatternId,
}),
})
);
await waitForNextUpdate();
expect(result.current.searchBarProps.indexPatterns).toMatchObject([
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { getDataPlugin } from '../../../../kibana-services';
import { useFilterManager, useQueryManager, useTimeFilter } from '../../hooks';
import { AUTHORIZED_AGENTS } from '../../../../../common/constants';

// Input - types
/// Input - types
type tUseSearchBarCustomInputs = {
defaultIndexPatternID: IIndexPattern['id'];
onFiltersUpdated?: (filters: Filter[]) => void;
Expand All @@ -38,7 +38,6 @@ const useSearchBar = (
props?: tUseSearchBarProps,
): tUserSearchBarResponse => {
// dependencies
const SESSION_STORAGE_FILTERS_NAME = 'wazuh_persistent_searchbar_filters';
const filterManager = useFilterManager().filterManager as FilterManager;
const { filters } = useFilterManager();
const [query, setQuery] = props?.query
Expand All @@ -51,38 +50,29 @@ const useSearchBar = (
useState<IIndexPattern>();

useEffect(() => {
if (filters && filters.length > 0) {
sessionStorage.setItem(
SESSION_STORAGE_FILTERS_NAME,
JSON.stringify(filters),
);
}
initSearchBar();
/**
* When the component is disassembled, the original filters that arrived
* when the component was assembled are added.
*/
return () => {
const storagePreviousFilters = sessionStorage.getItem(
SESSION_STORAGE_FILTERS_NAME,
);
if (storagePreviousFilters) {
const previousFilters = JSON.parse(storagePreviousFilters);
const cleanedFilters = cleanFilters(previousFilters);
filterManager.setFilters(cleanedFilters);
}
};
}, []);

useEffect(() => {
const defaultIndex = props?.defaultIndexPatternID;
/* Filters that do not belong to the default index are filtered */
const cleanedFilters = filters.filter(
filter => filter.meta.index === defaultIndex,
);
if (cleanedFilters.length !== filters.length) {
filterManager.setFilters(cleanedFilters);
}
}, [filters]);

/**
* Initialize the searchbar props with the corresponding index pattern and filters
*/
const initSearchBar = async () => {
setIsLoading(true);
const indexPattern = await getIndexPattern(props?.defaultIndexPatternID);
setIndexPatternSelected(indexPattern);
const initialFilters = props?.filters ?? filters;
filterManager.setFilters(initialFilters);
const filters = await getInitialFilters(indexPattern);
filterManager.setFilters(filters);
setIsLoading(false);
};

Expand All @@ -108,33 +98,44 @@ const useSearchBar = (
};

/**
* Return filters from filters manager.
* Additionally solve the known issue with the auto loaded agent.id filters from the searchbar
* and filters those filters that are not related to the default index pattern
* Return the initial filters considering if hook receives initial filters
* When the default index pattern is the same like the received preserve the filters
* @param indexPattern
* @returns
*/
const getFilters = () => {
const originalFilters = filterManager ? filterManager.getFilters() : [];
return originalFilters.filter(
(filter: Filter) =>
filter?.meta?.controlledBy !== AUTHORIZED_AGENTS && // remove auto loaded agent.id filters
filter?.meta?.index === props?.defaultIndexPatternID,
);
const getInitialFilters = async (indexPattern: IIndexPattern) => {
const indexPatternService = getDataPlugin()
.indexPatterns as IndexPatternsContract;
let initialFilters: Filter[] = [];
if (props?.filters) {
return props?.filters;
}
if (indexPattern) {
// get filtermanager and filters
// if the index is the same, get filters stored
// else clear filters
const defaultIndexPattern =
(await indexPatternService.getDefault()) as IIndexPattern;
initialFilters =
defaultIndexPattern.id === indexPattern.id
? filterManager.getFilters()
: [];
} else {
initialFilters = [];
}
return initialFilters;
};

/**
* Return cleaned filters.
* Clean the known issue with the auto loaded agent.id filters from the searchbar
* and filters those filters that are not related to the default index pattern
* @param previousFilters
* Return filters from filters manager.
* Additionally solve the known issue with the auto loaded agent.id filters from the searchbar
* @returns
*/
const cleanFilters = (previousFilters: Filter[]) => {
return previousFilters.filter(
(filter: Filter) =>
filter?.meta?.controlledBy !== AUTHORIZED_AGENTS &&
filter?.meta?.index !== props?.defaultIndexPatternID,
);
const getFilters = () => {
const filters = filterManager ? filterManager.getFilters() : [];
return filters.filter(
filter => filter.meta.controlledBy !== AUTHORIZED_AGENTS,
); // remove auto loaded agent.id filters
};

/**
Expand All @@ -149,24 +150,9 @@ const useSearchBar = (
dateRangeFrom: timeFilter.from,
dateRangeTo: timeFilter.to,
onFiltersUpdated: (filters: Filter[]) => {
const storagePreviousFilters = sessionStorage.getItem(
SESSION_STORAGE_FILTERS_NAME,
);
/**
* If there are persisted filters, it is necessary to add them when
* updating the filters in the filterManager
*/
if (storagePreviousFilters) {
const previousFilters = JSON.parse(storagePreviousFilters);
const cleanedFilters = cleanFilters(previousFilters);
filterManager.setFilters([...cleanedFilters, ...filters]);

props?.onFiltersUpdated &&
props?.onFiltersUpdated([...cleanedFilters, ...filters]);
} else {
filterManager.setFilters(filters);
props?.onFiltersUpdated && props?.onFiltersUpdated(filters);
}
// its necessary execute setter to apply filters
filterManager.setFilters(filters);
props?.onFiltersUpdated && props?.onFiltersUpdated(filters);
},
onQuerySubmit: (
payload: { dateRange: TimeRange; query?: Query },
Expand Down

0 comments on commit 80d1c09

Please sign in to comment.