Skip to content

Commit

Permalink
fix(insights): do not throw if insightsClient is undefined in server …
Browse files Browse the repository at this point in the history
…environments (#1220)
  • Loading branch information
dhayab authored Nov 23, 2023
1 parent 484e31e commit 0692375
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,20 @@ import {
} from '../../../../test/utils';
import { createAlgoliaInsightsPlugin } from '../createAlgoliaInsightsPlugin';

beforeEach(() => {
(window as any).AlgoliaAnalyticsObject = undefined;
(window as any).aa = undefined;
describe('createAlgoliaInsightsPlugin', () => {
const originalWindow = global.window;

document.body.innerHTML = '';
});
beforeEach(() => {
(window as any).AlgoliaAnalyticsObject = undefined;
(window as any).aa = undefined;

document.body.innerHTML = '';
});

afterEach(() => {
global.window = originalWindow;
});

describe('createAlgoliaInsightsPlugin', () => {
test('has a name', () => {
const plugin = createAlgoliaInsightsPlugin({ insightsClient });

Expand Down Expand Up @@ -343,6 +349,17 @@ describe('createAlgoliaInsightsPlugin', () => {
'[Autocomplete]: Could not load search-insights.js. Please load it manually following https://alg.li/insights-autocomplete'
);
});

it('does not throw in server environments', () => {
// @ts-expect-error
delete global.window;

expect(() => {
createPlayground(createAutocomplete, {
plugins: [createAlgoliaInsightsPlugin({})],
});
}).not.toThrow();
});
});

describe('onItemsChange', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,12 @@ export function createAlgoliaInsightsPlugin(
});
}

// We return an empty plugin if `insightsClient` is still undefined at
// this stage, which can happen in server environments.
if (!insightsClient) {
return {};
}

const insights = createSearchInsightsApi(insightsClient);
const previousItems = createRef<AlgoliaInsightsHit[]>([]);

Expand Down

0 comments on commit 0692375

Please sign in to comment.