diff --git a/.changeset/pretty-timers-drive.md b/.changeset/pretty-timers-drive.md new file mode 100644 index 0000000000..bf9f57261e --- /dev/null +++ b/.changeset/pretty-timers-drive.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-search-react': patch +--- + +Capture analytics even when number of results is not available, since the total result count is not something that is always available for all search engines and configurations. diff --git a/plugins/search-react/src/context/SearchContext.test.tsx b/plugins/search-react/src/context/SearchContext.test.tsx index 39a9f09ef4..58fde35667 100644 --- a/plugins/search-react/src/context/SearchContext.test.tsx +++ b/plugins/search-react/src/context/SearchContext.test.tsx @@ -479,4 +479,61 @@ describe('SearchContext', () => { }); }); }); + + it('captures analytics events even if number of results does not exist', async () => { + const analyticsApiMock = { + captureEvent: jest.fn(), + } satisfies typeof analyticsApiRef.T; + + searchApiMock.query.mockResolvedValue({ + results: [], + }); + + const { result } = renderHook(() => useSearch(), { + wrapper: ({ children }) => { + const configApiMock = new MockConfigApi({}); + return ( + + + {children} + + + ); + }, + }); + + await waitFor(() => { + expect(result.current).toEqual(expect.objectContaining(initialState)); + }); + + const term = 'term'; + + await act(async () => { + result.current.setTerm(term); + }); + + await waitFor(() => { + expect(searchApiMock.query).toHaveBeenLastCalledWith({ + term: 'term', + types: ['*'], + filters: {}, + }); + expect(analyticsApiMock.captureEvent).toHaveBeenCalledWith({ + action: 'search', + subject: 'term', + value: undefined, + context: { + extension: 'App', + pluginId: 'root', + routeRef: 'unknown', + }, + }); + }); + }); }); diff --git a/plugins/search-react/src/context/SearchContext.tsx b/plugins/search-react/src/context/SearchContext.tsx index 6ce18501d9..f8140e2f19 100644 --- a/plugins/search-react/src/context/SearchContext.tsx +++ b/plugins/search-react/src/context/SearchContext.tsx @@ -138,9 +138,9 @@ const useSearchContextValue = ( pageLimit, pageCursor, }); - if (term && resultSet.numberOfResults !== undefined) { + if (term) { analytics.captureEvent('search', term, { - value: resultSet.numberOfResults, + value: result.value?.numberOfResults ?? undefined, }); } return resultSet;