Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(insights): do not throw if insightsClient is undefined in server environments #1220

Merged
merged 1 commit into from
Nov 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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