Skip to content

Commit 0692375

Browse files
authored
fix(insights): do not throw if insightsClient is undefined in server environments (#1220)
1 parent 484e31e commit 0692375

File tree

2 files changed

+29
-6
lines changed

2 files changed

+29
-6
lines changed

packages/autocomplete-plugin-algolia-insights/src/__tests__/createAlgoliaInsightsPlugin.test.ts

+23-6
Original file line numberDiff line numberDiff line change
@@ -18,14 +18,20 @@ import {
1818
} from '../../../../test/utils';
1919
import { createAlgoliaInsightsPlugin } from '../createAlgoliaInsightsPlugin';
2020

21-
beforeEach(() => {
22-
(window as any).AlgoliaAnalyticsObject = undefined;
23-
(window as any).aa = undefined;
21+
describe('createAlgoliaInsightsPlugin', () => {
22+
const originalWindow = global.window;
2423

25-
document.body.innerHTML = '';
26-
});
24+
beforeEach(() => {
25+
(window as any).AlgoliaAnalyticsObject = undefined;
26+
(window as any).aa = undefined;
27+
28+
document.body.innerHTML = '';
29+
});
30+
31+
afterEach(() => {
32+
global.window = originalWindow;
33+
});
2734

28-
describe('createAlgoliaInsightsPlugin', () => {
2935
test('has a name', () => {
3036
const plugin = createAlgoliaInsightsPlugin({ insightsClient });
3137

@@ -343,6 +349,17 @@ describe('createAlgoliaInsightsPlugin', () => {
343349
'[Autocomplete]: Could not load search-insights.js. Please load it manually following https://alg.li/insights-autocomplete'
344350
);
345351
});
352+
353+
it('does not throw in server environments', () => {
354+
// @ts-expect-error
355+
delete global.window;
356+
357+
expect(() => {
358+
createPlayground(createAutocomplete, {
359+
plugins: [createAlgoliaInsightsPlugin({})],
360+
});
361+
}).not.toThrow();
362+
});
346363
});
347364

348365
describe('onItemsChange', () => {

packages/autocomplete-plugin-algolia-insights/src/createAlgoliaInsightsPlugin.ts

+6
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,12 @@ export function createAlgoliaInsightsPlugin(
131131
});
132132
}
133133

134+
// We return an empty plugin if `insightsClient` is still undefined at
135+
// this stage, which can happen in server environments.
136+
if (!insightsClient) {
137+
return {};
138+
}
139+
134140
const insights = createSearchInsightsApi(insightsClient);
135141
const previousItems = createRef<AlgoliaInsightsHit[]>([]);
136142

0 commit comments

Comments
 (0)