From 53e36c1de2af5a0f1f15a41b9f006c83ebda2c89 Mon Sep 17 00:00:00 2001 From: arvinxx Date: Wed, 10 Jan 2024 13:20:30 +0800 Subject: [PATCH] :bug: fix: resolve undefined when plugin is not in LobeChat --- src/client/lobeChat.ts | 9 +++++++++ tests/client/lobeChat.test.ts | 21 ++++++++++++++++++++- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/src/client/lobeChat.ts b/src/client/lobeChat.ts index c31783c..3bc2414 100644 --- a/src/client/lobeChat.ts +++ b/src/client/lobeChat.ts @@ -25,12 +25,21 @@ class LobeChat { resolve(undefined as any); return; } + + const timer = setTimeout(() => { + resolve(undefined as any); + // eslint-disable-next-line @typescript-eslint/no-use-before-define + window.removeEventListener('message', receiverData); + }, 1000); + const receiverData = (e: MessageEvent) => { if (e.data.type === PluginChannel.initStandalonePlugin) { // TODO: drop e.data.props in v2 const payload: PluginRequestPayload = e.data.payload || e.data.props; const func = payload.apiName; const args = JSON.parse(payload.arguments || '{}'); + clearTimeout(timer); + resolve({ arguments: args, name: func, diff --git a/tests/client/lobeChat.test.ts b/tests/client/lobeChat.test.ts index 319591a..5942dce 100644 --- a/tests/client/lobeChat.test.ts +++ b/tests/client/lobeChat.test.ts @@ -91,7 +91,7 @@ describe('lobeChat', () => { }); }); - describe('fetchPluginPayload', () => { + describe('getPluginPayload', () => { it('should resolve undefined when window is undefined', async () => { const originalWindow = global.window; global.window = undefined as any; @@ -172,6 +172,25 @@ describe('lobeChat', () => { expect.any(Function), ); }); + + it('should resolve undefined if message is not received within timeout', async () => { + vi.useFakeTimers(); + + const promise = lobeChat.getPluginPayload(); + + // Fast-forward until all timers have been executed + vi.runAllTimers(); + + const result = await promise; + + expect(result).toBeUndefined(); + expect(global.window.removeEventListener).toHaveBeenCalledWith( + 'message', + expect.any(Function), + ); + + vi.useRealTimers(); + }); }); describe('fetchPluginSettings', () => {