Skip to content

Commit 817200b

Browse files
committed
test: adding unit tests for waitForInitilization
1 parent 9a8ee5b commit 817200b

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

packages/sdk/browser/__tests__/BrowserClient.test.ts

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -373,4 +373,57 @@ describe('given a mock platform for a BrowserClient', () => {
373373
// With events and goals disabled the only fetch calls should be for polling requests.
374374
expect(platform.requests.fetch.mock.calls.length).toBe(3);
375375
});
376+
377+
it('blocks until the client is ready when waitForInitialization is called', async () => {
378+
const client = makeClient(
379+
'client-side-id',
380+
AutoEnvAttributes.Disabled,
381+
{ streaming: false, logger, diagnosticOptOut: true, sendEvents: false, fetchGoals: false },
382+
platform,
383+
);
384+
385+
const waitPromise = client.waitForInitialization(10);
386+
const identifyPromise = client.identify({ key: 'user-key', kind: 'user' });
387+
388+
await Promise.all([waitPromise, identifyPromise]);
389+
390+
await expect(waitPromise).resolves.toBeUndefined();
391+
await expect(identifyPromise).resolves.toEqual({ status: 'completed' });
392+
});
393+
394+
it('rejects when initialization does not complete before the timeout', async () => {
395+
jest.useRealTimers();
396+
397+
// Create a platform with a delayed fetch response
398+
const delayedPlatform = makeBasicPlatform();
399+
let resolveFetch: (value: any) => void;
400+
const delayedFetchPromise = new Promise((resolve) => {
401+
resolveFetch = resolve;
402+
});
403+
404+
// Mock fetch to return a promise that won't resolve until we explicitly resolve it
405+
delayedPlatform.requests.fetch = jest.fn((_url: string, _options: any) =>
406+
delayedFetchPromise.then(() => ({})),
407+
) as any;
408+
409+
const client = makeClient(
410+
'client-side-id',
411+
AutoEnvAttributes.Disabled,
412+
{ streaming: false, logger, diagnosticOptOut: true, sendEvents: false, fetchGoals: false },
413+
delayedPlatform,
414+
);
415+
416+
// Start identify which will trigger a fetch that won't complete
417+
client.identify({ key: 'user-key', kind: 'user' });
418+
419+
// Call waitForInitialization with a short timeout (0.1 seconds)
420+
const waitPromise = client.waitForInitialization(0.1);
421+
422+
// Verify that waitForInitialization rejects with a timeout error
423+
await expect(waitPromise).rejects.toThrow();
424+
425+
// Clean up: resolve the fetch to avoid hanging promises and restore fake timers
426+
resolveFetch!({});
427+
jest.useFakeTimers();
428+
});
376429
});

0 commit comments

Comments
 (0)